@monogrid/gainmap-js 3.6.0 → 3.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +86 -13
- package/dist/GainMapNode-CntuYSg-.js +338 -0
- package/dist/GainMapNode-DtVNqKtN.js +5 -0
- package/dist/{warn-deprecated-Bk17fVbj.js → Loader-D82gF-Rq.js} +3 -19
- package/dist/{warn-deprecated-D0kPpXtA.js → Loader-EFF6JZel.js} +2 -2
- package/dist/{QuadRenderer-CXtNzoCY.js → QuadRenderer-DD6leG7y.js} +1 -1
- package/dist/{QuadRenderer-DcBTBLz6.js → QuadRenderer-DoK2pW5M.js} +1 -1
- package/dist/{_commonjsHelpers-CnYhShyx.js → _commonjsHelpers-C0JuzTK_.js} +1 -1
- package/dist/{_commonjsHelpers-Cdw2adc2.js → _commonjsHelpers-p2JmW4Hh.js} +1 -1
- package/dist/{compress-C42bpk6O.js → compress-BTsSIi_B.js} +1 -1
- package/dist/{compress-CzMz2bpX.js → compress-PmebyFxR.js} +1 -1
- package/dist/core/webgpu/RenderTargetNode.d.ts +79 -0
- package/dist/decode/shared/utils/warn-deprecated.d.ts +1 -1
- package/dist/decode/webgl/decode.d.ts +0 -1
- package/dist/decode/webgl/index.d.ts +0 -1
- package/dist/decode/webgl/loaders/GainMapLoader.d.ts +1 -3
- package/dist/decode/webgl/loaders/HDRJPGLoader.d.ts +1 -3
- package/dist/decode/webgl/materials/GainMapDecoderMaterial.d.ts +0 -1
- package/dist/decode/webgpu/nodes/GainMapNode.d.ts +17 -18
- package/dist/decode.js +5 -18
- package/dist/decode.min.js +2 -2
- package/dist/decode.umd.cjs +1 -30
- package/dist/decode.umd.min.cjs +2 -2
- package/dist/decode.webgpu.js +41 -228
- package/dist/decode.webgpu.min.js +2 -2
- package/dist/decode.webgpu.umd.cjs +186 -62
- package/dist/decode.webgpu.umd.min.cjs +2 -2
- package/dist/encode/webgpu/GainMapEncoder.d.ts +142 -0
- package/dist/encode/webgpu/find-texture-min-max.d.ts +27 -0
- package/dist/encode/webgpu/index.d.ts +8 -0
- package/dist/encode/webgpu/nodes/GainMapEncoderNode.d.ts +92 -0
- package/dist/encode/webgpu/nodes/SDRRenditionNode.d.ts +120 -0
- package/dist/encode/webgpu/read-render-target-pixels.d.ts +11 -0
- package/dist/encode.js +5 -36
- 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 +635 -0
- package/dist/encode.webgpu.min.js +5 -0
- package/dist/encode.webgpu.umd.cjs +1081 -0
- package/dist/encode.webgpu.umd.min.cjs +5 -0
- package/dist/get-data-texture-CkaFVcv-.js +5 -0
- package/dist/get-data-texture-DkHkbczN.js +40 -0
- package/dist/{iso-gainmap-metadata-CEaaU7RT.js → iso-gainmap-metadata-BJxZGPtk.js} +1 -1
- package/dist/{iso-gainmap-metadata-ByNqnUPn.js → iso-gainmap-metadata-Bx6ha9th.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 +10 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.
|
|
2
|
+
* @monogrid/gainmap-js v3.7.0
|
|
3
3
|
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
4
|
*/
|
|
5
5
|
|
|
@@ -669,7 +669,20 @@
|
|
|
669
669
|
if (!this._supportsReadPixels)
|
|
670
670
|
throw new Error('Can\'t read pixels in this browser');
|
|
671
671
|
const out = await this._renderer.readRenderTargetPixelsAsync(this._renderTarget, 0, 0, this._width, this._height);
|
|
672
|
-
|
|
672
|
+
if (!this._renderer.backend.isWebGPUBackend) {
|
|
673
|
+
return out;
|
|
674
|
+
}
|
|
675
|
+
// the WebGPU backend returns rows top-down, each padded to 256 bytes,
|
|
676
|
+
// the WebGL backend returns tightly packed rows bottom-up:
|
|
677
|
+
// repack to the WebGL layout so both backends return the same data
|
|
678
|
+
const rowLength = this._width * 4;
|
|
679
|
+
const paddedRowLength = Math.ceil(rowLength * out.BYTES_PER_ELEMENT / 256) * 256 / out.BYTES_PER_ELEMENT;
|
|
680
|
+
const packed = new out.constructor(rowLength * this._height);
|
|
681
|
+
for (let y = 0; y < this._height; y++) {
|
|
682
|
+
const start = (this._height - 1 - y) * paddedRowLength;
|
|
683
|
+
packed.set(out.subarray(start, start + rowLength), y * rowLength);
|
|
684
|
+
}
|
|
685
|
+
return packed;
|
|
673
686
|
}
|
|
674
687
|
/**
|
|
675
688
|
* Performs a readPixel operation in the renderTarget
|
|
@@ -1260,6 +1273,129 @@
|
|
|
1260
1273
|
}
|
|
1261
1274
|
}
|
|
1262
1275
|
|
|
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
|
+
|
|
1263
1399
|
// max half float value
|
|
1264
1400
|
const HALF_FLOAT_MAX = 65504;
|
|
1265
1401
|
/**
|
|
@@ -1294,33 +1430,25 @@
|
|
|
1294
1430
|
* scene.backgroundNode = hdr.sample(equirectUV())
|
|
1295
1431
|
* hdr.maxDisplayBoost.value = 2 // re-decodes once, on the next frame
|
|
1296
1432
|
*/
|
|
1297
|
-
class GainMapNode extends
|
|
1433
|
+
class GainMapNode extends RenderTargetNode {
|
|
1298
1434
|
static get type() { return 'GainMapNode'; }
|
|
1299
1435
|
/**
|
|
1300
1436
|
* Shared textures and uniforms
|
|
1301
1437
|
*/
|
|
1302
1438
|
uniforms;
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
renderTarget;
|
|
1307
|
-
_quadMesh;
|
|
1308
|
-
_material;
|
|
1309
|
-
// filled by RendererUtils.resetRendererState
|
|
1310
|
-
_rendererState = {};
|
|
1311
|
-
_state = [];
|
|
1439
|
+
// set when the textures are produced by other render target nodes (e.g. a gain map encoder)
|
|
1440
|
+
_sdrSource = null;
|
|
1441
|
+
_gainMapSource = null;
|
|
1312
1442
|
constructor() {
|
|
1313
|
-
const
|
|
1443
|
+
const material = new webgpu.MeshBasicNodeMaterial();
|
|
1444
|
+
material.name = 'GainMapDecoder';
|
|
1445
|
+
super(material, {
|
|
1314
1446
|
type: webgpu.HalfFloatType,
|
|
1315
1447
|
colorSpace: webgpu.LinearSRGBColorSpace,
|
|
1316
|
-
depthBuffer: false,
|
|
1317
1448
|
generateMipmaps: true,
|
|
1318
1449
|
minFilter: webgpu.LinearMipmapLinearFilter,
|
|
1319
1450
|
magFilter: webgpu.LinearFilter
|
|
1320
1451
|
});
|
|
1321
|
-
super(renderTarget.texture);
|
|
1322
|
-
this.renderTarget = renderTarget;
|
|
1323
|
-
this.updateBeforeType = webgpu.NodeUpdateType.RENDER;
|
|
1324
1452
|
const u = this.uniforms = {
|
|
1325
1453
|
sdr: tsl.texture(new webgpu.Texture()),
|
|
1326
1454
|
gainMap: tsl.texture(new webgpu.Texture()),
|
|
@@ -1337,10 +1465,7 @@
|
|
|
1337
1465
|
const logBoost = tsl.mix(u.gainMapMin, u.gainMapMax, logRecovery);
|
|
1338
1466
|
const weight = tsl.saturate(tsl.log2(u.maxDisplayBoost).sub(u.hdrCapacityMin).div(u.hdrCapacityMax.sub(u.hdrCapacityMin)));
|
|
1339
1467
|
const hdr = u.sdr.rgb.add(u.offsetSdr).mul(tsl.exp2(logBoost.mul(weight))).sub(u.offsetHdr);
|
|
1340
|
-
|
|
1341
|
-
this._material.name = 'GainMapDecoder';
|
|
1342
|
-
this._material.colorNode = tsl.vec4(hdr.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX), 1);
|
|
1343
|
-
this._quadMesh = new webgpu.QuadMesh(this._material);
|
|
1468
|
+
material.colorNode = tsl.vec4(hdr.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX), 1);
|
|
1344
1469
|
}
|
|
1345
1470
|
/** The SDR rendition texture (sRGB) */
|
|
1346
1471
|
get sdr() { return this.uniforms.sdr.value; }
|
|
@@ -1366,19 +1491,32 @@
|
|
|
1366
1491
|
*/
|
|
1367
1492
|
get maxDisplayBoost() { return this.uniforms.maxDisplayBoost; }
|
|
1368
1493
|
/** Width of the SDR image, 0 until loaded */
|
|
1369
|
-
get width() {
|
|
1494
|
+
get width() {
|
|
1495
|
+
if (this._sdrSource)
|
|
1496
|
+
return this._sdrSource.width;
|
|
1497
|
+
return this.sdr.image?.width ?? 0;
|
|
1498
|
+
}
|
|
1370
1499
|
/** Height of the SDR image, 0 until loaded */
|
|
1371
|
-
get height() {
|
|
1500
|
+
get height() {
|
|
1501
|
+
if (this._sdrSource)
|
|
1502
|
+
return this._sdrSource.height;
|
|
1503
|
+
return this.sdr.image?.height ?? 0;
|
|
1504
|
+
}
|
|
1372
1505
|
/**
|
|
1373
1506
|
* Sets the SDR and gain map textures.
|
|
1374
1507
|
* The SDR texture is expected in sRGB color space, the gain map in linear.
|
|
1375
1508
|
*
|
|
1509
|
+
* Render target nodes (e.g. the `sdr` and `gainMap` nodes of a `GainMapEncoder`) are accepted as well:
|
|
1510
|
+
* they are rendered before decoding and the image is decoded again whenever they change.
|
|
1511
|
+
*
|
|
1376
1512
|
* @param sdr
|
|
1377
1513
|
* @param gainMap
|
|
1378
1514
|
*/
|
|
1379
1515
|
setTextures(sdr, gainMap) {
|
|
1380
|
-
this.
|
|
1381
|
-
this.
|
|
1516
|
+
this._sdrSource = sdr instanceof RenderTargetNode ? sdr : null;
|
|
1517
|
+
this._gainMapSource = gainMap instanceof RenderTargetNode ? gainMap : null;
|
|
1518
|
+
this.uniforms.sdr.value = sdr instanceof RenderTargetNode ? sdr.value : sdr;
|
|
1519
|
+
this.uniforms.gainMap.value = gainMap instanceof RenderTargetNode ? gainMap.value : gainMap;
|
|
1382
1520
|
// size the render target right away, so `value` has its final size before the first decode
|
|
1383
1521
|
if (this.width > 0 && this.height > 0)
|
|
1384
1522
|
this.renderTarget.setSize(this.width, this.height);
|
|
@@ -1402,7 +1540,7 @@
|
|
|
1402
1540
|
u.maxDisplayBoost.value = Math.pow(2, metadata.hdrCapacityMax);
|
|
1403
1541
|
return this;
|
|
1404
1542
|
}
|
|
1405
|
-
|
|
1543
|
+
_getState() {
|
|
1406
1544
|
const u = this.uniforms;
|
|
1407
1545
|
return [
|
|
1408
1546
|
this.sdr.id, this.sdr.version, this.gainMap.id, this.gainMap.version,
|
|
@@ -1411,6 +1549,17 @@
|
|
|
1411
1549
|
u.hdrCapacityMin.value, u.hdrCapacityMax.value, u.maxDisplayBoost.value
|
|
1412
1550
|
];
|
|
1413
1551
|
}
|
|
1552
|
+
_getDependencies() {
|
|
1553
|
+
const dependencies = [];
|
|
1554
|
+
if (this._sdrSource)
|
|
1555
|
+
dependencies.push(this._sdrSource);
|
|
1556
|
+
if (this._gainMapSource)
|
|
1557
|
+
dependencies.push(this._gainMapSource);
|
|
1558
|
+
return dependencies;
|
|
1559
|
+
}
|
|
1560
|
+
_onRender() {
|
|
1561
|
+
this.value.needsPMREMUpdate = true;
|
|
1562
|
+
}
|
|
1414
1563
|
/**
|
|
1415
1564
|
* Decodes the image into {@link GainMapNode.renderTarget}, only if something changed since the last decode.
|
|
1416
1565
|
*
|
|
@@ -1420,52 +1569,27 @@
|
|
|
1420
1569
|
* @returns `true` if the image was decoded
|
|
1421
1570
|
*/
|
|
1422
1571
|
decode(renderer) {
|
|
1423
|
-
|
|
1424
|
-
if (this.width === 0 || this.height === 0)
|
|
1425
|
-
return false;
|
|
1426
|
-
const state = this._currentState();
|
|
1427
|
-
if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
|
|
1428
|
-
return false;
|
|
1429
|
-
this._state = state;
|
|
1430
|
-
webgpu.RendererUtils.resetRendererState(renderer, this._rendererState);
|
|
1431
|
-
renderer.setRenderTarget(this.renderTarget);
|
|
1432
|
-
this._quadMesh.render(renderer);
|
|
1433
|
-
webgpu.RendererUtils.restoreRendererState(renderer, this._rendererState);
|
|
1434
|
-
this.value.needsPMREMUpdate = true;
|
|
1435
|
-
return true;
|
|
1572
|
+
return this.render(renderer);
|
|
1436
1573
|
}
|
|
1574
|
+
/**
|
|
1575
|
+
* Calls {@link GainMapNode.decode} once per render, before the node is evaluated.
|
|
1576
|
+
*
|
|
1577
|
+
* @param frame
|
|
1578
|
+
*/
|
|
1437
1579
|
updateBefore(frame) {
|
|
1438
1580
|
if (frame.renderer)
|
|
1439
1581
|
this.decode(frame.renderer);
|
|
1440
1582
|
return undefined;
|
|
1441
1583
|
}
|
|
1442
|
-
set value(value) {
|
|
1443
|
-
if (this.renderTarget && value !== this.renderTarget.texture) {
|
|
1444
|
-
throw new Error('GainMapNode: the value of this node is its render target texture and can\'t be replaced');
|
|
1445
|
-
}
|
|
1446
|
-
}
|
|
1447
|
-
get value() {
|
|
1448
|
-
return this.renderTarget?.texture;
|
|
1449
|
-
}
|
|
1450
|
-
/**
|
|
1451
|
-
* Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
|
|
1452
|
-
* they keep it updated before rendering as well
|
|
1453
|
-
*/
|
|
1454
|
-
clone() {
|
|
1455
|
-
const node = new webgpu.TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
|
|
1456
|
-
node.sampler = this.sampler;
|
|
1457
|
-
node.updateBeforeType = webgpu.NodeUpdateType.RENDER;
|
|
1458
|
-
node.updateBefore = (frame) => this.updateBefore(frame);
|
|
1459
|
-
return node;
|
|
1460
|
-
}
|
|
1461
1584
|
/**
|
|
1462
1585
|
* Disposes the render target, the SDR and gain map textures
|
|
1586
|
+
* (unless they belong to other render target nodes)
|
|
1463
1587
|
*/
|
|
1464
1588
|
dispose() {
|
|
1465
|
-
this.
|
|
1466
|
-
|
|
1467
|
-
this.
|
|
1468
|
-
|
|
1589
|
+
if (!this._sdrSource)
|
|
1590
|
+
this.sdr.dispose();
|
|
1591
|
+
if (!this._gainMapSource)
|
|
1592
|
+
this.gainMap.dispose();
|
|
1469
1593
|
super.dispose();
|
|
1470
1594
|
}
|
|
1471
1595
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.
|
|
2
|
+
* @monogrid/gainmap-js v3.7.0
|
|
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 l=[],m=[],c=[],f=[],u=[];for(let e=0;e<o;e++)l.push(h(!0)),m.push(h(!0)),c.push(h(!1)),f.push(h(!0)),u.push(h(!0));const M=e=>3===o?e:[e[0],e[0],e[0]];return{gainMapMin:M(l),gainMapMax:M(m),gamma:M(c),offsetSdr:M(f),offsetHdr:M(u),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 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,l=[];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,l.push(t)}if(this.options.extractNonFII&&l.length){const e=new Blob([i]),r=[];for(const t of l){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=h(e)??g(e);if(!t)throw new s("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 n("Gain map recovery image not found");return{sdr:new Uint8Array(await a[0].arrayBuffer()),gainMap:new Uint8Array(await a[1].arrayBuffer()),metadata:t}},c=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?c(a):Promise.resolve(void 0),c(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}},u=(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 f(e,t,r)}createTextures(e,t,r){return u(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");return await this._renderer.readRenderTargetPixelsAsync(this._renderTarget,0,0,this._width,this._height)}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 w=new Set,_=(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`))},x=a.vec3(-65504,-65504,-65504),v=a.vec3(65504,65504,65504);class T 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 l=(Math.log2(o)-d)/(h-d);this._weightFactorUniform=a.uniform(l,"float"),this._maxDisplayBoost=o,this._hdrCapacityMin=d,this._hdrCapacityMax=h;const m=this._sdrTexture.rgb,c=this._gainMapTexture.rgb.pow(this._gammaUniform),f=this._gainMapMinUniform.mul(c.oneMinus()).add(this._gainMapMaxUniform.mul(c)),u=a.vec3(2).pow(f.mul(this._weightFactorUniform)),M=m.add(this._offsetSdrUniform).mul(u).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 S=i({renderer:r.WebGPURenderer,createMaterial:e=>new T(e),createQuadRenderer:e=>new y(e)});class U extends M{constructor(e,t){super({renderer:e,createMaterial:e=>new T(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 C extends r.TextureNode{static get type(){return"GainMapNode"}uniforms;renderTarget;_quadMesh;_material;_rendererState={};_state=[];constructor(){const e=new r.RenderTarget(1,1,{type:r.HalfFloatType,colorSpace:r.LinearSRGBColorSpace,depthBuffer:!1,generateMipmaps:!0,minFilter:r.LinearMipmapLinearFilter,magFilter:r.LinearFilter});super(e.texture),this.renderTarget=e,this.updateBeforeType=r.NodeUpdateType.RENDER;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);this._material=new r.MeshBasicNodeMaterial,this._material.name="GainMapDecoder",this._material.colorNode=a.vec4(o.clamp(-65504,65504),1),this._quadMesh=new r.QuadMesh(this._material)}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.sdr.image?.width??0}get height(){return this.sdr.image?.height??0}setTextures(e,t){return this.uniforms.sdr.value=e,this.uniforms.gainMap.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}_currentState(){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]}decode(e){if(0===this.width||0===this.height)return!1;const t=this._currentState();return(t.length!==this._state.length||!t.every((e,t)=>e===this._state[t]))&&(this._state=t,r.RendererUtils.resetRendererState(e,this._rendererState),e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),r.RendererUtils.restoreRendererState(e,this._rendererState),this.value.needsPMREMUpdate=!0,!0)}updateBefore(e){e.renderer&&this.decode(e.renderer)}set value(e){if(this.renderTarget&&e!==this.renderTarget.texture)throw new Error("GainMapNode: 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(),this.sdr.dispose(),this.gainMap.dispose(),super.dispose()}}class R 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 f(r,a,"from-image"),{sdr:s,gainMap:o}=u(i,n,!0);e.setTextures(s,o).setMetadata(t)}}class F extends U{constructor(e,t){super(e,t),_("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 m(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=T,e.GainMapLoader=class extends U{constructor(e,t){super(e,t),_("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 l=!0,m=0,c=0,f=!0,u=0,M=0,y=!0,w=0,_=0;const x=()=>{if("function"==typeof n){n(new ProgressEvent("progress",{lengthComputable:l&&f&&y,loaded:c+M+_,total:m+u+w}))}};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=>{l=e.lengthComputable,c=e.loaded,m=e.total,x()},t=>{this.manager.itemError(e),"function"==typeof s&&s(t)});const T=new r.FileLoader(this._internalLoadingManager);T.setResponseType("arraybuffer"),T.setRequestHeader(this.requestHeader),T.setPath(this.path),T.setWithCredentials(this.withCredentials),T.load(t,async e=>{if("string"==typeof e)throw new Error("Invalid gainmap buffer");h=e,await g()},e=>{f=e.lengthComputable,M=e.loaded,u=e.total,x()},e=>{this.manager.itemError(t),"function"==typeof s&&s(e)});const S=new r.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,_=e.loaded,w=e.total,x()},e=>{this.manager.itemError(a),"function"==typeof s&&s(e)}),o}},e.GainMapNode=C,e.GainMapNodeLoader=class extends R{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=F,e.HDRJPGNodeLoader=class extends R{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 m(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=F,e.LoaderBaseShared=M,e.MPFExtractor=l,e.QuadRenderer=y,e.XMPMetadataNotFoundError=s,e.createDecodeFunction=i,e.createTextures=u,e.decode=async e=>{if(_("decode()","@monogrid/gainmap-js/webgpu","gainMapNode()"),!e.renderer)throw new Error("Renderer is required for decode function");const t=S({...e,renderer:e.renderer});try{await t.render()}catch(e){throw t.disposeOnDemandRenderer(),e}return t},e.extractGainmapFromJPEG=m,e.extractISO=h,e.extractXMP=g,e.gainMapNode=(e,t,r)=>(new C).setTextures(e,t).setMetadata(r),e.processImages=f});
|
|
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});
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { type DataTextureLoaderTexData, type WebGPURenderer } from 'three/webgpu';
|
|
2
|
+
import { type GainMapMetadata } from '../../core/types';
|
|
3
|
+
import { GainMapNode } from '../../decode/webgpu/nodes/GainMapNode';
|
|
4
|
+
import { type WorkerInterfaceImplementation } from '../../worker-types';
|
|
5
|
+
import { type CompressedImage, type CompressOptions, type GainmapEncodingParameters } from '../types';
|
|
6
|
+
import { GainMapEncoderNode } from './nodes/GainMapEncoderNode';
|
|
7
|
+
import { type HDRInput, SDRRenditionNode, type SDRRenditionNodeOptions } from './nodes/SDRRenditionNode';
|
|
8
|
+
/**
|
|
9
|
+
* Options of a {@link GainMapEncoder}
|
|
10
|
+
*
|
|
11
|
+
* @category Encoding Parameters
|
|
12
|
+
* @group Encoding Parameters
|
|
13
|
+
*/
|
|
14
|
+
export type GainMapEncoderOptions = Partial<GainmapEncodingParameters> & SDRRenditionNodeOptions;
|
|
15
|
+
/**
|
|
16
|
+
* Raw (uncompressed) result of a {@link GainMapEncoder}
|
|
17
|
+
*
|
|
18
|
+
* @category Encoding Parameters
|
|
19
|
+
* @group Encoding Parameters
|
|
20
|
+
*/
|
|
21
|
+
export type GainMapEncoderRawResult = {
|
|
22
|
+
/** SDR rendition, rows top to bottom */
|
|
23
|
+
sdr: ImageData;
|
|
24
|
+
/** Gain map, rows top to bottom */
|
|
25
|
+
gainMap: ImageData;
|
|
26
|
+
metadata: GainMapMetadata;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Compressed result of a {@link GainMapEncoder},
|
|
30
|
+
* can be passed as is to `encodeJPEGMetadata` when compressed as `image/jpeg`
|
|
31
|
+
*
|
|
32
|
+
* @category Encoding Parameters
|
|
33
|
+
* @group Encoding Parameters
|
|
34
|
+
*/
|
|
35
|
+
export type GainMapEncoderCompressedResult = GainMapMetadata & {
|
|
36
|
+
sdr: CompressedImage;
|
|
37
|
+
gainMap: CompressedImage;
|
|
38
|
+
rawSDR: Uint8ClampedArray;
|
|
39
|
+
rawGainMap: Uint8ClampedArray;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Encodes an HDR image into an SDR rendition + a gain map, on the GPU, with TSL nodes.
|
|
43
|
+
*
|
|
44
|
+
* {@link GainMapEncoder.sdr} and {@link GainMapEncoder.gainMap} are live texture nodes:
|
|
45
|
+
* every encoding parameter is a uniform, changing one re-renders the affected nodes once, when they're next used.
|
|
46
|
+
* No renderer is needed until the result is read back with {@link GainMapEncoder.read} or {@link GainMapEncoder.compress}.
|
|
47
|
+
*
|
|
48
|
+
* Read back images are oriented top to bottom (like `ImageData`), no `flipY` is needed when compressing them.
|
|
49
|
+
*
|
|
50
|
+
* @category Encoding Functions
|
|
51
|
+
* @group Encoding Functions
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* import { GainMapEncoder } from '@monogrid/gainmap-js/encode/webgpu'
|
|
55
|
+
* import { encodeJPEGMetadata } from '@monogrid/gainmap-js/libultrahdr'
|
|
56
|
+
* import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js'
|
|
57
|
+
* import { AgXToneMapping, MeshBasicNodeMaterial, WebGPURenderer } from 'three/webgpu'
|
|
58
|
+
*
|
|
59
|
+
* const renderer = new WebGPURenderer()
|
|
60
|
+
* await renderer.init()
|
|
61
|
+
*
|
|
62
|
+
* const image = await new EXRLoader().loadAsync('image.exr')
|
|
63
|
+
* const encoder = new GainMapEncoder(image, { toneMapping: AgXToneMapping })
|
|
64
|
+
* // encode the full HDR range
|
|
65
|
+
* await encoder.fitMaxContentBoost(renderer)
|
|
66
|
+
*
|
|
67
|
+
* // live previews, they follow any parameter change
|
|
68
|
+
* sdrMaterial.colorNode = encoder.sdr
|
|
69
|
+
* gainMapMaterial.colorNode = encoder.gainMap
|
|
70
|
+
* hdrMaterial.colorNode = encoder.createPreviewNode() // decodes the encoded result
|
|
71
|
+
*
|
|
72
|
+
* encoder.sdr.exposure.value = 0.9
|
|
73
|
+
* encoder.gainMap.gamma.value.setScalar(1.1)
|
|
74
|
+
*
|
|
75
|
+
* // compress and embed into a single JPEG file
|
|
76
|
+
* const result = await encoder.compress(renderer, { mimeType: 'image/jpeg', quality: 0.9 })
|
|
77
|
+
* const jpeg = encodeJPEGMetadata(result)
|
|
78
|
+
*/
|
|
79
|
+
export declare class GainMapEncoder {
|
|
80
|
+
/**
|
|
81
|
+
* The SDR rendition node
|
|
82
|
+
*/
|
|
83
|
+
readonly sdr: SDRRenditionNode;
|
|
84
|
+
/**
|
|
85
|
+
* The gain map node
|
|
86
|
+
*/
|
|
87
|
+
readonly gainMap: GainMapEncoderNode;
|
|
88
|
+
private _ownedTexture;
|
|
89
|
+
/**
|
|
90
|
+
* @param image the HDR image: a texture, raw texture data (e.g. from a worker) or a TSL node (which requires `width` and `height`)
|
|
91
|
+
* @param options encoding parameters, all of them can be changed later through the node uniforms
|
|
92
|
+
*/
|
|
93
|
+
constructor(image: HDRInput | DataTextureLoaderTexData, options?: GainMapEncoderOptions);
|
|
94
|
+
/** Width of the encoded images */
|
|
95
|
+
get width(): number;
|
|
96
|
+
/** Height of the encoded images */
|
|
97
|
+
get height(): number;
|
|
98
|
+
/**
|
|
99
|
+
* The gain map metadata matching the current parameters
|
|
100
|
+
*/
|
|
101
|
+
get metadata(): GainMapMetadata;
|
|
102
|
+
/**
|
|
103
|
+
* Finds the max value of the HDR image and uses it as `maxContentBoost`,
|
|
104
|
+
* so the full HDR range is encoded.
|
|
105
|
+
*
|
|
106
|
+
* @param renderer
|
|
107
|
+
* @returns the new `maxContentBoost`
|
|
108
|
+
*/
|
|
109
|
+
fitMaxContentBoost(renderer: WebGPURenderer): Promise<number>;
|
|
110
|
+
/**
|
|
111
|
+
* Creates a {@link GainMapNode} decoding the encoded result on the fly,
|
|
112
|
+
* it follows any change to the encoding parameters.
|
|
113
|
+
* Its `maxDisplayBoost` is initialized to restore the full HDR range, and is not changed afterwards.
|
|
114
|
+
*/
|
|
115
|
+
createPreviewNode(): GainMapNode;
|
|
116
|
+
/**
|
|
117
|
+
* Renders the SDR rendition and the gain map, only if something changed since the last render
|
|
118
|
+
*
|
|
119
|
+
* @param renderer
|
|
120
|
+
*/
|
|
121
|
+
render(renderer: WebGPURenderer): void;
|
|
122
|
+
/**
|
|
123
|
+
* Renders (if needed) and reads back the raw SDR rendition and gain map
|
|
124
|
+
*
|
|
125
|
+
* @param renderer
|
|
126
|
+
*/
|
|
127
|
+
read(renderer: WebGPURenderer): Promise<GainMapEncoderRawResult>;
|
|
128
|
+
/**
|
|
129
|
+
* Renders (if needed), reads back and compresses the SDR rendition and gain map
|
|
130
|
+
*
|
|
131
|
+
* @param renderer
|
|
132
|
+
* @param options compression options, `flipY` is not needed
|
|
133
|
+
* @throws {Error} if the browser does not support [createImageBitmap](https://caniuse.com/createimagebitmap)
|
|
134
|
+
*/
|
|
135
|
+
compress(renderer: WebGPURenderer, options: CompressOptions & {
|
|
136
|
+
withWorker?: WorkerInterfaceImplementation;
|
|
137
|
+
}): Promise<GainMapEncoderCompressedResult>;
|
|
138
|
+
/**
|
|
139
|
+
* Disposes the nodes, and the HDR texture if it was created by the encoder from raw data
|
|
140
|
+
*/
|
|
141
|
+
dispose(): void;
|
|
142
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type DataTextureLoaderTexData, type WebGPURenderer } from 'three/webgpu';
|
|
2
|
+
import { type HDRInput } from './nodes/SDRRenditionNode';
|
|
3
|
+
/**
|
|
4
|
+
* Finds the min or max value of each RGB channel of an HDR image, on the GPU.
|
|
5
|
+
*
|
|
6
|
+
* The image is reduced by 2x2 cells until it's 1x1, then the single remaining pixel is read back.
|
|
7
|
+
* Negative values are ignored when looking for the max, values above 65504 (max half float) when looking for the min.
|
|
8
|
+
*
|
|
9
|
+
* @category Utility
|
|
10
|
+
* @group Utility
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* import { findTextureMinMax } from '@monogrid/gainmap-js/encode/webgpu'
|
|
14
|
+
*
|
|
15
|
+
* const [r, g, b] = await findTextureMinMax(exrTexture, 'max', renderer)
|
|
16
|
+
* const maxContentBoost = Math.max(r, g, b)
|
|
17
|
+
*
|
|
18
|
+
* @param image the HDR image: a texture, raw texture data or a TSL node (which requires `size`)
|
|
19
|
+
* @param mode
|
|
20
|
+
* @param renderer
|
|
21
|
+
* @param size size of the image, required when the image is a generic node
|
|
22
|
+
* @throws {Error} if the image is a generic node and `size` is not provided
|
|
23
|
+
*/
|
|
24
|
+
export declare const findTextureMinMax: (image: HDRInput | DataTextureLoaderTexData, mode: "min" | "max", renderer: WebGPURenderer, size?: {
|
|
25
|
+
width: number;
|
|
26
|
+
height: number;
|
|
27
|
+
}) => Promise<[number, number, number]>;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from '../../core/types';
|
|
2
|
+
export { RenderTargetNode } from '../../core/webgpu/RenderTargetNode';
|
|
3
|
+
export * from '../compress';
|
|
4
|
+
export * from '../types';
|
|
5
|
+
export * from './find-texture-min-max';
|
|
6
|
+
export * from './GainMapEncoder';
|
|
7
|
+
export * from './nodes/GainMapEncoderNode';
|
|
8
|
+
export * from './nodes/SDRRenditionNode';
|