@monogrid/gainmap-js 3.7.0 → 3.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/{GainMapNode-DtVNqKtN.js → GainMapNode-Cz4_NIGH.js} +1 -1
- package/dist/{GainMapNode-CntuYSg-.js → GainMapNode-Dl8yqSVg.js} +5 -1
- package/dist/{Loader-D82gF-Rq.js → Loader-BNe3xn0l.js} +2 -2
- package/dist/{Loader-EFF6JZel.js → Loader-DcZ7MyM7.js} +2 -2
- package/dist/{QuadRenderer-DD6leG7y.js → QuadRenderer-BOS9Aas1.js} +1 -1
- package/dist/{QuadRenderer-DoK2pW5M.js → QuadRenderer-BqD-oQ7D.js} +1 -1
- package/dist/{_commonjsHelpers-C0JuzTK_.js → _commonjsHelpers-DrNnMDE-.js} +1 -1
- package/dist/{_commonjsHelpers-p2JmW4Hh.js → _commonjsHelpers-pGJUN9hi.js} +1 -1
- package/dist/{compress-PmebyFxR.js → compress-DA31yhmz.js} +1 -1
- package/dist/{compress-BTsSIi_B.js → compress-goZ8TdVo.js} +1 -1
- package/dist/core/webgpu/RenderTargetNode.d.ts +4 -0
- package/dist/decode/webgpu/index.d.ts +1 -0
- package/dist/decode.js +5 -5
- package/dist/decode.min.js +2 -2
- package/dist/decode.umd.cjs +1 -1
- package/dist/decode.umd.min.cjs +1 -1
- package/dist/decode.webgpu.js +6 -6
- package/dist/decode.webgpu.min.js +2 -2
- package/dist/decode.webgpu.umd.cjs +133 -128
- package/dist/decode.webgpu.umd.min.cjs +2 -2
- package/dist/encode.js +4 -4
- package/dist/encode.min.js +2 -2
- package/dist/encode.umd.cjs +1 -1
- package/dist/encode.umd.min.cjs +1 -1
- package/dist/encode.webgpu.js +6 -5
- package/dist/encode.webgpu.min.js +2 -2
- package/dist/encode.webgpu.umd.cjs +7 -2
- package/dist/encode.webgpu.umd.min.cjs +2 -2
- package/dist/{get-data-texture-DkHkbczN.js → get-data-texture-CpszSMzv.js} +1 -1
- package/dist/{get-data-texture-CkaFVcv-.js → get-data-texture-Dlg6zKSG.js} +1 -1
- package/dist/{iso-gainmap-metadata-Bx6ha9th.js → iso-gainmap-metadata-BwLnWVQ-.js} +1 -1
- package/dist/{iso-gainmap-metadata-BJxZGPtk.js → iso-gainmap-metadata-CuDCCi9d.js} +1 -1
- package/dist/libultrahdr.js +2 -2
- package/dist/libultrahdr.min.js +2 -2
- package/dist/libultrahdr.umd.cjs +1 -1
- package/dist/libultrahdr.umd.min.cjs +1 -1
- package/dist/worker-interface.js +2 -2
- package/dist/worker-interface.min.js +2 -2
- package/dist/worker-interface.umd.cjs +1 -1
- package/dist/worker-interface.umd.min.cjs +1 -1
- package/dist/worker.js +3 -3
- package/dist/worker.min.js +2 -2
- package/dist/worker.umd.cjs +1 -1
- package/dist/worker.umd.min.cjs +1 -1
- package/package.json +1 -1
|
@@ -1,13 +1,140 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.7.
|
|
2
|
+
* @monogrid/gainmap-js v3.7.1
|
|
3
3
|
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
(function (global, factory) {
|
|
7
|
-
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three'), require('three
|
|
8
|
-
typeof define === 'function' && define.amd ? define(['exports', 'three', 'three
|
|
9
|
-
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@monogrid/gainmap-js"] = {}, global
|
|
10
|
-
})(this, (function (exports,
|
|
7
|
+
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three/webgpu'), require('three'), require('three/tsl')) :
|
|
8
|
+
typeof define === 'function' && define.amd ? define(['exports', 'three/webgpu', 'three', 'three/tsl'], factory) :
|
|
9
|
+
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@monogrid/gainmap-js"] = {}, global["three/webgpu"], global.three, global["three/tsl"]));
|
|
10
|
+
})(this, (function (exports, webgpu, three, tsl) { 'use strict';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Base class for TSL texture nodes whose texture is a render target, filled by rendering a full screen quad.
|
|
14
|
+
*
|
|
15
|
+
* The quad is rendered only when something changed since the last render:
|
|
16
|
+
* subclasses list what the result depends on in {@link RenderTargetNode._getState}
|
|
17
|
+
* and the other render target nodes they read from in {@link RenderTargetNode._getDependencies}.
|
|
18
|
+
* Sampling the node costs a single texture read, like any other texture.
|
|
19
|
+
*
|
|
20
|
+
* The node renders itself before rendering whenever it is part of a rendered node graph
|
|
21
|
+
* (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`)
|
|
22
|
+
* call {@link RenderTargetNode.render} yourself.
|
|
23
|
+
*
|
|
24
|
+
* @category Nodes
|
|
25
|
+
* @group Nodes
|
|
26
|
+
*/
|
|
27
|
+
class RenderTargetNode extends webgpu.TextureNode {
|
|
28
|
+
/**
|
|
29
|
+
* The render target holding the result
|
|
30
|
+
*/
|
|
31
|
+
renderTarget;
|
|
32
|
+
/**
|
|
33
|
+
* Incremented every time the render target is rendered,
|
|
34
|
+
* nodes depending on this one use it to know when to render again
|
|
35
|
+
*/
|
|
36
|
+
revision = 0;
|
|
37
|
+
_quadMesh;
|
|
38
|
+
_material;
|
|
39
|
+
// filled by RendererUtils.resetRendererState
|
|
40
|
+
_rendererState = {};
|
|
41
|
+
_state = [];
|
|
42
|
+
/**
|
|
43
|
+
* @param material the material rendered on the full screen quad
|
|
44
|
+
* @param renderTargetOptions options of the render target, it is created with a 1x1 size
|
|
45
|
+
* and resized to {@link RenderTargetNode.width} x {@link RenderTargetNode.height} before rendering
|
|
46
|
+
*/
|
|
47
|
+
constructor(material, renderTargetOptions) {
|
|
48
|
+
const renderTarget = new webgpu.RenderTarget(1, 1, { depthBuffer: false, ...renderTargetOptions });
|
|
49
|
+
super(renderTarget.texture);
|
|
50
|
+
this.renderTarget = renderTarget;
|
|
51
|
+
this.updateBeforeType = webgpu.NodeUpdateType.RENDER;
|
|
52
|
+
this._material = material;
|
|
53
|
+
this._quadMesh = new webgpu.QuadMesh(material);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Render target nodes read by this node, rendered (if needed) before this one
|
|
57
|
+
*/
|
|
58
|
+
_getDependencies() { return []; }
|
|
59
|
+
/**
|
|
60
|
+
* Called after the render target has been rendered
|
|
61
|
+
*/
|
|
62
|
+
_onRender() { }
|
|
63
|
+
/**
|
|
64
|
+
* Forces a render the next time {@link RenderTargetNode.render} is called,
|
|
65
|
+
* use it when something the node can't track changed (e.g. a custom input node)
|
|
66
|
+
*/
|
|
67
|
+
invalidate() {
|
|
68
|
+
this._state = [];
|
|
69
|
+
return this;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Renders into {@link RenderTargetNode.renderTarget}, only if something changed since the last render.
|
|
73
|
+
*
|
|
74
|
+
* Called automatically when the node is part of a rendered node graph.
|
|
75
|
+
*
|
|
76
|
+
* @param renderer
|
|
77
|
+
* @returns `true` if the render target was rendered
|
|
78
|
+
*/
|
|
79
|
+
render(renderer) {
|
|
80
|
+
const dependencies = this._getDependencies();
|
|
81
|
+
for (const dependency of dependencies)
|
|
82
|
+
dependency.render(renderer);
|
|
83
|
+
const { width, height } = this;
|
|
84
|
+
// not ready yet
|
|
85
|
+
if (width === 0 || height === 0)
|
|
86
|
+
return false;
|
|
87
|
+
const state = [width, height, ...dependencies.map(d => d.revision), ...this._getState()];
|
|
88
|
+
if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
|
|
89
|
+
return false;
|
|
90
|
+
this._state = state;
|
|
91
|
+
if (this.renderTarget.width !== width || this.renderTarget.height !== height)
|
|
92
|
+
this.renderTarget.setSize(width, height);
|
|
93
|
+
webgpu.RendererUtils.resetRendererState(renderer, this._rendererState);
|
|
94
|
+
renderer.setRenderTarget(this.renderTarget);
|
|
95
|
+
this._quadMesh.render(renderer);
|
|
96
|
+
webgpu.RendererUtils.restoreRendererState(renderer, this._rendererState);
|
|
97
|
+
this.revision++;
|
|
98
|
+
this._onRender();
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Called by three.js before rendering, renders the node when needed
|
|
103
|
+
* @internal
|
|
104
|
+
*/
|
|
105
|
+
updateBefore(frame) {
|
|
106
|
+
if (frame.renderer)
|
|
107
|
+
this.render(frame.renderer);
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
set value(value) {
|
|
111
|
+
if (this.renderTarget && value !== this.renderTarget.texture) {
|
|
112
|
+
throw new Error(`${this.constructor.name}: the value of this node is its render target texture and can't be replaced`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
get value() {
|
|
116
|
+
return this.renderTarget?.texture;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
|
|
120
|
+
* they keep it updated before rendering as well
|
|
121
|
+
*/
|
|
122
|
+
clone() {
|
|
123
|
+
const node = new webgpu.TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
|
|
124
|
+
node.sampler = this.sampler;
|
|
125
|
+
node.updateBeforeType = webgpu.NodeUpdateType.RENDER;
|
|
126
|
+
node.updateBefore = (frame) => this.updateBefore(frame);
|
|
127
|
+
return node;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Disposes the render target and the material
|
|
131
|
+
*/
|
|
132
|
+
dispose() {
|
|
133
|
+
this.renderTarget.dispose();
|
|
134
|
+
this._material.dispose();
|
|
135
|
+
super.dispose();
|
|
136
|
+
}
|
|
137
|
+
}
|
|
11
138
|
|
|
12
139
|
/**
|
|
13
140
|
* Shared decode implementation factory
|
|
@@ -1273,129 +1400,6 @@
|
|
|
1273
1400
|
}
|
|
1274
1401
|
}
|
|
1275
1402
|
|
|
1276
|
-
/**
|
|
1277
|
-
* Base class for TSL texture nodes whose texture is a render target, filled by rendering a full screen quad.
|
|
1278
|
-
*
|
|
1279
|
-
* The quad is rendered only when something changed since the last render:
|
|
1280
|
-
* subclasses list what the result depends on in {@link RenderTargetNode._getState}
|
|
1281
|
-
* and the other render target nodes they read from in {@link RenderTargetNode._getDependencies}.
|
|
1282
|
-
* Sampling the node costs a single texture read, like any other texture.
|
|
1283
|
-
*
|
|
1284
|
-
* The node renders itself before rendering whenever it is part of a rendered node graph
|
|
1285
|
-
* (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`)
|
|
1286
|
-
* call {@link RenderTargetNode.render} yourself.
|
|
1287
|
-
*
|
|
1288
|
-
* @category Nodes
|
|
1289
|
-
* @group Nodes
|
|
1290
|
-
*/
|
|
1291
|
-
class RenderTargetNode extends webgpu.TextureNode {
|
|
1292
|
-
/**
|
|
1293
|
-
* The render target holding the result
|
|
1294
|
-
*/
|
|
1295
|
-
renderTarget;
|
|
1296
|
-
/**
|
|
1297
|
-
* Incremented every time the render target is rendered,
|
|
1298
|
-
* nodes depending on this one use it to know when to render again
|
|
1299
|
-
*/
|
|
1300
|
-
revision = 0;
|
|
1301
|
-
_quadMesh;
|
|
1302
|
-
_material;
|
|
1303
|
-
// filled by RendererUtils.resetRendererState
|
|
1304
|
-
_rendererState = {};
|
|
1305
|
-
_state = [];
|
|
1306
|
-
/**
|
|
1307
|
-
* @param material the material rendered on the full screen quad
|
|
1308
|
-
* @param renderTargetOptions options of the render target, it is created with a 1x1 size
|
|
1309
|
-
* and resized to {@link RenderTargetNode.width} x {@link RenderTargetNode.height} before rendering
|
|
1310
|
-
*/
|
|
1311
|
-
constructor(material, renderTargetOptions) {
|
|
1312
|
-
const renderTarget = new webgpu.RenderTarget(1, 1, { depthBuffer: false, ...renderTargetOptions });
|
|
1313
|
-
super(renderTarget.texture);
|
|
1314
|
-
this.renderTarget = renderTarget;
|
|
1315
|
-
this.updateBeforeType = webgpu.NodeUpdateType.RENDER;
|
|
1316
|
-
this._material = material;
|
|
1317
|
-
this._quadMesh = new webgpu.QuadMesh(material);
|
|
1318
|
-
}
|
|
1319
|
-
/**
|
|
1320
|
-
* Render target nodes read by this node, rendered (if needed) before this one
|
|
1321
|
-
*/
|
|
1322
|
-
_getDependencies() { return []; }
|
|
1323
|
-
/**
|
|
1324
|
-
* Called after the render target has been rendered
|
|
1325
|
-
*/
|
|
1326
|
-
_onRender() { }
|
|
1327
|
-
/**
|
|
1328
|
-
* Forces a render the next time {@link RenderTargetNode.render} is called,
|
|
1329
|
-
* use it when something the node can't track changed (e.g. a custom input node)
|
|
1330
|
-
*/
|
|
1331
|
-
invalidate() {
|
|
1332
|
-
this._state = [];
|
|
1333
|
-
return this;
|
|
1334
|
-
}
|
|
1335
|
-
/**
|
|
1336
|
-
* Renders into {@link RenderTargetNode.renderTarget}, only if something changed since the last render.
|
|
1337
|
-
*
|
|
1338
|
-
* Called automatically when the node is part of a rendered node graph.
|
|
1339
|
-
*
|
|
1340
|
-
* @param renderer
|
|
1341
|
-
* @returns `true` if the render target was rendered
|
|
1342
|
-
*/
|
|
1343
|
-
render(renderer) {
|
|
1344
|
-
const dependencies = this._getDependencies();
|
|
1345
|
-
for (const dependency of dependencies)
|
|
1346
|
-
dependency.render(renderer);
|
|
1347
|
-
const { width, height } = this;
|
|
1348
|
-
// not ready yet
|
|
1349
|
-
if (width === 0 || height === 0)
|
|
1350
|
-
return false;
|
|
1351
|
-
const state = [width, height, ...dependencies.map(d => d.revision), ...this._getState()];
|
|
1352
|
-
if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
|
|
1353
|
-
return false;
|
|
1354
|
-
this._state = state;
|
|
1355
|
-
if (this.renderTarget.width !== width || this.renderTarget.height !== height)
|
|
1356
|
-
this.renderTarget.setSize(width, height);
|
|
1357
|
-
webgpu.RendererUtils.resetRendererState(renderer, this._rendererState);
|
|
1358
|
-
renderer.setRenderTarget(this.renderTarget);
|
|
1359
|
-
this._quadMesh.render(renderer);
|
|
1360
|
-
webgpu.RendererUtils.restoreRendererState(renderer, this._rendererState);
|
|
1361
|
-
this.revision++;
|
|
1362
|
-
this._onRender();
|
|
1363
|
-
return true;
|
|
1364
|
-
}
|
|
1365
|
-
updateBefore(frame) {
|
|
1366
|
-
if (frame.renderer)
|
|
1367
|
-
this.render(frame.renderer);
|
|
1368
|
-
return undefined;
|
|
1369
|
-
}
|
|
1370
|
-
set value(value) {
|
|
1371
|
-
if (this.renderTarget && value !== this.renderTarget.texture) {
|
|
1372
|
-
throw new Error(`${this.constructor.name}: the value of this node is its render target texture and can't be replaced`);
|
|
1373
|
-
}
|
|
1374
|
-
}
|
|
1375
|
-
get value() {
|
|
1376
|
-
return this.renderTarget?.texture;
|
|
1377
|
-
}
|
|
1378
|
-
/**
|
|
1379
|
-
* Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
|
|
1380
|
-
* they keep it updated before rendering as well
|
|
1381
|
-
*/
|
|
1382
|
-
clone() {
|
|
1383
|
-
const node = new webgpu.TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
|
|
1384
|
-
node.sampler = this.sampler;
|
|
1385
|
-
node.updateBeforeType = webgpu.NodeUpdateType.RENDER;
|
|
1386
|
-
node.updateBefore = (frame) => this.updateBefore(frame);
|
|
1387
|
-
return node;
|
|
1388
|
-
}
|
|
1389
|
-
/**
|
|
1390
|
-
* Disposes the render target and the material
|
|
1391
|
-
*/
|
|
1392
|
-
dispose() {
|
|
1393
|
-
this.renderTarget.dispose();
|
|
1394
|
-
this._material.dispose();
|
|
1395
|
-
super.dispose();
|
|
1396
|
-
}
|
|
1397
|
-
}
|
|
1398
|
-
|
|
1399
1403
|
// max half float value
|
|
1400
1404
|
const HALF_FLOAT_MAX = 65504;
|
|
1401
1405
|
/**
|
|
@@ -1957,6 +1961,7 @@
|
|
|
1957
1961
|
exports.LoaderBaseShared = LoaderBaseShared;
|
|
1958
1962
|
exports.MPFExtractor = MPFExtractor;
|
|
1959
1963
|
exports.QuadRenderer = QuadRenderer;
|
|
1964
|
+
exports.RenderTargetNode = RenderTargetNode;
|
|
1960
1965
|
exports.XMPMetadataNotFoundError = XMPMetadataNotFoundError;
|
|
1961
1966
|
exports.createDecodeFunction = createDecodeFunction;
|
|
1962
1967
|
exports.createTextures = createTextures;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.7.
|
|
2
|
+
* @monogrid/gainmap-js v3.7.1
|
|
3
3
|
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
4
|
*/
|
|
5
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three"),require("three/webgpu"),require("three/tsl")):"function"==typeof define&&define.amd?define(["exports","three","three/webgpu","three/tsl"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@monogrid/gainmap-js"]={},e.three,e["three/webgpu"],e["three/tsl"])}(this,function(e,t,r,a){"use strict";function i(e){return r=>{const{sdr:a,gainMap:i,renderer:n}=r;a.colorSpace!==t.SRGBColorSpace&&(console.warn("SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically"),a.colorSpace=t.SRGBColorSpace),a.needsUpdate=!0,i.colorSpace!==t.LinearSRGBColorSpace&&(console.warn("Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically"),i.colorSpace=t.LinearSRGBColorSpace),i.needsUpdate=!0;const s=e.createMaterial({...r,sdr:a,gainMap:i});return e.createQuadRenderer({width:a.image.width,height:a.image.height,type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,material:s,renderer:n,renderTargetOptions:r.renderTargetOptions})}}class n extends Error{}class s extends Error{}const o=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=0;const a=()=>{const e=t.getUint16(r);return r+=2,e},i=()=>{const e=t.getUint32(r);return r+=4,e},n=a();if(0!==n)throw new Error(`Unsupported ISO 21496-1 minimum_version ${n}`);a();const s=t.getUint8(r++);if(4&s)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const o=128&s?3:1,d=8&s?i():void 0,h=e=>{const a=e?(()=>{const e=t.getInt32(r);return r+=4,e})():i(),n=d??i();if(0===n)throw new Error("Invalid ISO 21496-1 fraction with zero denominator");return a/n},p=h(!1),g=h(!1);if(p>g)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const c=[],l=[],m=[],u=[],f=[];for(let e=0;e<o;e++)c.push(h(!0)),l.push(h(!0)),m.push(h(!1)),u.push(h(!0)),f.push(h(!0));const M=e=>3===o?e:[e[0],e[0],e[0]];return{gainMapMin:M(c),gainMapMax:M(l),gamma:M(m),offsetSdr:M(u),offsetHdr:M(f),hdrCapacityMin:p,hdrCapacityMax:g}},d=Array.from("urn:iso:std:iso:ts:21496:-1\0",e=>e.charCodeAt(0)),h=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=4+d.length;for(let a=0;a+r<e.length;a++){if(255!==e[a]||226!==e[a+1])continue;if(!d.every((t,r)=>e[a+4+r]===t))continue;const i=Math.min(e.length,a+2+t.getUint16(a+2));if(!(i-(a+r)<=4))try{return o(e.subarray(a+r,i))}catch(e){return}}},p=(e,t,r)=>{const a=new RegExp(`${t}="([^"]*)"`,"i").exec(e);if(a)return a[1];const i=new RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`,"i").exec(e);if(i){const e=i[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);return e&&3===e.length?e.map(e=>e.replace(/<\/?rdf:li>/g,"")):i[1].trim()}if(void 0!==r)return r;throw new Error(`Can't find ${t} in gainmap metadata`)},g=e=>{let t;t="undefined"!=typeof TextDecoder?(new TextDecoder).decode(e):e.toString();let r=t.indexOf("<x:xmpmeta");for(;-1!==r;){const e=t.indexOf("x:xmpmeta>",r),a=t.slice(r,e+10);try{const e=p(a,"hdrgm:GainMapMin","0"),t=p(a,"hdrgm:GainMapMax"),r=p(a,"hdrgm:Gamma","1"),i=p(a,"hdrgm:OffsetSDR","0.015625"),n=p(a,"hdrgm:OffsetHDR","0.015625"),s=/hdrgm:HDRCapacityMin="([^"]*)"/.exec(a),o=s?s[1]:"0",d=/hdrgm:HDRCapacityMax="([^"]*)"/.exec(a);if(!d)throw new Error("Incomplete gainmap metadata");const h=d[1];return{gainMapMin:Array.isArray(e)?e.map(e=>parseFloat(e)):[parseFloat(e),parseFloat(e),parseFloat(e)],gainMapMax:Array.isArray(t)?t.map(e=>parseFloat(e)):[parseFloat(t),parseFloat(t),parseFloat(t)],gamma:Array.isArray(r)?r.map(e=>parseFloat(e)):[parseFloat(r),parseFloat(r),parseFloat(r)],offsetSdr:Array.isArray(i)?i.map(e=>parseFloat(e)):[parseFloat(i),parseFloat(i),parseFloat(i)],offsetHdr:Array.isArray(n)?n.map(e=>parseFloat(e)):[parseFloat(n),parseFloat(n),parseFloat(n)],hdrCapacityMin:parseFloat(o),hdrCapacityMax:parseFloat(h)}}catch(e){}r=t.indexOf("<x:xmpmeta",e)}};class c{options;constructor(e){this.options={debug:!(!e||void 0===e.debug)&&e.debug,extractFII:!e||void 0===e.extractFII||e.extractFII,extractNonFII:!e||void 0===e.extractNonFII||e.extractNonFII}}extract(e){return new Promise((t,r)=>{const a=this.options.debug,i=new DataView(e.buffer);if(65496!==i.getUint16(0))return void r(new Error("Not a valid jpeg"));const n=i.byteLength;let s,o=2,d=0;for(;o<n;){if(++d>250)return void r(new Error(`Found no marker after ${d} loops 😵`));if(255!==i.getUint8(o))return void r(new Error(`Not a valid marker at offset 0x${o.toString(16)}, found: 0x${i.getUint8(o).toString(16)}`));if(s=i.getUint8(o+1),a&&console.log(`Marker: ${s.toString(16)}`),226===s){a&&console.log("Found APP2 marker (0xffe2)");const e=o+4;if(1297106432===i.getUint32(e)){const a=e+4;let n;if(18761===i.getUint16(a))n=!1;else{if(19789!==i.getUint16(a))return void r(new Error("No valid endianness marker found in TIFF header"));n=!0}if(42!==i.getUint16(a+2,!n))return void r(new Error("Not valid TIFF data! (no 0x002A marker)"));const s=i.getUint32(a+4,!n);if(s<8)return void r(new Error("Not valid TIFF data! (First offset less than 8)"));const o=a+s,d=i.getUint16(o,!n),h=o+2;let p=0;for(let e=h;e<h+12*d;e+=12)45057===i.getUint16(e,!n)&&(p=i.getUint32(e+8,!n));const g=o+2+12*d+4,c=[];for(let e=g;e<g+16*p;e+=16){const t={MPType:i.getUint32(e,!n),size:i.getUint32(e+4,!n),dataOffset:i.getUint32(e+8,!n),dependantImages:i.getUint32(e+12,!n),start:-1,end:-1,isFII:!1};t.dataOffset?(t.start=a+t.dataOffset,t.isFII=!1):(t.start=0,t.isFII=!0),t.end=t.start+t.size,c.push(t)}if(this.options.extractNonFII&&c.length){const e=new Blob([i]),r=[];for(const t of c){if(t.isFII&&!this.options.extractFII)continue;const a=e.slice(t.start,t.end+1,"image/jpeg");r.push(a)}t(r)}}}o+=2+i.getUint16(o+2)}})}}const l=async e=>{const t=h(e)??g(e);if(!t)throw new s("Gain map XMP metadata not found");const r=new c({extractFII:!0,extractNonFII:!0}),a=await r.extract(e);if(2!==a.length)throw new n("Gain map recovery image not found");return{sdr:new Uint8Array(await a[0].arrayBuffer()),gainMap:new Uint8Array(await a[1].arrayBuffer()),metadata:t}},m=e=>new Promise((t,r)=>{const a=document.createElement("img");a.onload=()=>{t(a)},a.onerror=e=>{r(e)},a.src=URL.createObjectURL(e)}),u=async(e,t,r)=>{const a=t?new Blob([t],{type:"image/jpeg"}):void 0,i=new Blob([e],{type:"image/jpeg"});let n,s,o=!1;if("undefined"==typeof createImageBitmap){const e=await Promise.all([a?m(a):Promise.resolve(void 0),m(i)]);s=e[0],n=e[1],o="flipY"===r}else{const e=await Promise.all([a?createImageBitmap(a,{imageOrientation:r||"flipY"}):Promise.resolve(void 0),createImageBitmap(i,{imageOrientation:r||"flipY"})]);s=e[0],n=e[1]}return{sdrImage:n,gainMapImage:s,needsFlip:o}},f=(e,r,a)=>{const i=new t.Texture(r||new ImageData(2,2),t.UVMapping,t.ClampToEdgeWrapping,t.ClampToEdgeWrapping,t.LinearFilter,t.LinearMipMapLinearFilter,t.RGBAFormat,t.UnsignedByteType,1,t.LinearSRGBColorSpace);i.flipY=a,i.needsUpdate=!0;const n=new t.Texture(e,t.UVMapping,t.ClampToEdgeWrapping,t.ClampToEdgeWrapping,t.LinearFilter,t.LinearMipMapLinearFilter,t.RGBAFormat,t.UnsignedByteType,1,t.SRGBColorSpace);return n.flipY=a,n.needsUpdate=!0,{gainMap:i,sdr:n}};class M extends t.Loader{_renderer;_renderTargetOptions;_internalLoadingManager;_config;constructor(e,r){super(r),this._config=e,e.renderer&&(this._renderer=e.renderer),this._internalLoadingManager=new t.LoadingManager}setRenderer(e){return this._renderer=e,this}setRenderTargetOptions(e){return this._renderTargetOptions=e,this}prepareQuadRenderer(){this._renderer||console.warn("WARNING: A Renderer was not passed to this Loader constructor or in setRenderer, the result of this Loader will need to be converted to a Data Texture with toDataTexture() before you can use it in your renderer.");const e=this._config.createMaterial({gainMapMax:[1,1,1],gainMapMin:[0,0,0],gamma:[1,1,1],offsetHdr:[1,1,1],offsetSdr:[1,1,1],hdrCapacityMax:1,hdrCapacityMin:0,maxDisplayBoost:1,gainMap:new t.Texture,sdr:new t.Texture});return this._config.createQuadRenderer({width:16,height:16,type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,material:e,renderer:this._renderer,renderTargetOptions:this._renderTargetOptions})}processImages(e,t,r){return u(e,t,r)}createTextures(e,t,r){return f(e,t,r)}updateQuadRenderer(e,t,r,a,i){e.width=t.width,e.height=t.height,e.material.gainMap=r,e.material.sdr=a,e.material.gainMapMin=i.gainMapMin,e.material.gainMapMax=i.gainMapMax,e.material.offsetHdr=i.offsetHdr,e.material.offsetSdr=i.offsetSdr,e.material.gamma=i.gamma,e.material.hdrCapacityMin=i.hdrCapacityMin,e.material.hdrCapacityMax=i.hdrCapacityMax,e.material.maxDisplayBoost=Math.pow(2,i.hdrCapacityMax),e.material.needsUpdate=!0}}class y{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(e){this._width=e.width,this._height=e.height,this._type=e.type,this._colorSpace=e.colorSpace;const t={format:r.RGBAFormat,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:void 0!==e.renderTargetOptions?.anisotropy?e.renderTargetOptions?.anisotropy:1,generateMipmaps:void 0!==e.renderTargetOptions?.generateMipmaps&&e.renderTargetOptions?.generateMipmaps,magFilter:void 0!==e.renderTargetOptions?.magFilter?e.renderTargetOptions?.magFilter:r.LinearFilter,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:r.LinearFilter,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:r.ClampToEdgeWrapping,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:r.ClampToEdgeWrapping};this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=y.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new r.Scene,this._camera=new r.OrthographicCamera,this._camera.position.set(0,0,10),this._camera.left=-.5,this._camera.right=.5,this._camera.top=.5,this._camera.bottom=-.5,this._camera.updateProjectionMatrix(),this._quad=new r.Mesh(new r.PlaneGeometry,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new r.RenderTarget(this.width,this.height,t),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:r.UVMapping}static instantiateRenderer(){const e=new r.WebGPURenderer;return e.setSize(128,128),e}render=async()=>{this._renderer.hasInitialized()||await this._renderer.init(),this._renderer.setRenderTarget(this._renderTarget);try{this._renderer.render(this._scene,this._camera)}catch(e){throw this._renderer.setRenderTarget(null),e}this._renderer.setRenderTarget(null)};async toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=await this._renderer.readRenderTargetPixelsAsync(this._renderTarget,0,0,this._width,this._height);if(!this._renderer.backend.isWebGPUBackend)return e;const t=4*this._width,r=256*Math.ceil(t*e.BYTES_PER_ELEMENT/256)/e.BYTES_PER_ELEMENT,a=new e.constructor(t*this._height);for(let i=0;i<this._height;i++){const n=(this._height-1-i)*r;a.set(e.subarray(n,n+t),i*t)}return a}async toDataTexture(e){const t=new r.DataTexture(await this.toArray(),this.width,this.height,r.RGBAFormat,this._type,e?.mapping||r.UVMapping,e?.wrapS||r.ClampToEdgeWrapping,e?.wrapT||r.ClampToEdgeWrapping,e?.magFilter||r.LinearFilter,e?.minFilter||r.LinearFilter,e?.anisotropy||1,r.LinearSRGBColorSpace);return t.flipY=void 0===e?.flipY||e?.flipY,t.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,t}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&this._renderer.dispose().catch(console.error)}dispose(e){e&&this.renderTarget.dispose(),this.material instanceof r.ShaderMaterial&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof r.Texture&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof r.Texture&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose(),this.disposeOnDemandRenderer()}get width(){return this._width}set width(e){this._width=e,this._renderTarget.setSize(this._width,this._height)}get height(){return this._height}set height(e){this._height=e,this._renderTarget.setSize(this._width,this._height)}get renderer(){return this._renderer}get renderTarget(){return this._renderTarget}set renderTarget(e){this._renderTarget=e,this._width=e.width,this._height=e.height}get material(){return this._material}get type(){return this._type}get colorSpace(){return this._colorSpace}}const _=new Set,w=(e,t,r)=>{const a=`${t}:${e}`;_.has(a)||(_.add(a),console.warn(`gainmap-js: ${e} from '${t}' is deprecated and will be removed in v4.0.0. Use ${r} from '@monogrid/gainmap-js/webgpu' with WebGPURenderer (which also has a WebGL2 backend) instead. It is not a drop-in replacement (it returns a GainMapNode, not a render target), see https://github.com/MONOGRID/gainmap-js#migrating-to-v400`))},x=a.vec3(-65504,-65504,-65504),v=a.vec3(65504,65504,65504);class S extends r.MeshBasicNodeMaterial{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;_gammaUniform;_offsetHdrUniform;_offsetSdrUniform;_gainMapMinUniform;_gainMapMaxUniform;_weightFactorUniform;_sdrTexture;_gainMapTexture;constructor({gamma:e,offsetHdr:t,offsetSdr:i,gainMapMin:n,gainMapMax:s,maxDisplayBoost:o,hdrCapacityMin:d,hdrCapacityMax:h,sdr:p,gainMap:g}){super(),this.name="GainMapDecoderMaterial",this.blending=r.NoBlending,this.depthTest=!1,this.depthWrite=!1,this._sdrTexture=a.texture(p),this._gainMapTexture=a.texture(g),this._gammaUniform=a.uniform(new r.Vector3(1/e[0],1/e[1],1/e[2])),this._offsetHdrUniform=a.uniform(new r.Vector3(t[0],t[1],t[2])),this._offsetSdrUniform=a.uniform(new r.Vector3(i[0],i[1],i[2])),this._gainMapMinUniform=a.uniform(new r.Vector3(n[0],n[1],n[2])),this._gainMapMaxUniform=a.uniform(new r.Vector3(s[0],s[1],s[2]));const c=(Math.log2(o)-d)/(h-d);this._weightFactorUniform=a.uniform(c,"float"),this._maxDisplayBoost=o,this._hdrCapacityMin=d,this._hdrCapacityMax=h;const l=this._sdrTexture.rgb,m=this._gainMapTexture.rgb.pow(this._gammaUniform),u=this._gainMapMinUniform.mul(m.oneMinus()).add(this._gainMapMaxUniform.mul(m)),f=a.vec3(2).pow(u.mul(this._weightFactorUniform)),M=l.add(this._offsetSdrUniform).mul(f).sub(this._offsetHdrUniform).min(v).max(x);this.colorNode=M}get sdr(){return this._sdrTexture.value}set sdr(e){this._sdrTexture.value=e}get gainMap(){return this._gainMapTexture.value}set gainMap(e){this._gainMapTexture.value=e}get offsetHdr(){return[this._offsetHdrUniform.value.x,this._offsetHdrUniform.value.y,this._offsetHdrUniform.value.z]}set offsetHdr(e){this._offsetHdrUniform.value.x=e[0],this._offsetHdrUniform.value.y=e[1],this._offsetHdrUniform.value.z=e[2]}get offsetSdr(){return[this._offsetSdrUniform.value.x,this._offsetSdrUniform.value.y,this._offsetSdrUniform.value.z]}set offsetSdr(e){this._offsetSdrUniform.value.x=e[0],this._offsetSdrUniform.value.y=e[1],this._offsetSdrUniform.value.z=e[2]}get gainMapMin(){return[this._gainMapMinUniform.value.x,this._gainMapMinUniform.value.y,this._gainMapMinUniform.value.z]}set gainMapMin(e){this._gainMapMinUniform.value.x=e[0],this._gainMapMinUniform.value.y=e[1],this._gainMapMinUniform.value.z=e[2]}get gainMapMax(){return[this._gainMapMaxUniform.value.x,this._gainMapMaxUniform.value.y,this._gainMapMaxUniform.value.z]}set gainMapMax(e){this._gainMapMaxUniform.value.x=e[0],this._gainMapMaxUniform.value.y=e[1],this._gainMapMaxUniform.value.z=e[2]}get gamma(){return[1/this._gammaUniform.value.x,1/this._gammaUniform.value.y,1/this._gammaUniform.value.z]}set gamma(e){this._gammaUniform.value.x=1/e[0],this._gammaUniform.value.y=1/e[1],this._gammaUniform.value.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this._weightFactorUniform.value=Math.max(0,Math.min(1,e))}}const T=i({renderer:r.WebGPURenderer,createMaterial:e=>new S(e),createQuadRenderer:e=>new y(e)});class R extends M{constructor(e,t){super({renderer:e,createMaterial:e=>new S(e),createQuadRenderer:e=>new y(e)},t)}async render(e,t,r,a){const{sdrImage:i,gainMapImage:n,needsFlip:s}=await this.processImages(r,a,"from-image"),{gainMap:o,sdr:d}=this.createTextures(i,n,s);this.updateQuadRenderer(e,i,o,d,t),await e.render()}}class U extends r.TextureNode{renderTarget;revision=0;_quadMesh;_material;_rendererState={};_state=[];constructor(e,t){const a=new r.RenderTarget(1,1,{depthBuffer:!1,...t});super(a.texture),this.renderTarget=a,this.updateBeforeType=r.NodeUpdateType.RENDER,this._material=e,this._quadMesh=new r.QuadMesh(e)}_getDependencies(){return[]}_onRender(){}invalidate(){return this._state=[],this}render(e){const t=this._getDependencies();for(const r of t)r.render(e);const{width:a,height:i}=this;if(0===a||0===i)return!1;const n=[a,i,...t.map(e=>e.revision),...this._getState()];return(n.length!==this._state.length||!n.every((e,t)=>e===this._state[t]))&&(this._state=n,this.renderTarget.width===a&&this.renderTarget.height===i||this.renderTarget.setSize(a,i),r.RendererUtils.resetRendererState(e,this._rendererState),e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),r.RendererUtils.restoreRendererState(e,this._rendererState),this.revision++,this._onRender(),!0)}updateBefore(e){e.renderer&&this.render(e.renderer)}set value(e){if(this.renderTarget&&e!==this.renderTarget.texture)throw new Error(`${this.constructor.name}: the value of this node is its render target texture and can't be replaced`)}get value(){return this.renderTarget?.texture}clone(){const e=new r.TextureNode(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.updateBeforeType=r.NodeUpdateType.RENDER,e.updateBefore=e=>this.updateBefore(e),e}dispose(){this.renderTarget.dispose(),this._material.dispose(),super.dispose()}}class C extends U{static get type(){return"GainMapNode"}uniforms;_sdrSource=null;_gainMapSource=null;constructor(){const e=new r.MeshBasicNodeMaterial;e.name="GainMapDecoder",super(e,{type:r.HalfFloatType,colorSpace:r.LinearSRGBColorSpace,generateMipmaps:!0,minFilter:r.LinearMipmapLinearFilter,magFilter:r.LinearFilter});const t=this.uniforms={sdr:a.texture(new r.Texture),gainMap:a.texture(new r.Texture),gamma:a.uniform(new r.Vector3(1,1,1)),offsetSdr:a.uniform(new r.Vector3),offsetHdr:a.uniform(new r.Vector3),gainMapMin:a.uniform(new r.Vector3),gainMapMax:a.uniform(new r.Vector3(1,1,1)),hdrCapacityMin:a.uniform(0),hdrCapacityMax:a.uniform(1),maxDisplayBoost:a.uniform(1)},i=t.gainMap.rgb.pow(a.vec3(1).div(t.gamma)),n=a.mix(t.gainMapMin,t.gainMapMax,i),s=a.saturate(a.log2(t.maxDisplayBoost).sub(t.hdrCapacityMin).div(t.hdrCapacityMax.sub(t.hdrCapacityMin))),o=t.sdr.rgb.add(t.offsetSdr).mul(a.exp2(n.mul(s))).sub(t.offsetHdr);e.colorNode=a.vec4(o.clamp(-65504,65504),1)}get sdr(){return this.uniforms.sdr.value}get gainMap(){return this.uniforms.gainMap.value}get gamma(){return this.uniforms.gamma}get offsetSdr(){return this.uniforms.offsetSdr}get offsetHdr(){return this.uniforms.offsetHdr}get gainMapMin(){return this.uniforms.gainMapMin}get gainMapMax(){return this.uniforms.gainMapMax}get hdrCapacityMin(){return this.uniforms.hdrCapacityMin}get hdrCapacityMax(){return this.uniforms.hdrCapacityMax}get maxDisplayBoost(){return this.uniforms.maxDisplayBoost}get width(){return this._sdrSource?this._sdrSource.width:this.sdr.image?.width??0}get height(){return this._sdrSource?this._sdrSource.height:this.sdr.image?.height??0}setTextures(e,t){return this._sdrSource=e instanceof U?e:null,this._gainMapSource=t instanceof U?t:null,this.uniforms.sdr.value=e instanceof U?e.value:e,this.uniforms.gainMap.value=t instanceof U?t.value:t,this.width>0&&this.height>0&&this.renderTarget.setSize(this.width,this.height),this}setMetadata(e){const t=this.uniforms;return t.gamma.value.fromArray(e.gamma),t.offsetSdr.value.fromArray(e.offsetSdr),t.offsetHdr.value.fromArray(e.offsetHdr),t.gainMapMin.value.fromArray(e.gainMapMin),t.gainMapMax.value.fromArray(e.gainMapMax),t.hdrCapacityMin.value=e.hdrCapacityMin,t.hdrCapacityMax.value=e.hdrCapacityMax,t.maxDisplayBoost.value=Math.pow(2,e.hdrCapacityMax),this}_getState(){const e=this.uniforms;return[this.sdr.id,this.sdr.version,this.gainMap.id,this.gainMap.version,...e.gamma.value.toArray(),...e.offsetSdr.value.toArray(),...e.offsetHdr.value.toArray(),...e.gainMapMin.value.toArray(),...e.gainMapMax.value.toArray(),e.hdrCapacityMin.value,e.hdrCapacityMax.value,e.maxDisplayBoost.value]}_getDependencies(){const e=[];return this._sdrSource&&e.push(this._sdrSource),this._gainMapSource&&e.push(this._gainMapSource),e}_onRender(){this.value.needsPMREMUpdate=!0}decode(e){return this.render(e)}updateBefore(e){e.renderer&&this.decode(e.renderer)}dispose(){this._sdrSource||this.sdr.dispose(),this._gainMapSource||this.gainMap.dispose(),super.dispose()}}class F extends r.Loader{createFileLoader(e){const t=new r.FileLoader(this.manager);return e&&t.setResponseType(e),t.setRequestHeader(this.requestHeader),t.setPath(this.path),t.setWithCredentials(this.withCredentials),t}async fillNode(e,t,r,a){const{sdrImage:i,gainMapImage:n}=await u(r,a,"from-image"),{sdr:s,gainMap:o}=f(i,n,!0);e.setTextures(s,o).setMetadata(t)}}class b extends R{constructor(e,t){super(e,t),w("HDRJPGLoader","@monogrid/gainmap-js/webgpu","HDRJPGNodeLoader")}load(e,t,a,i){const o=this.prepareQuadRenderer(),d=new r.FileLoader(this._internalLoadingManager);return d.setResponseType("arraybuffer"),d.setRequestHeader(this.requestHeader),d.setPath(this.path),d.setWithCredentials(this.withCredentials),this.manager.itemStart(e),d.load(e,async r=>{if("string"==typeof r)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const a=new Uint8Array(r);let d,h,p;try{const e=await l(a);d=e.sdr,h=e.gainMap,p=e.metadata}catch(t){if(!(t instanceof s||t instanceof n))throw t;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),p={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},d=a}try{await this.render(o,p,d.buffer,h?.buffer)}catch(t){return this.manager.itemError(e),"function"==typeof i&&i(t),void o.disposeOnDemandRenderer()}"function"==typeof t&&t(o),this.manager.itemEnd(e),o.disposeOnDemandRenderer()},a,t=>{this.manager.itemError(e),"function"==typeof i&&i(t)}),o}}e.GainMapDecoderMaterial=S,e.GainMapLoader=class extends R{constructor(e,t){super(e,t),w("GainMapLoader","@monogrid/gainmap-js/webgpu","GainMapNodeLoader")}load([e,t,a],i,n,s){const o=this.prepareQuadRenderer();let d,h,p;const g=async()=>{if(d&&h&&p){try{await this.render(o,p,d,h)}catch(r){return this.manager.itemError(e),this.manager.itemError(t),this.manager.itemError(a),"function"==typeof s&&s(r),void o.disposeOnDemandRenderer()}"function"==typeof i&&i(o),this.manager.itemEnd(e),this.manager.itemEnd(t),this.manager.itemEnd(a),o.disposeOnDemandRenderer()}};let c=!0,l=0,m=0,u=!0,f=0,M=0,y=!0,_=0,w=0;const x=()=>{if("function"==typeof n){n(new ProgressEvent("progress",{lengthComputable:c&&u&&y,loaded:m+M+w,total:l+f+_}))}};this.manager.itemStart(e),this.manager.itemStart(t),this.manager.itemStart(a);const v=new r.FileLoader(this._internalLoadingManager);v.setResponseType("arraybuffer"),v.setRequestHeader(this.requestHeader),v.setPath(this.path),v.setWithCredentials(this.withCredentials),v.load(e,async e=>{if("string"==typeof e)throw new Error("Invalid sdr buffer");d=e,await g()},e=>{c=e.lengthComputable,m=e.loaded,l=e.total,x()},t=>{this.manager.itemError(e),"function"==typeof s&&s(t)});const S=new r.FileLoader(this._internalLoadingManager);S.setResponseType("arraybuffer"),S.setRequestHeader(this.requestHeader),S.setPath(this.path),S.setWithCredentials(this.withCredentials),S.load(t,async e=>{if("string"==typeof e)throw new Error("Invalid gainmap buffer");h=e,await g()},e=>{u=e.lengthComputable,M=e.loaded,f=e.total,x()},e=>{this.manager.itemError(t),"function"==typeof s&&s(e)});const T=new r.FileLoader(this._internalLoadingManager);return T.setRequestHeader(this.requestHeader),T.setPath(this.path),T.setWithCredentials(this.withCredentials),T.load(a,async e=>{if("string"!=typeof e)throw new Error("Invalid metadata string");p=JSON.parse(e),await g()},e=>{y=e.lengthComputable,w=e.loaded,_=e.total,x()},e=>{this.manager.itemError(a),"function"==typeof s&&s(e)}),o}},e.GainMapNode=C,e.GainMapNodeLoader=class extends F{load(e,t,r,a){const i=new C,n=e.map(()=>({lengthComputable:!0,loaded:0,total:0})),s=(e,t,a)=>new Promise((i,s)=>{this.manager.itemStart(e),this.createFileLoader(a).load(e,i,e=>{n[t]={lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total},"function"==typeof r&&r(new ProgressEvent("progress",{lengthComputable:n.every(e=>e.lengthComputable),loaded:n.reduce((e,t)=>e+t.loaded,0),total:n.reduce((e,t)=>e+t.total,0)}))},s)}),[o,d,h]=e;return Promise.all([s(o,0,"arraybuffer"),s(d,1,"arraybuffer"),s(h,2)]).then(async([e,t,r])=>{if("string"==typeof e||"string"==typeof t||"string"!=typeof r)throw new Error("Invalid response types");const a=JSON.parse(r);await this.fillNode(i,a,e,t)}).then(()=>{"function"==typeof t&&t(i),e.forEach(e=>this.manager.itemEnd(e))},t=>{e.forEach(e=>this.manager.itemError(e)),"function"==typeof a&&a(t)}),i}},e.GainMapNotFoundError=n,e.HDRJPGLoader=b,e.HDRJPGNodeLoader=class extends F{load(e,t,r,a){const i=new C;return this.manager.itemStart(e),this.createFileLoader("arraybuffer").load(e,async r=>{try{if("string"==typeof r)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const t=new Uint8Array(r);let a,o,d;try{const e=await l(t);a=e.sdr,o=e.gainMap,d=e.metadata}catch(r){if(!(r instanceof s||r instanceof n))throw r;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGNodeLoader will render the SDR jpeg`),d={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},a=t}await this.fillNode(i,d,a.buffer,o?.buffer)}catch(t){return this.manager.itemError(e),void("function"==typeof a&&a(t))}"function"==typeof t&&t(i),this.manager.itemEnd(e)},r,t=>{this.manager.itemError(e),"function"==typeof a&&a(t)}),i}},e.JPEGRLoader=b,e.LoaderBaseShared=M,e.MPFExtractor=c,e.QuadRenderer=y,e.XMPMetadataNotFoundError=s,e.createDecodeFunction=i,e.createTextures=f,e.decode=async e=>{if(w("decode()","@monogrid/gainmap-js/webgpu","gainMapNode()"),!e.renderer)throw new Error("Renderer is required for decode function");const t=T({...e,renderer:e.renderer});try{await t.render()}catch(e){throw t.disposeOnDemandRenderer(),e}return t},e.extractGainmapFromJPEG=l,e.extractISO=h,e.extractXMP=g,e.gainMapNode=(e,t,r)=>(new C).setTextures(e,t).setMetadata(r),e.processImages=u});
|
|
5
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three/webgpu"),require("three"),require("three/tsl")):"function"==typeof define&&define.amd?define(["exports","three/webgpu","three","three/tsl"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@monogrid/gainmap-js"]={},e["three/webgpu"],e.three,e["three/tsl"])}(this,function(e,t,r,a){"use strict";class i extends t.TextureNode{renderTarget;revision=0;_quadMesh;_material;_rendererState={};_state=[];constructor(e,r){const a=new t.RenderTarget(1,1,{depthBuffer:!1,...r});super(a.texture),this.renderTarget=a,this.updateBeforeType=t.NodeUpdateType.RENDER,this._material=e,this._quadMesh=new t.QuadMesh(e)}_getDependencies(){return[]}_onRender(){}invalidate(){return this._state=[],this}render(e){const r=this._getDependencies();for(const t of r)t.render(e);const{width:a,height:i}=this;if(0===a||0===i)return!1;const n=[a,i,...r.map(e=>e.revision),...this._getState()];return(n.length!==this._state.length||!n.every((e,t)=>e===this._state[t]))&&(this._state=n,this.renderTarget.width===a&&this.renderTarget.height===i||this.renderTarget.setSize(a,i),t.RendererUtils.resetRendererState(e,this._rendererState),e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),t.RendererUtils.restoreRendererState(e,this._rendererState),this.revision++,this._onRender(),!0)}updateBefore(e){e.renderer&&this.render(e.renderer)}set value(e){if(this.renderTarget&&e!==this.renderTarget.texture)throw new Error(`${this.constructor.name}: the value of this node is its render target texture and can't be replaced`)}get value(){return this.renderTarget?.texture}clone(){const e=new t.TextureNode(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.updateBeforeType=t.NodeUpdateType.RENDER,e.updateBefore=e=>this.updateBefore(e),e}dispose(){this.renderTarget.dispose(),this._material.dispose(),super.dispose()}}function n(e){return t=>{const{sdr:a,gainMap:i,renderer:n}=t;a.colorSpace!==r.SRGBColorSpace&&(console.warn("SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically"),a.colorSpace=r.SRGBColorSpace),a.needsUpdate=!0,i.colorSpace!==r.LinearSRGBColorSpace&&(console.warn("Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically"),i.colorSpace=r.LinearSRGBColorSpace),i.needsUpdate=!0;const s=e.createMaterial({...t,sdr:a,gainMap:i});return e.createQuadRenderer({width:a.image.width,height:a.image.height,type:r.HalfFloatType,colorSpace:r.LinearSRGBColorSpace,material:s,renderer:n,renderTargetOptions:t.renderTargetOptions})}}class s extends Error{}class o extends Error{}const d=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=0;const a=()=>{const e=t.getUint16(r);return r+=2,e},i=()=>{const e=t.getUint32(r);return r+=4,e},n=a();if(0!==n)throw new Error(`Unsupported ISO 21496-1 minimum_version ${n}`);a();const s=t.getUint8(r++);if(4&s)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const o=128&s?3:1,d=8&s?i():void 0,h=e=>{const a=e?(()=>{const e=t.getInt32(r);return r+=4,e})():i(),n=d??i();if(0===n)throw new Error("Invalid ISO 21496-1 fraction with zero denominator");return a/n},p=h(!1),g=h(!1);if(p>g)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const c=[],l=[],m=[],u=[],f=[];for(let e=0;e<o;e++)c.push(h(!0)),l.push(h(!0)),m.push(h(!1)),u.push(h(!0)),f.push(h(!0));const M=e=>3===o?e:[e[0],e[0],e[0]];return{gainMapMin:M(c),gainMapMax:M(l),gamma:M(m),offsetSdr:M(u),offsetHdr:M(f),hdrCapacityMin:p,hdrCapacityMax:g}},h=Array.from("urn:iso:std:iso:ts:21496:-1\0",e=>e.charCodeAt(0)),p=e=>{const t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=4+h.length;for(let a=0;a+r<e.length;a++){if(255!==e[a]||226!==e[a+1])continue;if(!h.every((t,r)=>e[a+4+r]===t))continue;const i=Math.min(e.length,a+2+t.getUint16(a+2));if(!(i-(a+r)<=4))try{return d(e.subarray(a+r,i))}catch(e){return}}},g=(e,t,r)=>{const a=new RegExp(`${t}="([^"]*)"`,"i").exec(e);if(a)return a[1];const i=new RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`,"i").exec(e);if(i){const e=i[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);return e&&3===e.length?e.map(e=>e.replace(/<\/?rdf:li>/g,"")):i[1].trim()}if(void 0!==r)return r;throw new Error(`Can't find ${t} in gainmap metadata`)},c=e=>{let t;t="undefined"!=typeof TextDecoder?(new TextDecoder).decode(e):e.toString();let r=t.indexOf("<x:xmpmeta");for(;-1!==r;){const e=t.indexOf("x:xmpmeta>",r),a=t.slice(r,e+10);try{const e=g(a,"hdrgm:GainMapMin","0"),t=g(a,"hdrgm:GainMapMax"),r=g(a,"hdrgm:Gamma","1"),i=g(a,"hdrgm:OffsetSDR","0.015625"),n=g(a,"hdrgm:OffsetHDR","0.015625"),s=/hdrgm:HDRCapacityMin="([^"]*)"/.exec(a),o=s?s[1]:"0",d=/hdrgm:HDRCapacityMax="([^"]*)"/.exec(a);if(!d)throw new Error("Incomplete gainmap metadata");const h=d[1];return{gainMapMin:Array.isArray(e)?e.map(e=>parseFloat(e)):[parseFloat(e),parseFloat(e),parseFloat(e)],gainMapMax:Array.isArray(t)?t.map(e=>parseFloat(e)):[parseFloat(t),parseFloat(t),parseFloat(t)],gamma:Array.isArray(r)?r.map(e=>parseFloat(e)):[parseFloat(r),parseFloat(r),parseFloat(r)],offsetSdr:Array.isArray(i)?i.map(e=>parseFloat(e)):[parseFloat(i),parseFloat(i),parseFloat(i)],offsetHdr:Array.isArray(n)?n.map(e=>parseFloat(e)):[parseFloat(n),parseFloat(n),parseFloat(n)],hdrCapacityMin:parseFloat(o),hdrCapacityMax:parseFloat(h)}}catch(e){}r=t.indexOf("<x:xmpmeta",e)}};class l{options;constructor(e){this.options={debug:!(!e||void 0===e.debug)&&e.debug,extractFII:!e||void 0===e.extractFII||e.extractFII,extractNonFII:!e||void 0===e.extractNonFII||e.extractNonFII}}extract(e){return new Promise((t,r)=>{const a=this.options.debug,i=new DataView(e.buffer);if(65496!==i.getUint16(0))return void r(new Error("Not a valid jpeg"));const n=i.byteLength;let s,o=2,d=0;for(;o<n;){if(++d>250)return void r(new Error(`Found no marker after ${d} loops 😵`));if(255!==i.getUint8(o))return void r(new Error(`Not a valid marker at offset 0x${o.toString(16)}, found: 0x${i.getUint8(o).toString(16)}`));if(s=i.getUint8(o+1),a&&console.log(`Marker: ${s.toString(16)}`),226===s){a&&console.log("Found APP2 marker (0xffe2)");const e=o+4;if(1297106432===i.getUint32(e)){const a=e+4;let n;if(18761===i.getUint16(a))n=!1;else{if(19789!==i.getUint16(a))return void r(new Error("No valid endianness marker found in TIFF header"));n=!0}if(42!==i.getUint16(a+2,!n))return void r(new Error("Not valid TIFF data! (no 0x002A marker)"));const s=i.getUint32(a+4,!n);if(s<8)return void r(new Error("Not valid TIFF data! (First offset less than 8)"));const o=a+s,d=i.getUint16(o,!n),h=o+2;let p=0;for(let e=h;e<h+12*d;e+=12)45057===i.getUint16(e,!n)&&(p=i.getUint32(e+8,!n));const g=o+2+12*d+4,c=[];for(let e=g;e<g+16*p;e+=16){const t={MPType:i.getUint32(e,!n),size:i.getUint32(e+4,!n),dataOffset:i.getUint32(e+8,!n),dependantImages:i.getUint32(e+12,!n),start:-1,end:-1,isFII:!1};t.dataOffset?(t.start=a+t.dataOffset,t.isFII=!1):(t.start=0,t.isFII=!0),t.end=t.start+t.size,c.push(t)}if(this.options.extractNonFII&&c.length){const e=new Blob([i]),r=[];for(const t of c){if(t.isFII&&!this.options.extractFII)continue;const a=e.slice(t.start,t.end+1,"image/jpeg");r.push(a)}t(r)}}}o+=2+i.getUint16(o+2)}})}}const m=async e=>{const t=p(e)??c(e);if(!t)throw new o("Gain map XMP metadata not found");const r=new l({extractFII:!0,extractNonFII:!0}),a=await r.extract(e);if(2!==a.length)throw new s("Gain map recovery image not found");return{sdr:new Uint8Array(await a[0].arrayBuffer()),gainMap:new Uint8Array(await a[1].arrayBuffer()),metadata:t}},u=e=>new Promise((t,r)=>{const a=document.createElement("img");a.onload=()=>{t(a)},a.onerror=e=>{r(e)},a.src=URL.createObjectURL(e)}),f=async(e,t,r)=>{const a=t?new Blob([t],{type:"image/jpeg"}):void 0,i=new Blob([e],{type:"image/jpeg"});let n,s,o=!1;if("undefined"==typeof createImageBitmap){const e=await Promise.all([a?u(a):Promise.resolve(void 0),u(i)]);s=e[0],n=e[1],o="flipY"===r}else{const e=await Promise.all([a?createImageBitmap(a,{imageOrientation:r||"flipY"}):Promise.resolve(void 0),createImageBitmap(i,{imageOrientation:r||"flipY"})]);s=e[0],n=e[1]}return{sdrImage:n,gainMapImage:s,needsFlip:o}},M=(e,t,a)=>{const i=new r.Texture(t||new ImageData(2,2),r.UVMapping,r.ClampToEdgeWrapping,r.ClampToEdgeWrapping,r.LinearFilter,r.LinearMipMapLinearFilter,r.RGBAFormat,r.UnsignedByteType,1,r.LinearSRGBColorSpace);i.flipY=a,i.needsUpdate=!0;const n=new r.Texture(e,r.UVMapping,r.ClampToEdgeWrapping,r.ClampToEdgeWrapping,r.LinearFilter,r.LinearMipMapLinearFilter,r.RGBAFormat,r.UnsignedByteType,1,r.SRGBColorSpace);return n.flipY=a,n.needsUpdate=!0,{gainMap:i,sdr:n}};class y extends r.Loader{_renderer;_renderTargetOptions;_internalLoadingManager;_config;constructor(e,t){super(t),this._config=e,e.renderer&&(this._renderer=e.renderer),this._internalLoadingManager=new r.LoadingManager}setRenderer(e){return this._renderer=e,this}setRenderTargetOptions(e){return this._renderTargetOptions=e,this}prepareQuadRenderer(){this._renderer||console.warn("WARNING: A Renderer was not passed to this Loader constructor or in setRenderer, the result of this Loader will need to be converted to a Data Texture with toDataTexture() before you can use it in your renderer.");const e=this._config.createMaterial({gainMapMax:[1,1,1],gainMapMin:[0,0,0],gamma:[1,1,1],offsetHdr:[1,1,1],offsetSdr:[1,1,1],hdrCapacityMax:1,hdrCapacityMin:0,maxDisplayBoost:1,gainMap:new r.Texture,sdr:new r.Texture});return this._config.createQuadRenderer({width:16,height:16,type:r.HalfFloatType,colorSpace:r.LinearSRGBColorSpace,material:e,renderer:this._renderer,renderTargetOptions:this._renderTargetOptions})}processImages(e,t,r){return f(e,t,r)}createTextures(e,t,r){return M(e,t,r)}updateQuadRenderer(e,t,r,a,i){e.width=t.width,e.height=t.height,e.material.gainMap=r,e.material.sdr=a,e.material.gainMapMin=i.gainMapMin,e.material.gainMapMax=i.gainMapMax,e.material.offsetHdr=i.offsetHdr,e.material.offsetSdr=i.offsetSdr,e.material.gamma=i.gamma,e.material.hdrCapacityMin=i.hdrCapacityMin,e.material.hdrCapacityMax=i.hdrCapacityMax,e.material.maxDisplayBoost=Math.pow(2,i.hdrCapacityMax),e.material.needsUpdate=!0}}class _{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(e){this._width=e.width,this._height=e.height,this._type=e.type,this._colorSpace=e.colorSpace;const r={format:t.RGBAFormat,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:void 0!==e.renderTargetOptions?.anisotropy?e.renderTargetOptions?.anisotropy:1,generateMipmaps:void 0!==e.renderTargetOptions?.generateMipmaps&&e.renderTargetOptions?.generateMipmaps,magFilter:void 0!==e.renderTargetOptions?.magFilter?e.renderTargetOptions?.magFilter:t.LinearFilter,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:t.LinearFilter,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:t.ClampToEdgeWrapping,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:t.ClampToEdgeWrapping};this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=_.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new t.Scene,this._camera=new t.OrthographicCamera,this._camera.position.set(0,0,10),this._camera.left=-.5,this._camera.right=.5,this._camera.top=.5,this._camera.bottom=-.5,this._camera.updateProjectionMatrix(),this._quad=new t.Mesh(new t.PlaneGeometry,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new t.RenderTarget(this.width,this.height,r),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:t.UVMapping}static instantiateRenderer(){const e=new t.WebGPURenderer;return e.setSize(128,128),e}render=async()=>{this._renderer.hasInitialized()||await this._renderer.init(),this._renderer.setRenderTarget(this._renderTarget);try{this._renderer.render(this._scene,this._camera)}catch(e){throw this._renderer.setRenderTarget(null),e}this._renderer.setRenderTarget(null)};async toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=await this._renderer.readRenderTargetPixelsAsync(this._renderTarget,0,0,this._width,this._height);if(!this._renderer.backend.isWebGPUBackend)return e;const t=4*this._width,r=256*Math.ceil(t*e.BYTES_PER_ELEMENT/256)/e.BYTES_PER_ELEMENT,a=new e.constructor(t*this._height);for(let i=0;i<this._height;i++){const n=(this._height-1-i)*r;a.set(e.subarray(n,n+t),i*t)}return a}async toDataTexture(e){const r=new t.DataTexture(await this.toArray(),this.width,this.height,t.RGBAFormat,this._type,e?.mapping||t.UVMapping,e?.wrapS||t.ClampToEdgeWrapping,e?.wrapT||t.ClampToEdgeWrapping,e?.magFilter||t.LinearFilter,e?.minFilter||t.LinearFilter,e?.anisotropy||1,t.LinearSRGBColorSpace);return r.flipY=void 0===e?.flipY||e?.flipY,r.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,r}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&this._renderer.dispose().catch(console.error)}dispose(e){e&&this.renderTarget.dispose(),this.material instanceof t.ShaderMaterial&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof t.Texture&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof t.Texture&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose(),this.disposeOnDemandRenderer()}get width(){return this._width}set width(e){this._width=e,this._renderTarget.setSize(this._width,this._height)}get height(){return this._height}set height(e){this._height=e,this._renderTarget.setSize(this._width,this._height)}get renderer(){return this._renderer}get renderTarget(){return this._renderTarget}set renderTarget(e){this._renderTarget=e,this._width=e.width,this._height=e.height}get material(){return this._material}get type(){return this._type}get colorSpace(){return this._colorSpace}}const w=new Set,x=(e,t,r)=>{const a=`${t}:${e}`;w.has(a)||(w.add(a),console.warn(`gainmap-js: ${e} from '${t}' is deprecated and will be removed in v4.0.0. Use ${r} from '@monogrid/gainmap-js/webgpu' with WebGPURenderer (which also has a WebGL2 backend) instead. It is not a drop-in replacement (it returns a GainMapNode, not a render target), see https://github.com/MONOGRID/gainmap-js#migrating-to-v400`))},v=a.vec3(-65504,-65504,-65504),T=a.vec3(65504,65504,65504);class S extends t.MeshBasicNodeMaterial{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;_gammaUniform;_offsetHdrUniform;_offsetSdrUniform;_gainMapMinUniform;_gainMapMaxUniform;_weightFactorUniform;_sdrTexture;_gainMapTexture;constructor({gamma:e,offsetHdr:r,offsetSdr:i,gainMapMin:n,gainMapMax:s,maxDisplayBoost:o,hdrCapacityMin:d,hdrCapacityMax:h,sdr:p,gainMap:g}){super(),this.name="GainMapDecoderMaterial",this.blending=t.NoBlending,this.depthTest=!1,this.depthWrite=!1,this._sdrTexture=a.texture(p),this._gainMapTexture=a.texture(g),this._gammaUniform=a.uniform(new t.Vector3(1/e[0],1/e[1],1/e[2])),this._offsetHdrUniform=a.uniform(new t.Vector3(r[0],r[1],r[2])),this._offsetSdrUniform=a.uniform(new t.Vector3(i[0],i[1],i[2])),this._gainMapMinUniform=a.uniform(new t.Vector3(n[0],n[1],n[2])),this._gainMapMaxUniform=a.uniform(new t.Vector3(s[0],s[1],s[2]));const c=(Math.log2(o)-d)/(h-d);this._weightFactorUniform=a.uniform(c,"float"),this._maxDisplayBoost=o,this._hdrCapacityMin=d,this._hdrCapacityMax=h;const l=this._sdrTexture.rgb,m=this._gainMapTexture.rgb.pow(this._gammaUniform),u=this._gainMapMinUniform.mul(m.oneMinus()).add(this._gainMapMaxUniform.mul(m)),f=a.vec3(2).pow(u.mul(this._weightFactorUniform)),M=l.add(this._offsetSdrUniform).mul(f).sub(this._offsetHdrUniform).min(T).max(v);this.colorNode=M}get sdr(){return this._sdrTexture.value}set sdr(e){this._sdrTexture.value=e}get gainMap(){return this._gainMapTexture.value}set gainMap(e){this._gainMapTexture.value=e}get offsetHdr(){return[this._offsetHdrUniform.value.x,this._offsetHdrUniform.value.y,this._offsetHdrUniform.value.z]}set offsetHdr(e){this._offsetHdrUniform.value.x=e[0],this._offsetHdrUniform.value.y=e[1],this._offsetHdrUniform.value.z=e[2]}get offsetSdr(){return[this._offsetSdrUniform.value.x,this._offsetSdrUniform.value.y,this._offsetSdrUniform.value.z]}set offsetSdr(e){this._offsetSdrUniform.value.x=e[0],this._offsetSdrUniform.value.y=e[1],this._offsetSdrUniform.value.z=e[2]}get gainMapMin(){return[this._gainMapMinUniform.value.x,this._gainMapMinUniform.value.y,this._gainMapMinUniform.value.z]}set gainMapMin(e){this._gainMapMinUniform.value.x=e[0],this._gainMapMinUniform.value.y=e[1],this._gainMapMinUniform.value.z=e[2]}get gainMapMax(){return[this._gainMapMaxUniform.value.x,this._gainMapMaxUniform.value.y,this._gainMapMaxUniform.value.z]}set gainMapMax(e){this._gainMapMaxUniform.value.x=e[0],this._gainMapMaxUniform.value.y=e[1],this._gainMapMaxUniform.value.z=e[2]}get gamma(){return[1/this._gammaUniform.value.x,1/this._gammaUniform.value.y,1/this._gammaUniform.value.z]}set gamma(e){this._gammaUniform.value.x=1/e[0],this._gammaUniform.value.y=1/e[1],this._gammaUniform.value.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this._weightFactorUniform.value=Math.max(0,Math.min(1,e))}}const R=n({renderer:t.WebGPURenderer,createMaterial:e=>new S(e),createQuadRenderer:e=>new _(e)});class U extends y{constructor(e,t){super({renderer:e,createMaterial:e=>new S(e),createQuadRenderer:e=>new _(e)},t)}async render(e,t,r,a){const{sdrImage:i,gainMapImage:n,needsFlip:s}=await this.processImages(r,a,"from-image"),{gainMap:o,sdr:d}=this.createTextures(i,n,s);this.updateQuadRenderer(e,i,o,d,t),await e.render()}}class C extends i{static get type(){return"GainMapNode"}uniforms;_sdrSource=null;_gainMapSource=null;constructor(){const e=new t.MeshBasicNodeMaterial;e.name="GainMapDecoder",super(e,{type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,generateMipmaps:!0,minFilter:t.LinearMipmapLinearFilter,magFilter:t.LinearFilter});const r=this.uniforms={sdr:a.texture(new t.Texture),gainMap:a.texture(new t.Texture),gamma:a.uniform(new t.Vector3(1,1,1)),offsetSdr:a.uniform(new t.Vector3),offsetHdr:a.uniform(new t.Vector3),gainMapMin:a.uniform(new t.Vector3),gainMapMax:a.uniform(new t.Vector3(1,1,1)),hdrCapacityMin:a.uniform(0),hdrCapacityMax:a.uniform(1),maxDisplayBoost:a.uniform(1)},i=r.gainMap.rgb.pow(a.vec3(1).div(r.gamma)),n=a.mix(r.gainMapMin,r.gainMapMax,i),s=a.saturate(a.log2(r.maxDisplayBoost).sub(r.hdrCapacityMin).div(r.hdrCapacityMax.sub(r.hdrCapacityMin))),o=r.sdr.rgb.add(r.offsetSdr).mul(a.exp2(n.mul(s))).sub(r.offsetHdr);e.colorNode=a.vec4(o.clamp(-65504,65504),1)}get sdr(){return this.uniforms.sdr.value}get gainMap(){return this.uniforms.gainMap.value}get gamma(){return this.uniforms.gamma}get offsetSdr(){return this.uniforms.offsetSdr}get offsetHdr(){return this.uniforms.offsetHdr}get gainMapMin(){return this.uniforms.gainMapMin}get gainMapMax(){return this.uniforms.gainMapMax}get hdrCapacityMin(){return this.uniforms.hdrCapacityMin}get hdrCapacityMax(){return this.uniforms.hdrCapacityMax}get maxDisplayBoost(){return this.uniforms.maxDisplayBoost}get width(){return this._sdrSource?this._sdrSource.width:this.sdr.image?.width??0}get height(){return this._sdrSource?this._sdrSource.height:this.sdr.image?.height??0}setTextures(e,t){return this._sdrSource=e instanceof i?e:null,this._gainMapSource=t instanceof i?t:null,this.uniforms.sdr.value=e instanceof i?e.value:e,this.uniforms.gainMap.value=t instanceof i?t.value:t,this.width>0&&this.height>0&&this.renderTarget.setSize(this.width,this.height),this}setMetadata(e){const t=this.uniforms;return t.gamma.value.fromArray(e.gamma),t.offsetSdr.value.fromArray(e.offsetSdr),t.offsetHdr.value.fromArray(e.offsetHdr),t.gainMapMin.value.fromArray(e.gainMapMin),t.gainMapMax.value.fromArray(e.gainMapMax),t.hdrCapacityMin.value=e.hdrCapacityMin,t.hdrCapacityMax.value=e.hdrCapacityMax,t.maxDisplayBoost.value=Math.pow(2,e.hdrCapacityMax),this}_getState(){const e=this.uniforms;return[this.sdr.id,this.sdr.version,this.gainMap.id,this.gainMap.version,...e.gamma.value.toArray(),...e.offsetSdr.value.toArray(),...e.offsetHdr.value.toArray(),...e.gainMapMin.value.toArray(),...e.gainMapMax.value.toArray(),e.hdrCapacityMin.value,e.hdrCapacityMax.value,e.maxDisplayBoost.value]}_getDependencies(){const e=[];return this._sdrSource&&e.push(this._sdrSource),this._gainMapSource&&e.push(this._gainMapSource),e}_onRender(){this.value.needsPMREMUpdate=!0}decode(e){return this.render(e)}updateBefore(e){e.renderer&&this.decode(e.renderer)}dispose(){this._sdrSource||this.sdr.dispose(),this._gainMapSource||this.gainMap.dispose(),super.dispose()}}class F extends t.Loader{createFileLoader(e){const r=new t.FileLoader(this.manager);return e&&r.setResponseType(e),r.setRequestHeader(this.requestHeader),r.setPath(this.path),r.setWithCredentials(this.withCredentials),r}async fillNode(e,t,r,a){const{sdrImage:i,gainMapImage:n}=await f(r,a,"from-image"),{sdr:s,gainMap:o}=M(i,n,!0);e.setTextures(s,o).setMetadata(t)}}class b extends U{constructor(e,t){super(e,t),x("HDRJPGLoader","@monogrid/gainmap-js/webgpu","HDRJPGNodeLoader")}load(e,r,a,i){const n=this.prepareQuadRenderer(),d=new t.FileLoader(this._internalLoadingManager);return d.setResponseType("arraybuffer"),d.setRequestHeader(this.requestHeader),d.setPath(this.path),d.setWithCredentials(this.withCredentials),this.manager.itemStart(e),d.load(e,async t=>{if("string"==typeof t)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const a=new Uint8Array(t);let d,h,p;try{const e=await m(a);d=e.sdr,h=e.gainMap,p=e.metadata}catch(t){if(!(t instanceof o||t instanceof s))throw t;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),p={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},d=a}try{await this.render(n,p,d.buffer,h?.buffer)}catch(t){return this.manager.itemError(e),"function"==typeof i&&i(t),void n.disposeOnDemandRenderer()}"function"==typeof r&&r(n),this.manager.itemEnd(e),n.disposeOnDemandRenderer()},a,t=>{this.manager.itemError(e),"function"==typeof i&&i(t)}),n}}e.GainMapDecoderMaterial=S,e.GainMapLoader=class extends U{constructor(e,t){super(e,t),x("GainMapLoader","@monogrid/gainmap-js/webgpu","GainMapNodeLoader")}load([e,r,a],i,n,s){const o=this.prepareQuadRenderer();let d,h,p;const g=async()=>{if(d&&h&&p){try{await this.render(o,p,d,h)}catch(t){return this.manager.itemError(e),this.manager.itemError(r),this.manager.itemError(a),"function"==typeof s&&s(t),void o.disposeOnDemandRenderer()}"function"==typeof i&&i(o),this.manager.itemEnd(e),this.manager.itemEnd(r),this.manager.itemEnd(a),o.disposeOnDemandRenderer()}};let c=!0,l=0,m=0,u=!0,f=0,M=0,y=!0,_=0,w=0;const x=()=>{if("function"==typeof n){n(new ProgressEvent("progress",{lengthComputable:c&&u&&y,loaded:m+M+w,total:l+f+_}))}};this.manager.itemStart(e),this.manager.itemStart(r),this.manager.itemStart(a);const v=new t.FileLoader(this._internalLoadingManager);v.setResponseType("arraybuffer"),v.setRequestHeader(this.requestHeader),v.setPath(this.path),v.setWithCredentials(this.withCredentials),v.load(e,async e=>{if("string"==typeof e)throw new Error("Invalid sdr buffer");d=e,await g()},e=>{c=e.lengthComputable,m=e.loaded,l=e.total,x()},t=>{this.manager.itemError(e),"function"==typeof s&&s(t)});const T=new t.FileLoader(this._internalLoadingManager);T.setResponseType("arraybuffer"),T.setRequestHeader(this.requestHeader),T.setPath(this.path),T.setWithCredentials(this.withCredentials),T.load(r,async e=>{if("string"==typeof e)throw new Error("Invalid gainmap buffer");h=e,await g()},e=>{u=e.lengthComputable,M=e.loaded,f=e.total,x()},e=>{this.manager.itemError(r),"function"==typeof s&&s(e)});const S=new t.FileLoader(this._internalLoadingManager);return S.setRequestHeader(this.requestHeader),S.setPath(this.path),S.setWithCredentials(this.withCredentials),S.load(a,async e=>{if("string"!=typeof e)throw new Error("Invalid metadata string");p=JSON.parse(e),await g()},e=>{y=e.lengthComputable,w=e.loaded,_=e.total,x()},e=>{this.manager.itemError(a),"function"==typeof s&&s(e)}),o}},e.GainMapNode=C,e.GainMapNodeLoader=class extends F{load(e,t,r,a){const i=new C,n=e.map(()=>({lengthComputable:!0,loaded:0,total:0})),s=(e,t,a)=>new Promise((i,s)=>{this.manager.itemStart(e),this.createFileLoader(a).load(e,i,e=>{n[t]={lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total},"function"==typeof r&&r(new ProgressEvent("progress",{lengthComputable:n.every(e=>e.lengthComputable),loaded:n.reduce((e,t)=>e+t.loaded,0),total:n.reduce((e,t)=>e+t.total,0)}))},s)}),[o,d,h]=e;return Promise.all([s(o,0,"arraybuffer"),s(d,1,"arraybuffer"),s(h,2)]).then(async([e,t,r])=>{if("string"==typeof e||"string"==typeof t||"string"!=typeof r)throw new Error("Invalid response types");const a=JSON.parse(r);await this.fillNode(i,a,e,t)}).then(()=>{"function"==typeof t&&t(i),e.forEach(e=>this.manager.itemEnd(e))},t=>{e.forEach(e=>this.manager.itemError(e)),"function"==typeof a&&a(t)}),i}},e.GainMapNotFoundError=s,e.HDRJPGLoader=b,e.HDRJPGNodeLoader=class extends F{load(e,t,r,a){const i=new C;return this.manager.itemStart(e),this.createFileLoader("arraybuffer").load(e,async r=>{try{if("string"==typeof r)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const t=new Uint8Array(r);let a,n,d;try{const e=await m(t);a=e.sdr,n=e.gainMap,d=e.metadata}catch(r){if(!(r instanceof o||r instanceof s))throw r;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGNodeLoader will render the SDR jpeg`),d={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},a=t}await this.fillNode(i,d,a.buffer,n?.buffer)}catch(t){return this.manager.itemError(e),void("function"==typeof a&&a(t))}"function"==typeof t&&t(i),this.manager.itemEnd(e)},r,t=>{this.manager.itemError(e),"function"==typeof a&&a(t)}),i}},e.JPEGRLoader=b,e.LoaderBaseShared=y,e.MPFExtractor=l,e.QuadRenderer=_,e.RenderTargetNode=i,e.XMPMetadataNotFoundError=o,e.createDecodeFunction=n,e.createTextures=M,e.decode=async e=>{if(x("decode()","@monogrid/gainmap-js/webgpu","gainMapNode()"),!e.renderer)throw new Error("Renderer is required for decode function");const t=R({...e,renderer:e.renderer});try{await t.render()}catch(e){throw t.disposeOnDemandRenderer(),e}return t},e.extractGainmapFromJPEG=m,e.extractISO=p,e.extractXMP=c,e.gainMapNode=(e,t,r)=>(new C).setTextures(e,t).setMetadata(r),e.processImages=f});
|
package/dist/encode.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.7.
|
|
2
|
+
* @monogrid/gainmap-js v3.7.1
|
|
3
3
|
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import { c as compress } from './compress-
|
|
7
|
-
import { g as getDataTexture } from './get-data-texture-
|
|
6
|
+
import { c as compress } from './compress-DA31yhmz.js';
|
|
7
|
+
import { g as getDataTexture } from './get-data-texture-CpszSMzv.js';
|
|
8
8
|
import { ShaderMaterial, NoBlending, Vector3, LinearSRGBColorSpace, UnsignedByteType, ACESFilmicToneMapping, LinearToneMapping, NeutralToneMapping, AgXToneMapping, CineonToneMapping, ReinhardToneMapping, SRGBColorSpace, AlphaFormat, RGBFormat, RGBAFormat, DepthFormat, DepthStencilFormat, RedFormat, RedIntegerFormat, RGFormat, RGIntegerFormat, RGBIntegerFormat, RGBAIntegerFormat, Vector2, WebGLRenderTarget, ClampToEdgeWrapping, NearestFilter, FloatType, DataUtils } from 'three';
|
|
9
|
-
import { Q as QuadRenderer } from './QuadRenderer-
|
|
9
|
+
import { Q as QuadRenderer } from './QuadRenderer-BOS9Aas1.js';
|
|
10
10
|
|
|
11
11
|
const vertexShader$2 = /* glsl */ `
|
|
12
12
|
varying vec2 vUv;
|
package/dist/encode.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.7.
|
|
2
|
+
* @monogrid/gainmap-js v3.7.1
|
|
3
3
|
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
4
|
*/
|
|
5
|
-
import{c as n}from"./compress-BTsSIi_B.js";import{g as e}from"./get-data-texture-CkaFVcv-.js";import{ShaderMaterial as t,NoBlending as o,Vector3 as a,LinearSRGBColorSpace as r,UnsignedByteType as i,ACESFilmicToneMapping as s,LinearToneMapping as m,NeutralToneMapping as c,AgXToneMapping as l,CineonToneMapping as p,ReinhardToneMapping as u,SRGBColorSpace as g,AlphaFormat as d,RGBFormat as f,RGBAFormat as h,DepthFormat as v,DepthStencilFormat as x,RedFormat as M,RedIntegerFormat as _,RGFormat as C,RGIntegerFormat as w,RGBIntegerFormat as A,RGBAIntegerFormat as T,Vector2 as E,WebGLRenderTarget as I,ClampToEdgeWrapping as y,NearestFilter as N,FloatType as S,DataUtils as R}from"three";import{Q as L}from"./QuadRenderer-DoK2pW5M.js";const O=1.0001,b=n=>{console.warn(`gainmap-js: maxContentBoost is ${n} (<= 1), the source image has no HDR content. It will be clamped to 1.0001 and the result will be equivalent to an SDR image.`)},U=(n,e)=>{console.warn(`gainmap-js: minContentBoost (${n}) must be lower than maxContentBoost (${e}), the resulting gain map will be invalid.`)};class B extends t{_minContentBoost;_maxContentBoost;_offsetSdr;_offsetHdr;_gamma;constructor({sdr:n,hdr:e,offsetSdr:t,offsetHdr:r,maxContentBoost:i,minContentBoost:s,gamma:m}){if(!i)throw new Error("maxContentBoost is required");if(!n)throw new Error("sdr is required");if(!e)throw new Error("hdr is required");const c=m||[1,1,1],l=t||[1/64,1/64,1/64],p=r||[1/64,1/64,1/64];i<=1&&b(i);const u=s||1,g=Math.max(i,O);u>=g&&U(u,g),super({name:"GainMapEncoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform sampler2D sdr;\nuniform sampler2D hdr;\nuniform vec3 gamma;\nuniform vec3 offsetSdr;\nuniform vec3 offsetHdr;\nuniform float minLog2;\nuniform float maxLog2;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 sdrColor = texture2D(sdr, vUv).rgb;\n vec3 hdrColor = texture2D(hdr, vUv).rgb;\n\n vec3 pixelGain = (hdrColor + offsetHdr) / (sdrColor + offsetSdr);\n vec3 logRecovery = (log2(pixelGain) - minLog2) / (maxLog2 - minLog2);\n vec3 clampedRecovery = saturate(logRecovery);\n gl_FragColor = vec4(pow(clampedRecovery, gamma), 1.0);\n}\n",uniforms:{sdr:{value:n},hdr:{value:e},gamma:{value:(new a).fromArray(c)},offsetSdr:{value:(new a).fromArray(l)},offsetHdr:{value:(new a).fromArray(p)},minLog2:{value:Math.log2(u)},maxLog2:{value:Math.log2(g)}},blending:o,depthTest:!1,depthWrite:!1}),this._minContentBoost=u,this._maxContentBoost=g,this._offsetSdr=l,this._offsetHdr=p,this._gamma=c,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get gamma(){return this._gamma}set gamma(n){this._gamma=n,this.uniforms.gamma.value=(new a).fromArray(n)}get offsetHdr(){return this._offsetHdr}set offsetHdr(n){this._offsetHdr=n,this.uniforms.offsetHdr.value=(new a).fromArray(n)}get offsetSdr(){return this._offsetSdr}set offsetSdr(n){this._offsetSdr=n,this.uniforms.offsetSdr.value=(new a).fromArray(n)}get minContentBoost(){return this._minContentBoost}set minContentBoost(n){n>=this._maxContentBoost&&U(n,this._maxContentBoost),this._minContentBoost=n,this.uniforms.minLog2.value=Math.log2(n)}get maxContentBoost(){return this._maxContentBoost}set maxContentBoost(n){n<=1&&b(n);const e=Math.max(n,O);this._minContentBoost>=e&&U(this._minContentBoost,e),this._maxContentBoost=e,this.uniforms.maxLog2.value=Math.log2(e)}get gainMapMin(){return[Math.log2(this._minContentBoost),Math.log2(this._minContentBoost),Math.log2(this._minContentBoost)]}get gainMapMax(){return[Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost)]}get hdrCapacityMin(){return Math.min(Math.max(0,this.gainMapMin[0]),Math.max(0,this.gainMapMin[1]),Math.max(0,this.gainMapMin[2]))}get hdrCapacityMax(){return Math.max(Math.max(0,this.gainMapMax[0]),Math.max(0,this.gainMapMax[1]),Math.max(0,this.gainMapMax[2]))}}const P=n=>{const{image:t,sdr:o,renderer:a}=n,s=e(t),m=new B({...n,sdr:o.renderTarget.texture,hdr:s}),c=new L({width:s.image.width,height:s.image.height,type:i,colorSpace:r,material:m,renderer:a,renderTargetOptions:n.renderTargetOptions});try{c.render()}catch(n){throw c.disposeOnDemandRenderer(),n}return c};class D extends t{_brightness=0;_contrast=1;_saturation=1;_exposure=1;_toneMapping;_map;constructor({map:n,toneMapping:e}){super({name:"SDRMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n\nuniform sampler2D map;\nuniform float brightness;\nuniform float contrast;\nuniform float saturation;\nuniform float exposure;\n\nvarying vec2 vUv;\n\nmat4 brightnessMatrix( float brightness ) {\n return mat4(\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n brightness, brightness, brightness, 1\n );\n}\n\nmat4 contrastMatrix( float contrast ) {\n float t = ( 1.0 - contrast ) / 2.0;\n return mat4(\n contrast, 0, 0, 0,\n 0, contrast, 0, 0,\n 0, 0, contrast, 0,\n t, t, t, 1\n );\n}\n\nmat4 saturationMatrix( float saturation ) {\n vec3 luminance = vec3( 0.3086, 0.6094, 0.0820 );\n float oneMinusSat = 1.0 - saturation;\n vec3 red = vec3( luminance.x * oneMinusSat );\n red+= vec3( saturation, 0, 0 );\n vec3 green = vec3( luminance.y * oneMinusSat );\n green += vec3( 0, saturation, 0 );\n vec3 blue = vec3( luminance.z * oneMinusSat );\n blue += vec3( 0, 0, saturation );\n return mat4(\n red, 0,\n green, 0,\n blue, 0,\n 0, 0, 0, 1\n );\n}\n\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\n\nvec3 ACESFilmicToneMapping( vec3 color ) {\n // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source\n vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n // ODT_SAT => XYZ => D60_2_D65 => sRGB\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source\n vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color = ACESInputMat * color;\n // Apply RRT and ODT\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n // Clamp to [0, 1]\n return saturate( color );\n}\n\n// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf\nvec3 ReinhardToneMapping( vec3 color ) {\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n\n// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/\nvec3 CineonToneMapping( vec3 color ) {\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n\n// nothing\nvec3 LinearToneMapping ( vec3 color ) {\n return color;\n}\n\n// Matrices for rec 2020 <> rec 709 color space conversion\n// matrix provided in row-major order so it has been transposed\n// https://www.itu.int/pub/R-REP-BT.2407-2017\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\n\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\n\n// https://iolite-engine.com/blog_posts/minimal_agx_implementation\n// Mean error^2: 3.6705141e-06\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\n\n// AgX Tone Mapping implementation based on Filament, which in turn is based\n// on Blender's implementation using rec 2020 primaries\n// https://github.com/google/filament/pull/7236\n// Inputs and outputs are encoded as Linear-sRGB.\n\nvec3 AgXToneMapping( vec3 color ) {\n\n // AgX constants\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n\n // explicit AgXOutsetMatrix generated from Filaments AgXOutsetMatrixInv\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n\n // LOG2_MIN = -10.0\n // LOG2_MAX = +6.5\n // MIDDLE_GRAY = 0.18\n const float AgxMinEv = - 12.47393; // log2( pow( 2, LOG2_MIN ) * MIDDLE_GRAY )\n const float AgxMaxEv = 4.026069; // log2( pow( 2, LOG2_MAX ) * MIDDLE_GRAY )\n\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\n color = AgXInsetMatrix * color;\n\n // Log2 encoding\n color = max( color, 1e-10 ); // avoid 0 or negative numbers for log2\n color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\n color = clamp( color, 0.0, 1.0 );\n\n // Apply sigmoid\n color = agxDefaultContrastApprox( color );\n\n // Apply AgX look\n // v = agxLook(v, look);\n\n color = AgXOutsetMatrix * color;\n\n // Linearize\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\n // Gamut mapping. Simple clamp for now.\n color = clamp( color, 0.0, 1.0 );\n\n return color;\n\n}\n\n// https://modelviewer.dev/examples/tone-mapping\n\nvec3 NeutralToneMapping( vec3 color ) {\n\n const float StartCompression = 0.8 - 0.04;\n const float Desaturation = 0.15;\n\n float x = min( color.r, min( color.g, color.b ) );\n\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\n color -= offset;\n\n float peak = max( color.r, max( color.g, color.b ) );\n\n if ( peak < StartCompression ) return color;\n\n float d = 1. - StartCompression;\n\n float newPeak = 1. - d * d / ( peak + d - StartCompression );\n\n color *= newPeak / peak;\n\n float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\n return mix( color, vec3( newPeak ), g );\n\n}\n\n\n\nvoid main() {\n vec4 color = texture2D(map, vUv);\n\n vec4 exposed = vec4(exposure * color.rgb, color.a);\n\n vec4 tonemapped = vec4(TONEMAPPING_FUNCTION(exposed.rgb), color.a);\n\n vec4 adjusted =\n brightnessMatrix( brightness ) *\n contrastMatrix( contrast ) *\n saturationMatrix( saturation ) *\n tonemapped;\n\n gl_FragColor = adjusted;\n}\n",uniforms:{map:{value:n},brightness:{value:0},contrast:{value:1},saturation:{value:1},exposure:{value:1}},blending:o,depthTest:!1,depthWrite:!1}),this._map=n,this.toneMapping=this._toneMapping=e||s,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get toneMapping(){return this._toneMapping}set toneMapping(n){let e=!1;switch(n){case s:this.defines.TONEMAPPING_FUNCTION="ACESFilmicToneMapping",e=!0;break;case u:this.defines.TONEMAPPING_FUNCTION="ReinhardToneMapping",e=!0;break;case p:this.defines.TONEMAPPING_FUNCTION="CineonToneMapping",e=!0;break;case m:this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",e=!0;break;case l:this.defines.TONEMAPPING_FUNCTION="AgXToneMapping",e=!0;break;case c:this.defines.TONEMAPPING_FUNCTION="NeutralToneMapping",e=!0;break;default:console.error(`Unsupported toneMapping: ${n}. Using LinearToneMapping.`),this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",this._toneMapping=m}e&&(this._toneMapping=n),this.needsUpdate=!0}get brightness(){return this._brightness}set brightness(n){this._brightness=n,this.uniforms.brightness.value=n}get contrast(){return this._contrast}set contrast(n){this._contrast=n,this.uniforms.contrast.value=n}get saturation(){return this._saturation}set saturation(n){this._saturation=n,this.uniforms.saturation.value=n}get exposure(){return this._exposure}set exposure(n){this._exposure=n,this.uniforms.exposure.value=n}get map(){return this._map}set map(n){this._map=n,this.uniforms.map.value=n}}const F=(n,e,t,o)=>{n.needsUpdate=!0;const a=new L({width:n.image.width,height:n.image.height,type:i,colorSpace:g,material:new D({map:n,toneMapping:t}),renderer:e,renderTargetOptions:o});try{a.render()}catch(n){throw a.disposeOnDemandRenderer(),n}return a},G=n=>{const{image:t,renderer:o}=n,a=e(t),r=F(a,o,n.toneMapping,n.renderTargetOptions),i=P({...n,image:a,sdr:r,renderer:r.renderer});return{sdr:r,gainMap:i,hdr:a,getMetadata:()=>({gainMapMax:i.material.gainMapMax,gainMapMin:i.material.gainMapMin,gamma:i.material.gamma,hdrCapacityMax:i.material.hdrCapacityMax,hdrCapacityMin:i.material.hdrCapacityMin,offsetHdr:i.material.offsetHdr,offsetSdr:i.material.offsetSdr})}},k=async e=>{const t=G(e),{mimeType:o,quality:a,flipY:r,withWorker:i}=e;let s,m,c;const l=new ImageData(t.sdr.toArray(),t.sdr.width,t.sdr.height),p=new ImageData(t.gainMap.toArray(),t.gainMap.width,t.gainMap.height);if(i){const n=await Promise.all([i.compress({source:l,mimeType:o,quality:a,flipY:r}),i.compress({source:p,mimeType:o,quality:a,flipY:r})]);s=n,m=n[0].source,c=n[1].source}else s=await Promise.all([n({source:l,mimeType:o,quality:a,flipY:r}),n({source:p,mimeType:o,quality:a,flipY:r})]),m=l.data,c=p.data;return t.sdr.dispose(),t.gainMap.dispose(),{...t,...t.getMetadata(),sdr:s[0],gainMap:s[1],rawSDR:m,rawGainMap:c}},H=(n,o="max",a)=>{const r=e(n);if(r.format!==d&&r.format!==f&&r.format!==h&&r.format!==v&&r.format!==x&&r.format!==M&&r.format!==_&&r.format!==C&&r.format!==w&&r.format!==A&&r.format!==T)throw new Error("Unsupported texture format");const i=new t({vertexShader:"\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\nprecision mediump float;\n\n#ifndef CELL_SIZE\n #define CELL_SIZE 2\n#endif\n\n#ifndef COMPARE_FUNCTION\n #define COMPARE_FUNCTION max\n#endif\n\n#ifndef INITIAL_VALUE\n #define INITIAL_VALUE 0\n#endif\n\nuniform sampler2D map;\nuniform vec2 u_srcResolution;\n\nvarying vec2 vUv;\n\nvoid main() {\n // compute the first pixel the source cell\n vec2 srcPixel = floor(gl_FragCoord.xy) * float(CELL_SIZE);\n\n // one pixel in source\n vec2 onePixel = vec2(1) / u_srcResolution;\n\n // uv for first pixel in cell. +0.5 for center of pixel\n vec2 uv = (srcPixel + 0.5) * onePixel;\n\n vec4 resultColor = vec4(INITIAL_VALUE);\n\n for (int y = 0; y < CELL_SIZE; ++y) {\n for (int x = 0; x < CELL_SIZE; ++x) {\n resultColor = COMPARE_FUNCTION(resultColor, texture2D(map, uv + vec2(x, y) * onePixel));\n }\n }\n\n gl_FragColor = resultColor;\n}\n",uniforms:{u_srcResolution:{value:new E(r.image.width,r.image.height)},map:{value:r}},defines:{CELL_SIZE:2,COMPARE_FUNCTION:o,INITIAL_VALUE:"max"===o?0:65504}});r.needsUpdate=!0,i.needsUpdate=!0;let s=r.image.width,m=r.image.height;const c=new L({width:s,height:m,type:r.type,colorSpace:r.colorSpace,material:i,renderer:a}),l=[];for(;s>1||m>1;){s=Math.max(1,(s+2-1)/2|0),m=Math.max(1,(m+2-1)/2|0);const n=new I(s,m,{type:c.type,format:r.format,colorSpace:c.colorSpace,minFilter:N,magFilter:N,wrapS:y,wrapT:y,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});l.push(n)}s=r.image.width,m=r.image.height,l.forEach(n=>{s=Math.max(1,(s+2-1)/2|0),m=Math.max(1,(m+2-1)/2|0),c.renderTarget=n,c.render(),i.uniforms.map.value=n.texture,i.uniforms.u_srcResolution.value.x=s,i.uniforms.u_srcResolution.value.y=m});const p=c.toArray();return c.dispose(),l.forEach(n=>n.dispose()),[c.type===S?p[0]:R.fromHalfFloat(p[0]),c.type===S?p[1]:R.fromHalfFloat(p[1]),c.type===S?p[2]:R.fromHalfFloat(p[2])]};export{B as GainMapEncoderMaterial,D as SDRMaterial,n as compress,G as encode,k as encodeAndCompress,H as findTextureMinMax,P as getGainMap,F as getSDRRendition};
|
|
5
|
+
import{c as n}from"./compress-goZ8TdVo.js";import{g as e}from"./get-data-texture-Dlg6zKSG.js";import{ShaderMaterial as t,NoBlending as o,Vector3 as a,LinearSRGBColorSpace as r,UnsignedByteType as i,ACESFilmicToneMapping as s,LinearToneMapping as m,NeutralToneMapping as c,AgXToneMapping as l,CineonToneMapping as p,ReinhardToneMapping as u,SRGBColorSpace as g,AlphaFormat as d,RGBFormat as f,RGBAFormat as h,DepthFormat as v,DepthStencilFormat as x,RedFormat as M,RedIntegerFormat as _,RGFormat as C,RGIntegerFormat as w,RGBIntegerFormat as A,RGBAIntegerFormat as T,Vector2 as E,WebGLRenderTarget as I,ClampToEdgeWrapping as y,NearestFilter as N,FloatType as S,DataUtils as R}from"three";import{Q as L}from"./QuadRenderer-BqD-oQ7D.js";const O=1.0001,b=n=>{console.warn(`gainmap-js: maxContentBoost is ${n} (<= 1), the source image has no HDR content. It will be clamped to 1.0001 and the result will be equivalent to an SDR image.`)},U=(n,e)=>{console.warn(`gainmap-js: minContentBoost (${n}) must be lower than maxContentBoost (${e}), the resulting gain map will be invalid.`)};class B extends t{_minContentBoost;_maxContentBoost;_offsetSdr;_offsetHdr;_gamma;constructor({sdr:n,hdr:e,offsetSdr:t,offsetHdr:r,maxContentBoost:i,minContentBoost:s,gamma:m}){if(!i)throw new Error("maxContentBoost is required");if(!n)throw new Error("sdr is required");if(!e)throw new Error("hdr is required");const c=m||[1,1,1],l=t||[1/64,1/64,1/64],p=r||[1/64,1/64,1/64];i<=1&&b(i);const u=s||1,g=Math.max(i,O);u>=g&&U(u,g),super({name:"GainMapEncoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform sampler2D sdr;\nuniform sampler2D hdr;\nuniform vec3 gamma;\nuniform vec3 offsetSdr;\nuniform vec3 offsetHdr;\nuniform float minLog2;\nuniform float maxLog2;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 sdrColor = texture2D(sdr, vUv).rgb;\n vec3 hdrColor = texture2D(hdr, vUv).rgb;\n\n vec3 pixelGain = (hdrColor + offsetHdr) / (sdrColor + offsetSdr);\n vec3 logRecovery = (log2(pixelGain) - minLog2) / (maxLog2 - minLog2);\n vec3 clampedRecovery = saturate(logRecovery);\n gl_FragColor = vec4(pow(clampedRecovery, gamma), 1.0);\n}\n",uniforms:{sdr:{value:n},hdr:{value:e},gamma:{value:(new a).fromArray(c)},offsetSdr:{value:(new a).fromArray(l)},offsetHdr:{value:(new a).fromArray(p)},minLog2:{value:Math.log2(u)},maxLog2:{value:Math.log2(g)}},blending:o,depthTest:!1,depthWrite:!1}),this._minContentBoost=u,this._maxContentBoost=g,this._offsetSdr=l,this._offsetHdr=p,this._gamma=c,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get gamma(){return this._gamma}set gamma(n){this._gamma=n,this.uniforms.gamma.value=(new a).fromArray(n)}get offsetHdr(){return this._offsetHdr}set offsetHdr(n){this._offsetHdr=n,this.uniforms.offsetHdr.value=(new a).fromArray(n)}get offsetSdr(){return this._offsetSdr}set offsetSdr(n){this._offsetSdr=n,this.uniforms.offsetSdr.value=(new a).fromArray(n)}get minContentBoost(){return this._minContentBoost}set minContentBoost(n){n>=this._maxContentBoost&&U(n,this._maxContentBoost),this._minContentBoost=n,this.uniforms.minLog2.value=Math.log2(n)}get maxContentBoost(){return this._maxContentBoost}set maxContentBoost(n){n<=1&&b(n);const e=Math.max(n,O);this._minContentBoost>=e&&U(this._minContentBoost,e),this._maxContentBoost=e,this.uniforms.maxLog2.value=Math.log2(e)}get gainMapMin(){return[Math.log2(this._minContentBoost),Math.log2(this._minContentBoost),Math.log2(this._minContentBoost)]}get gainMapMax(){return[Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost)]}get hdrCapacityMin(){return Math.min(Math.max(0,this.gainMapMin[0]),Math.max(0,this.gainMapMin[1]),Math.max(0,this.gainMapMin[2]))}get hdrCapacityMax(){return Math.max(Math.max(0,this.gainMapMax[0]),Math.max(0,this.gainMapMax[1]),Math.max(0,this.gainMapMax[2]))}}const P=n=>{const{image:t,sdr:o,renderer:a}=n,s=e(t),m=new B({...n,sdr:o.renderTarget.texture,hdr:s}),c=new L({width:s.image.width,height:s.image.height,type:i,colorSpace:r,material:m,renderer:a,renderTargetOptions:n.renderTargetOptions});try{c.render()}catch(n){throw c.disposeOnDemandRenderer(),n}return c};class D extends t{_brightness=0;_contrast=1;_saturation=1;_exposure=1;_toneMapping;_map;constructor({map:n,toneMapping:e}){super({name:"SDRMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n\nuniform sampler2D map;\nuniform float brightness;\nuniform float contrast;\nuniform float saturation;\nuniform float exposure;\n\nvarying vec2 vUv;\n\nmat4 brightnessMatrix( float brightness ) {\n return mat4(\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n brightness, brightness, brightness, 1\n );\n}\n\nmat4 contrastMatrix( float contrast ) {\n float t = ( 1.0 - contrast ) / 2.0;\n return mat4(\n contrast, 0, 0, 0,\n 0, contrast, 0, 0,\n 0, 0, contrast, 0,\n t, t, t, 1\n );\n}\n\nmat4 saturationMatrix( float saturation ) {\n vec3 luminance = vec3( 0.3086, 0.6094, 0.0820 );\n float oneMinusSat = 1.0 - saturation;\n vec3 red = vec3( luminance.x * oneMinusSat );\n red+= vec3( saturation, 0, 0 );\n vec3 green = vec3( luminance.y * oneMinusSat );\n green += vec3( 0, saturation, 0 );\n vec3 blue = vec3( luminance.z * oneMinusSat );\n blue += vec3( 0, 0, saturation );\n return mat4(\n red, 0,\n green, 0,\n blue, 0,\n 0, 0, 0, 1\n );\n}\n\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\n\nvec3 ACESFilmicToneMapping( vec3 color ) {\n // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source\n vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n // ODT_SAT => XYZ => D60_2_D65 => sRGB\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source\n vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color = ACESInputMat * color;\n // Apply RRT and ODT\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n // Clamp to [0, 1]\n return saturate( color );\n}\n\n// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf\nvec3 ReinhardToneMapping( vec3 color ) {\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n\n// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/\nvec3 CineonToneMapping( vec3 color ) {\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n\n// nothing\nvec3 LinearToneMapping ( vec3 color ) {\n return color;\n}\n\n// Matrices for rec 2020 <> rec 709 color space conversion\n// matrix provided in row-major order so it has been transposed\n// https://www.itu.int/pub/R-REP-BT.2407-2017\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\n\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\n\n// https://iolite-engine.com/blog_posts/minimal_agx_implementation\n// Mean error^2: 3.6705141e-06\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\n\n// AgX Tone Mapping implementation based on Filament, which in turn is based\n// on Blender's implementation using rec 2020 primaries\n// https://github.com/google/filament/pull/7236\n// Inputs and outputs are encoded as Linear-sRGB.\n\nvec3 AgXToneMapping( vec3 color ) {\n\n // AgX constants\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n\n // explicit AgXOutsetMatrix generated from Filaments AgXOutsetMatrixInv\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n\n // LOG2_MIN = -10.0\n // LOG2_MAX = +6.5\n // MIDDLE_GRAY = 0.18\n const float AgxMinEv = - 12.47393; // log2( pow( 2, LOG2_MIN ) * MIDDLE_GRAY )\n const float AgxMaxEv = 4.026069; // log2( pow( 2, LOG2_MAX ) * MIDDLE_GRAY )\n\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\n color = AgXInsetMatrix * color;\n\n // Log2 encoding\n color = max( color, 1e-10 ); // avoid 0 or negative numbers for log2\n color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\n color = clamp( color, 0.0, 1.0 );\n\n // Apply sigmoid\n color = agxDefaultContrastApprox( color );\n\n // Apply AgX look\n // v = agxLook(v, look);\n\n color = AgXOutsetMatrix * color;\n\n // Linearize\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\n // Gamut mapping. Simple clamp for now.\n color = clamp( color, 0.0, 1.0 );\n\n return color;\n\n}\n\n// https://modelviewer.dev/examples/tone-mapping\n\nvec3 NeutralToneMapping( vec3 color ) {\n\n const float StartCompression = 0.8 - 0.04;\n const float Desaturation = 0.15;\n\n float x = min( color.r, min( color.g, color.b ) );\n\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\n color -= offset;\n\n float peak = max( color.r, max( color.g, color.b ) );\n\n if ( peak < StartCompression ) return color;\n\n float d = 1. - StartCompression;\n\n float newPeak = 1. - d * d / ( peak + d - StartCompression );\n\n color *= newPeak / peak;\n\n float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\n return mix( color, vec3( newPeak ), g );\n\n}\n\n\n\nvoid main() {\n vec4 color = texture2D(map, vUv);\n\n vec4 exposed = vec4(exposure * color.rgb, color.a);\n\n vec4 tonemapped = vec4(TONEMAPPING_FUNCTION(exposed.rgb), color.a);\n\n vec4 adjusted =\n brightnessMatrix( brightness ) *\n contrastMatrix( contrast ) *\n saturationMatrix( saturation ) *\n tonemapped;\n\n gl_FragColor = adjusted;\n}\n",uniforms:{map:{value:n},brightness:{value:0},contrast:{value:1},saturation:{value:1},exposure:{value:1}},blending:o,depthTest:!1,depthWrite:!1}),this._map=n,this.toneMapping=this._toneMapping=e||s,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get toneMapping(){return this._toneMapping}set toneMapping(n){let e=!1;switch(n){case s:this.defines.TONEMAPPING_FUNCTION="ACESFilmicToneMapping",e=!0;break;case u:this.defines.TONEMAPPING_FUNCTION="ReinhardToneMapping",e=!0;break;case p:this.defines.TONEMAPPING_FUNCTION="CineonToneMapping",e=!0;break;case m:this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",e=!0;break;case l:this.defines.TONEMAPPING_FUNCTION="AgXToneMapping",e=!0;break;case c:this.defines.TONEMAPPING_FUNCTION="NeutralToneMapping",e=!0;break;default:console.error(`Unsupported toneMapping: ${n}. Using LinearToneMapping.`),this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",this._toneMapping=m}e&&(this._toneMapping=n),this.needsUpdate=!0}get brightness(){return this._brightness}set brightness(n){this._brightness=n,this.uniforms.brightness.value=n}get contrast(){return this._contrast}set contrast(n){this._contrast=n,this.uniforms.contrast.value=n}get saturation(){return this._saturation}set saturation(n){this._saturation=n,this.uniforms.saturation.value=n}get exposure(){return this._exposure}set exposure(n){this._exposure=n,this.uniforms.exposure.value=n}get map(){return this._map}set map(n){this._map=n,this.uniforms.map.value=n}}const F=(n,e,t,o)=>{n.needsUpdate=!0;const a=new L({width:n.image.width,height:n.image.height,type:i,colorSpace:g,material:new D({map:n,toneMapping:t}),renderer:e,renderTargetOptions:o});try{a.render()}catch(n){throw a.disposeOnDemandRenderer(),n}return a},G=n=>{const{image:t,renderer:o}=n,a=e(t),r=F(a,o,n.toneMapping,n.renderTargetOptions),i=P({...n,image:a,sdr:r,renderer:r.renderer});return{sdr:r,gainMap:i,hdr:a,getMetadata:()=>({gainMapMax:i.material.gainMapMax,gainMapMin:i.material.gainMapMin,gamma:i.material.gamma,hdrCapacityMax:i.material.hdrCapacityMax,hdrCapacityMin:i.material.hdrCapacityMin,offsetHdr:i.material.offsetHdr,offsetSdr:i.material.offsetSdr})}},k=async e=>{const t=G(e),{mimeType:o,quality:a,flipY:r,withWorker:i}=e;let s,m,c;const l=new ImageData(t.sdr.toArray(),t.sdr.width,t.sdr.height),p=new ImageData(t.gainMap.toArray(),t.gainMap.width,t.gainMap.height);if(i){const n=await Promise.all([i.compress({source:l,mimeType:o,quality:a,flipY:r}),i.compress({source:p,mimeType:o,quality:a,flipY:r})]);s=n,m=n[0].source,c=n[1].source}else s=await Promise.all([n({source:l,mimeType:o,quality:a,flipY:r}),n({source:p,mimeType:o,quality:a,flipY:r})]),m=l.data,c=p.data;return t.sdr.dispose(),t.gainMap.dispose(),{...t,...t.getMetadata(),sdr:s[0],gainMap:s[1],rawSDR:m,rawGainMap:c}},H=(n,o="max",a)=>{const r=e(n);if(r.format!==d&&r.format!==f&&r.format!==h&&r.format!==v&&r.format!==x&&r.format!==M&&r.format!==_&&r.format!==C&&r.format!==w&&r.format!==A&&r.format!==T)throw new Error("Unsupported texture format");const i=new t({vertexShader:"\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\nprecision mediump float;\n\n#ifndef CELL_SIZE\n #define CELL_SIZE 2\n#endif\n\n#ifndef COMPARE_FUNCTION\n #define COMPARE_FUNCTION max\n#endif\n\n#ifndef INITIAL_VALUE\n #define INITIAL_VALUE 0\n#endif\n\nuniform sampler2D map;\nuniform vec2 u_srcResolution;\n\nvarying vec2 vUv;\n\nvoid main() {\n // compute the first pixel the source cell\n vec2 srcPixel = floor(gl_FragCoord.xy) * float(CELL_SIZE);\n\n // one pixel in source\n vec2 onePixel = vec2(1) / u_srcResolution;\n\n // uv for first pixel in cell. +0.5 for center of pixel\n vec2 uv = (srcPixel + 0.5) * onePixel;\n\n vec4 resultColor = vec4(INITIAL_VALUE);\n\n for (int y = 0; y < CELL_SIZE; ++y) {\n for (int x = 0; x < CELL_SIZE; ++x) {\n resultColor = COMPARE_FUNCTION(resultColor, texture2D(map, uv + vec2(x, y) * onePixel));\n }\n }\n\n gl_FragColor = resultColor;\n}\n",uniforms:{u_srcResolution:{value:new E(r.image.width,r.image.height)},map:{value:r}},defines:{CELL_SIZE:2,COMPARE_FUNCTION:o,INITIAL_VALUE:"max"===o?0:65504}});r.needsUpdate=!0,i.needsUpdate=!0;let s=r.image.width,m=r.image.height;const c=new L({width:s,height:m,type:r.type,colorSpace:r.colorSpace,material:i,renderer:a}),l=[];for(;s>1||m>1;){s=Math.max(1,(s+2-1)/2|0),m=Math.max(1,(m+2-1)/2|0);const n=new I(s,m,{type:c.type,format:r.format,colorSpace:c.colorSpace,minFilter:N,magFilter:N,wrapS:y,wrapT:y,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});l.push(n)}s=r.image.width,m=r.image.height,l.forEach(n=>{s=Math.max(1,(s+2-1)/2|0),m=Math.max(1,(m+2-1)/2|0),c.renderTarget=n,c.render(),i.uniforms.map.value=n.texture,i.uniforms.u_srcResolution.value.x=s,i.uniforms.u_srcResolution.value.y=m});const p=c.toArray();return c.dispose(),l.forEach(n=>n.dispose()),[c.type===S?p[0]:R.fromHalfFloat(p[0]),c.type===S?p[1]:R.fromHalfFloat(p[1]),c.type===S?p[2]:R.fromHalfFloat(p[2])]};export{B as GainMapEncoderMaterial,D as SDRMaterial,n as compress,G as encode,k as encodeAndCompress,H as findTextureMinMax,P as getGainMap,F as getSDRRendition};
|
package/dist/encode.umd.cjs
CHANGED
package/dist/encode.umd.min.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.7.
|
|
2
|
+
* @monogrid/gainmap-js v3.7.1
|
|
3
3
|
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
4
|
*/
|
|
5
5
|
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three")):"function"==typeof define&&define.amd?define(["exports","three"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).encode={},e.three)}(this,function(e,t){"use strict";const n=async e=>{if("undefined"==typeof createImageBitmap)throw new Error("createImageBitmap() not supported.");const{source:t,mimeType:n,quality:r,flipY:a}=e;let o;if((t instanceof Uint8Array||t instanceof Uint8ClampedArray)&&"sourceMimeType"in e)o=new Blob([t],{type:e.sourceMimeType});else{if(!(t instanceof ImageData))throw new Error("Invalid source image");o=t}const i=await createImageBitmap(o),s=i.width,p=i.height;let l;"undefined"!=typeof OffscreenCanvas?l=new OffscreenCanvas(s,p):(l=document.createElement("canvas"),l.width=s,l.height=p);const c=l.getContext("2d");if(!c)throw new Error("Failed to create canvas Context");!0===a&&(c.translate(0,p),c.scale(1,-1)),c.drawImage(i,0,0,s,p);const d=await(async(e,t,n)=>{if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return e.convertToBlob({type:t,quality:n});if(e instanceof HTMLCanvasElement)return new Promise((r,a)=>{e.toBlob(e=>{e?r(e):a(new Error("Failed to convert canvas to blob"))},t,n)});throw new Error("Unsupported canvas element")})(l,n,r||.9);return{data:new Uint8Array(await d.arrayBuffer()),mimeType:n,width:s,height:p}},r=e=>{let n;if(e instanceof t.DataTexture){if(!(e.image.data instanceof Uint16Array||e.image.data instanceof Float32Array))throw new Error("Provided image is not HDR");n=e}else{if(!e.data||!e.width||!e.height)throw new Error("Provided image has no data or size");n=new t.DataTexture(e.data,e.width,e.height,e.format??t.RGBAFormat,e.type,t.UVMapping,t.RepeatWrapping,t.RepeatWrapping,t.LinearFilter,t.LinearFilter,1,"colorSpace"in e&&"srgb"===e.colorSpace?e.colorSpace:t.LinearSRGBColorSpace),"header"in e&&"gamma"in e&&(n.flipY=!0),n.needsUpdate=!0}return n},a=(e,n,r)=>{let a;switch(e){case t.UnsignedByteType:a=new Uint8ClampedArray(n*r*4);break;case t.HalfFloatType:a=new Uint16Array(n*r*4);break;case t.UnsignedIntType:a=new Uint32Array(n*r*4);break;case t.ByteType:a=new Int8Array(n*r*4);break;case t.ShortType:a=new Int16Array(n*r*4);break;case t.IntType:a=new Int32Array(n*r*4);break;case t.FloatType:a=new Float32Array(n*r*4);break;default:throw new Error("Unsupported data type")}return a};let o;class i{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(e){this._width=e.width,this._height=e.height,this._type=e.type,this._colorSpace=e.colorSpace;const n={format:t.RGBAFormat,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:void 0!==e.renderTargetOptions?.anisotropy?e.renderTargetOptions?.anisotropy:1,generateMipmaps:void 0!==e.renderTargetOptions?.generateMipmaps&&e.renderTargetOptions?.generateMipmaps,magFilter:void 0!==e.renderTargetOptions?.magFilter?e.renderTargetOptions?.magFilter:t.LinearFilter,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:t.LinearFilter,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:t.ClampToEdgeWrapping,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:t.ClampToEdgeWrapping};if(this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=i.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new t.Scene,this._camera=new t.OrthographicCamera,this._camera.position.set(0,0,10),this._camera.left=-.5,this._camera.right=.5,this._camera.top=.5,this._camera.bottom=-.5,this._camera.updateProjectionMatrix(),!((e,n,r,i)=>{if(void 0!==o)return o;const s=new t.WebGLRenderTarget(1,1,i);n.setRenderTarget(s);const p=new t.Mesh(new t.PlaneGeometry,new t.MeshBasicMaterial({color:16777215}));n.render(p,r),n.setRenderTarget(null);const l=a(e,s.width,s.height);return n.readRenderTargetPixels(s,0,0,s.width,s.height,l),s.dispose(),p.geometry.dispose(),p.material.dispose(),o=0!==l[0],o})(this._type,this._renderer,this._camera,n)){let e;if(this._type===t.HalfFloatType)e=this._renderer.extensions.has("EXT_color_buffer_float")?t.FloatType:void 0;void 0!==e?(console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${t.FloatType}`),this._type=e):(this._supportsReadPixels=!1,console.warn("This browser dos not support toArray or toDataTexture, calls to those methods will result in an error thrown"))}this._quad=new t.Mesh(new t.PlaneGeometry,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new t.WebGLRenderTarget(this.width,this.height,n),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:t.UVMapping}static instantiateRenderer(){const e=new t.WebGLRenderer;return e.setSize(128,128),e}render=()=>{this._renderer.setRenderTarget(this._renderTarget);try{this._renderer.render(this._scene,this._camera)}catch(e){throw this._renderer.setRenderTarget(null),e}this._renderer.setRenderTarget(null)};toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=a(this._type,this._width,this._height);return this._renderer.readRenderTargetPixels(this._renderTarget,0,0,this._width,this._height,e),e}toDataTexture(e){const n=new t.DataTexture(this.toArray(),this.width,this.height,t.RGBAFormat,this._type,e?.mapping||t.UVMapping,e?.wrapS||t.ClampToEdgeWrapping,e?.wrapT||t.ClampToEdgeWrapping,e?.magFilter||t.LinearFilter,e?.minFilter||t.LinearFilter,e?.anisotropy||1,t.LinearSRGBColorSpace);return n.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,n}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&(this._renderer.dispose(),this._renderer.forceContextLoss())}dispose(e){this.disposeOnDemandRenderer(),e&&this.renderTarget.dispose(),this.material instanceof t.ShaderMaterial&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof t.Texture&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof t.Texture&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose()}get width(){return this._width}set width(e){this._width=e,this._renderTarget.setSize(this._width,this._height)}get height(){return this._height}set height(e){this._height=e,this._renderTarget.setSize(this._width,this._height)}get renderer(){return this._renderer}get renderTarget(){return this._renderTarget}set renderTarget(e){this._renderTarget=e,this._width=e.width,this._height=e.height}get material(){return this._material}get type(){return this._type}get colorSpace(){return this._colorSpace}}const s=1.0001,p=e=>{console.warn(`gainmap-js: maxContentBoost is ${e} (<= 1), the source image has no HDR content. It will be clamped to 1.0001 and the result will be equivalent to an SDR image.`)},l=(e,t)=>{console.warn(`gainmap-js: minContentBoost (${e}) must be lower than maxContentBoost (${t}), the resulting gain map will be invalid.`)};class c extends t.ShaderMaterial{_minContentBoost;_maxContentBoost;_offsetSdr;_offsetHdr;_gamma;constructor({sdr:e,hdr:n,offsetSdr:r,offsetHdr:a,maxContentBoost:o,minContentBoost:i,gamma:c}){if(!o)throw new Error("maxContentBoost is required");if(!e)throw new Error("sdr is required");if(!n)throw new Error("hdr is required");const d=c||[1,1,1],m=r||[1/64,1/64,1/64],h=a||[1/64,1/64,1/64];o<=1&&p(o);const g=i||1,u=Math.max(o,s);g>=u&&l(g,u),super({name:"GainMapEncoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform sampler2D sdr;\nuniform sampler2D hdr;\nuniform vec3 gamma;\nuniform vec3 offsetSdr;\nuniform vec3 offsetHdr;\nuniform float minLog2;\nuniform float maxLog2;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 sdrColor = texture2D(sdr, vUv).rgb;\n vec3 hdrColor = texture2D(hdr, vUv).rgb;\n\n vec3 pixelGain = (hdrColor + offsetHdr) / (sdrColor + offsetSdr);\n vec3 logRecovery = (log2(pixelGain) - minLog2) / (maxLog2 - minLog2);\n vec3 clampedRecovery = saturate(logRecovery);\n gl_FragColor = vec4(pow(clampedRecovery, gamma), 1.0);\n}\n",uniforms:{sdr:{value:e},hdr:{value:n},gamma:{value:(new t.Vector3).fromArray(d)},offsetSdr:{value:(new t.Vector3).fromArray(m)},offsetHdr:{value:(new t.Vector3).fromArray(h)},minLog2:{value:Math.log2(g)},maxLog2:{value:Math.log2(u)}},blending:t.NoBlending,depthTest:!1,depthWrite:!1}),this._minContentBoost=g,this._maxContentBoost=u,this._offsetSdr=m,this._offsetHdr=h,this._gamma=d,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get gamma(){return this._gamma}set gamma(e){this._gamma=e,this.uniforms.gamma.value=(new t.Vector3).fromArray(e)}get offsetHdr(){return this._offsetHdr}set offsetHdr(e){this._offsetHdr=e,this.uniforms.offsetHdr.value=(new t.Vector3).fromArray(e)}get offsetSdr(){return this._offsetSdr}set offsetSdr(e){this._offsetSdr=e,this.uniforms.offsetSdr.value=(new t.Vector3).fromArray(e)}get minContentBoost(){return this._minContentBoost}set minContentBoost(e){e>=this._maxContentBoost&&l(e,this._maxContentBoost),this._minContentBoost=e,this.uniforms.minLog2.value=Math.log2(e)}get maxContentBoost(){return this._maxContentBoost}set maxContentBoost(e){e<=1&&p(e);const t=Math.max(e,s);this._minContentBoost>=t&&l(this._minContentBoost,t),this._maxContentBoost=t,this.uniforms.maxLog2.value=Math.log2(t)}get gainMapMin(){return[Math.log2(this._minContentBoost),Math.log2(this._minContentBoost),Math.log2(this._minContentBoost)]}get gainMapMax(){return[Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost)]}get hdrCapacityMin(){return Math.min(Math.max(0,this.gainMapMin[0]),Math.max(0,this.gainMapMin[1]),Math.max(0,this.gainMapMin[2]))}get hdrCapacityMax(){return Math.max(Math.max(0,this.gainMapMax[0]),Math.max(0,this.gainMapMax[1]),Math.max(0,this.gainMapMax[2]))}}const d=e=>{const{image:n,sdr:a,renderer:o}=e,s=r(n),p=new c({...e,sdr:a.renderTarget.texture,hdr:s}),l=new i({width:s.image.width,height:s.image.height,type:t.UnsignedByteType,colorSpace:t.LinearSRGBColorSpace,material:p,renderer:o,renderTargetOptions:e.renderTargetOptions});try{l.render()}catch(e){throw l.disposeOnDemandRenderer(),e}return l};class m extends t.ShaderMaterial{_brightness=0;_contrast=1;_saturation=1;_exposure=1;_toneMapping;_map;constructor({map:e,toneMapping:n}){super({name:"SDRMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n\nuniform sampler2D map;\nuniform float brightness;\nuniform float contrast;\nuniform float saturation;\nuniform float exposure;\n\nvarying vec2 vUv;\n\nmat4 brightnessMatrix( float brightness ) {\n return mat4(\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n brightness, brightness, brightness, 1\n );\n}\n\nmat4 contrastMatrix( float contrast ) {\n float t = ( 1.0 - contrast ) / 2.0;\n return mat4(\n contrast, 0, 0, 0,\n 0, contrast, 0, 0,\n 0, 0, contrast, 0,\n t, t, t, 1\n );\n}\n\nmat4 saturationMatrix( float saturation ) {\n vec3 luminance = vec3( 0.3086, 0.6094, 0.0820 );\n float oneMinusSat = 1.0 - saturation;\n vec3 red = vec3( luminance.x * oneMinusSat );\n red+= vec3( saturation, 0, 0 );\n vec3 green = vec3( luminance.y * oneMinusSat );\n green += vec3( 0, saturation, 0 );\n vec3 blue = vec3( luminance.z * oneMinusSat );\n blue += vec3( 0, 0, saturation );\n return mat4(\n red, 0,\n green, 0,\n blue, 0,\n 0, 0, 0, 1\n );\n}\n\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\n\nvec3 ACESFilmicToneMapping( vec3 color ) {\n // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source\n vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n // ODT_SAT => XYZ => D60_2_D65 => sRGB\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source\n vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color = ACESInputMat * color;\n // Apply RRT and ODT\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n // Clamp to [0, 1]\n return saturate( color );\n}\n\n// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf\nvec3 ReinhardToneMapping( vec3 color ) {\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n\n// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/\nvec3 CineonToneMapping( vec3 color ) {\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n\n// nothing\nvec3 LinearToneMapping ( vec3 color ) {\n return color;\n}\n\n// Matrices for rec 2020 <> rec 709 color space conversion\n// matrix provided in row-major order so it has been transposed\n// https://www.itu.int/pub/R-REP-BT.2407-2017\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\n\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\n\n// https://iolite-engine.com/blog_posts/minimal_agx_implementation\n// Mean error^2: 3.6705141e-06\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\n\n// AgX Tone Mapping implementation based on Filament, which in turn is based\n// on Blender's implementation using rec 2020 primaries\n// https://github.com/google/filament/pull/7236\n// Inputs and outputs are encoded as Linear-sRGB.\n\nvec3 AgXToneMapping( vec3 color ) {\n\n // AgX constants\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n\n // explicit AgXOutsetMatrix generated from Filaments AgXOutsetMatrixInv\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n\n // LOG2_MIN = -10.0\n // LOG2_MAX = +6.5\n // MIDDLE_GRAY = 0.18\n const float AgxMinEv = - 12.47393; // log2( pow( 2, LOG2_MIN ) * MIDDLE_GRAY )\n const float AgxMaxEv = 4.026069; // log2( pow( 2, LOG2_MAX ) * MIDDLE_GRAY )\n\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\n color = AgXInsetMatrix * color;\n\n // Log2 encoding\n color = max( color, 1e-10 ); // avoid 0 or negative numbers for log2\n color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\n color = clamp( color, 0.0, 1.0 );\n\n // Apply sigmoid\n color = agxDefaultContrastApprox( color );\n\n // Apply AgX look\n // v = agxLook(v, look);\n\n color = AgXOutsetMatrix * color;\n\n // Linearize\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\n // Gamut mapping. Simple clamp for now.\n color = clamp( color, 0.0, 1.0 );\n\n return color;\n\n}\n\n// https://modelviewer.dev/examples/tone-mapping\n\nvec3 NeutralToneMapping( vec3 color ) {\n\n const float StartCompression = 0.8 - 0.04;\n const float Desaturation = 0.15;\n\n float x = min( color.r, min( color.g, color.b ) );\n\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\n color -= offset;\n\n float peak = max( color.r, max( color.g, color.b ) );\n\n if ( peak < StartCompression ) return color;\n\n float d = 1. - StartCompression;\n\n float newPeak = 1. - d * d / ( peak + d - StartCompression );\n\n color *= newPeak / peak;\n\n float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\n return mix( color, vec3( newPeak ), g );\n\n}\n\n\n\nvoid main() {\n vec4 color = texture2D(map, vUv);\n\n vec4 exposed = vec4(exposure * color.rgb, color.a);\n\n vec4 tonemapped = vec4(TONEMAPPING_FUNCTION(exposed.rgb), color.a);\n\n vec4 adjusted =\n brightnessMatrix( brightness ) *\n contrastMatrix( contrast ) *\n saturationMatrix( saturation ) *\n tonemapped;\n\n gl_FragColor = adjusted;\n}\n",uniforms:{map:{value:e},brightness:{value:0},contrast:{value:1},saturation:{value:1},exposure:{value:1}},blending:t.NoBlending,depthTest:!1,depthWrite:!1}),this._map=e,this.toneMapping=this._toneMapping=n||t.ACESFilmicToneMapping,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get toneMapping(){return this._toneMapping}set toneMapping(e){let n=!1;switch(e){case t.ACESFilmicToneMapping:this.defines.TONEMAPPING_FUNCTION="ACESFilmicToneMapping",n=!0;break;case t.ReinhardToneMapping:this.defines.TONEMAPPING_FUNCTION="ReinhardToneMapping",n=!0;break;case t.CineonToneMapping:this.defines.TONEMAPPING_FUNCTION="CineonToneMapping",n=!0;break;case t.LinearToneMapping:this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",n=!0;break;case t.AgXToneMapping:this.defines.TONEMAPPING_FUNCTION="AgXToneMapping",n=!0;break;case t.NeutralToneMapping:this.defines.TONEMAPPING_FUNCTION="NeutralToneMapping",n=!0;break;default:console.error(`Unsupported toneMapping: ${e}. Using LinearToneMapping.`),this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",this._toneMapping=t.LinearToneMapping}n&&(this._toneMapping=e),this.needsUpdate=!0}get brightness(){return this._brightness}set brightness(e){this._brightness=e,this.uniforms.brightness.value=e}get contrast(){return this._contrast}set contrast(e){this._contrast=e,this.uniforms.contrast.value=e}get saturation(){return this._saturation}set saturation(e){this._saturation=e,this.uniforms.saturation.value=e}get exposure(){return this._exposure}set exposure(e){this._exposure=e,this.uniforms.exposure.value=e}get map(){return this._map}set map(e){this._map=e,this.uniforms.map.value=e}}const h=(e,n,r,a)=>{e.needsUpdate=!0;const o=new i({width:e.image.width,height:e.image.height,type:t.UnsignedByteType,colorSpace:t.SRGBColorSpace,material:new m({map:e,toneMapping:r}),renderer:n,renderTargetOptions:a});try{o.render()}catch(e){throw o.disposeOnDemandRenderer(),e}return o},g=e=>{const{image:t,renderer:n}=e,a=r(t),o=h(a,n,e.toneMapping,e.renderTargetOptions),i=d({...e,image:a,sdr:o,renderer:o.renderer});return{sdr:o,gainMap:i,hdr:a,getMetadata:()=>({gainMapMax:i.material.gainMapMax,gainMapMin:i.material.gainMapMin,gamma:i.material.gamma,hdrCapacityMax:i.material.hdrCapacityMax,hdrCapacityMin:i.material.hdrCapacityMin,offsetHdr:i.material.offsetHdr,offsetSdr:i.material.offsetSdr})}};e.GainMapEncoderMaterial=c,e.SDRMaterial=m,e.compress=n,e.encode=g,e.encodeAndCompress=async e=>{const t=g(e),{mimeType:r,quality:a,flipY:o,withWorker:i}=e;let s,p,l;const c=new ImageData(t.sdr.toArray(),t.sdr.width,t.sdr.height),d=new ImageData(t.gainMap.toArray(),t.gainMap.width,t.gainMap.height);if(i){const e=await Promise.all([i.compress({source:c,mimeType:r,quality:a,flipY:o}),i.compress({source:d,mimeType:r,quality:a,flipY:o})]);s=e,p=e[0].source,l=e[1].source}else s=await Promise.all([n({source:c,mimeType:r,quality:a,flipY:o}),n({source:d,mimeType:r,quality:a,flipY:o})]),p=c.data,l=d.data;return t.sdr.dispose(),t.gainMap.dispose(),{...t,...t.getMetadata(),sdr:s[0],gainMap:s[1],rawSDR:p,rawGainMap:l}},e.findTextureMinMax=(e,n="max",a)=>{const o=r(e);if(o.format!==t.AlphaFormat&&o.format!==t.RGBFormat&&o.format!==t.RGBAFormat&&o.format!==t.DepthFormat&&o.format!==t.DepthStencilFormat&&o.format!==t.RedFormat&&o.format!==t.RedIntegerFormat&&o.format!==t.RGFormat&&o.format!==t.RGIntegerFormat&&o.format!==t.RGBIntegerFormat&&o.format!==t.RGBAIntegerFormat)throw new Error("Unsupported texture format");const s=new t.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\nprecision mediump float;\n\n#ifndef CELL_SIZE\n #define CELL_SIZE 2\n#endif\n\n#ifndef COMPARE_FUNCTION\n #define COMPARE_FUNCTION max\n#endif\n\n#ifndef INITIAL_VALUE\n #define INITIAL_VALUE 0\n#endif\n\nuniform sampler2D map;\nuniform vec2 u_srcResolution;\n\nvarying vec2 vUv;\n\nvoid main() {\n // compute the first pixel the source cell\n vec2 srcPixel = floor(gl_FragCoord.xy) * float(CELL_SIZE);\n\n // one pixel in source\n vec2 onePixel = vec2(1) / u_srcResolution;\n\n // uv for first pixel in cell. +0.5 for center of pixel\n vec2 uv = (srcPixel + 0.5) * onePixel;\n\n vec4 resultColor = vec4(INITIAL_VALUE);\n\n for (int y = 0; y < CELL_SIZE; ++y) {\n for (int x = 0; x < CELL_SIZE; ++x) {\n resultColor = COMPARE_FUNCTION(resultColor, texture2D(map, uv + vec2(x, y) * onePixel));\n }\n }\n\n gl_FragColor = resultColor;\n}\n",uniforms:{u_srcResolution:{value:new t.Vector2(o.image.width,o.image.height)},map:{value:o}},defines:{CELL_SIZE:2,COMPARE_FUNCTION:n,INITIAL_VALUE:"max"===n?0:65504}});o.needsUpdate=!0,s.needsUpdate=!0;let p=o.image.width,l=o.image.height;const c=new i({width:p,height:l,type:o.type,colorSpace:o.colorSpace,material:s,renderer:a}),d=[];for(;p>1||l>1;){p=Math.max(1,(p+2-1)/2|0),l=Math.max(1,(l+2-1)/2|0);const e=new t.WebGLRenderTarget(p,l,{type:c.type,format:o.format,colorSpace:c.colorSpace,minFilter:t.NearestFilter,magFilter:t.NearestFilter,wrapS:t.ClampToEdgeWrapping,wrapT:t.ClampToEdgeWrapping,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});d.push(e)}p=o.image.width,l=o.image.height,d.forEach(e=>{p=Math.max(1,(p+2-1)/2|0),l=Math.max(1,(l+2-1)/2|0),c.renderTarget=e,c.render(),s.uniforms.map.value=e.texture,s.uniforms.u_srcResolution.value.x=p,s.uniforms.u_srcResolution.value.y=l});const m=c.toArray();return c.dispose(),d.forEach(e=>e.dispose()),[c.type===t.FloatType?m[0]:t.DataUtils.fromHalfFloat(m[0]),c.type===t.FloatType?m[1]:t.DataUtils.fromHalfFloat(m[1]),c.type===t.FloatType?m[2]:t.DataUtils.fromHalfFloat(m[2])]},e.getGainMap=d,e.getSDRRendition=h});
|
package/dist/encode.webgpu.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.7.
|
|
2
|
+
* @monogrid/gainmap-js v3.7.1
|
|
3
3
|
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import { R as RenderTargetNode, G as GainMapNode } from './GainMapNode-
|
|
7
|
-
import { c as compress } from './compress-
|
|
6
|
+
import { R as RenderTargetNode, G as GainMapNode } from './GainMapNode-Dl8yqSVg.js';
|
|
7
|
+
import { c as compress } from './compress-DA31yhmz.js';
|
|
8
8
|
import { vec4, uniform, textureLoad, Fn, screenCoordinate, float, ivec2, min, vec2, max, texture, log2, saturate, pow, toneMapping, mat4, vec3 } from 'three/tsl';
|
|
9
9
|
import { RendererUtils, QuadMesh, NodeMaterial, Texture, Vector2, RenderTarget, NearestFilter, FloatType, NoBlending, LinearFilter, LinearSRGBColorSpace, UnsignedByteType, Vector3, ACESFilmicToneMapping, SRGBColorSpace, TextureNode } from 'three/webgpu';
|
|
10
|
-
import { g as getDataTexture } from './get-data-texture-
|
|
10
|
+
import { g as getDataTexture } from './get-data-texture-CpszSMzv.js';
|
|
11
11
|
import 'three';
|
|
12
12
|
|
|
13
13
|
/**
|
|
@@ -421,7 +421,8 @@ class SDRRenditionNode extends RenderTargetNode {
|
|
|
421
421
|
const u = this.uniforms;
|
|
422
422
|
const color = vec4(this.hdr);
|
|
423
423
|
// exposure is applied here rather than by the tone mapping function, so it works with `NoToneMapping` too
|
|
424
|
-
|
|
424
|
+
// `.rgb` because ToneMappingNode declares a vec3 but its setup returns a vec4 (colour + alpha) when a tone mapping is set
|
|
425
|
+
const toneMapped = vec4(toneMapping(this._toneMapping, float(1), color.rgb.mul(u.exposure)).rgb, color.a);
|
|
425
426
|
const b = u.brightness;
|
|
426
427
|
const brightnessMatrix = mat4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, b, b, b, 1);
|
|
427
428
|
const c = u.contrast;
|