@monogrid/gainmap-js 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/CODE_OF_CONDUCT.md +1 -1
  3. package/CONTRIBUTING.md +1 -1
  4. package/README.md +113 -57
  5. package/dist/Loader-CsjVTcg5.js +424 -0
  6. package/dist/Loader-D4XqFES7.js +5 -0
  7. package/dist/{QuadRenderer-DuOPRGA4.js → QuadRenderer-BqJ2Q8P5.js} +39 -30
  8. package/dist/QuadRenderer-De5PMMtY.js +5 -0
  9. package/dist/{_commonjsHelpers-DeBGiDfT.js → _commonjsHelpers-C2Rq7Bzs.js} +2 -2
  10. package/dist/_commonjsHelpers-FnzxO7yL.js +5 -0
  11. package/dist/compress-HAw5HoXG.js +5 -0
  12. package/dist/{compress-B6OswAu8.js → compress-bMJEJ5JM.js} +4 -3
  13. package/dist/core/QuadRenderer.d.ts +2 -2
  14. package/dist/core/get-data-texture.d.ts +4 -3
  15. package/dist/core/types.d.ts +7 -1
  16. package/dist/decode/index.d.ts +1 -11
  17. package/dist/decode/shared/Loader.d.ts +59 -0
  18. package/dist/decode/shared/decode.d.ts +24 -0
  19. package/dist/decode/{extract.d.ts → shared/extract.d.ts} +4 -4
  20. package/dist/decode/shared/index.d.ts +8 -0
  21. package/dist/decode/shared/types.d.ts +53 -0
  22. package/dist/decode/{utils → shared/utils}/MPFExtractor.d.ts +1 -1
  23. package/dist/decode/{utils → shared/utils}/extractXMP.d.ts +1 -1
  24. package/dist/decode/{decode.d.ts → webgl/decode.d.ts} +6 -6
  25. package/dist/decode/webgl/index.d.ts +8 -0
  26. package/dist/decode/{loaders → webgl/loaders}/GainMapLoader.d.ts +5 -6
  27. package/dist/decode/{loaders → webgl/loaders}/HDRJPGLoader.d.ts +6 -7
  28. package/dist/decode/webgl/loaders/LoaderBaseWebGL.d.ts +20 -0
  29. package/dist/decode/{materials → webgl/materials}/GainMapDecoderMaterial.d.ts +2 -2
  30. package/dist/decode/webgpu/core/QuadRenderer.d.ts +153 -0
  31. package/dist/decode/webgpu/decode.d.ts +60 -0
  32. package/dist/decode/webgpu/index.d.ts +8 -0
  33. package/dist/decode/webgpu/loaders/GainMapLoader.d.ts +69 -0
  34. package/dist/decode/webgpu/loaders/HDRJPGLoader.d.ts +65 -0
  35. package/dist/decode/webgpu/loaders/LoaderBaseWebGPU.d.ts +20 -0
  36. package/dist/decode/webgpu/materials/GainMapDecoderMaterial.d.ts +78 -0
  37. package/dist/decode.js +45 -426
  38. package/dist/decode.min.js +5 -0
  39. package/dist/decode.umd.cjs +360 -314
  40. package/dist/decode.umd.min.cjs +5 -0
  41. package/dist/decode.webgpu.js +814 -0
  42. package/dist/decode.webgpu.min.js +5 -0
  43. package/dist/decode.webgpu.umd.cjs +1244 -0
  44. package/dist/decode.webgpu.umd.min.cjs +5 -0
  45. package/dist/encode/encode-and-compress.d.ts +4 -4
  46. package/dist/encode/encode.d.ts +3 -3
  47. package/dist/encode/find-texture-min-max.d.ts +4 -3
  48. package/dist/encode/types.d.ts +6 -5
  49. package/dist/encode.js +33 -12
  50. package/dist/encode.min.js +5 -0
  51. package/dist/encode.umd.cjs +70 -39
  52. package/dist/encode.umd.min.cjs +5 -0
  53. package/dist/libultrahdr/encode-jpeg-metadata.d.ts +6 -6
  54. package/dist/libultrahdr/jpeg-assembler.d.ts +41 -0
  55. package/dist/libultrahdr/jpeg-markers.d.ts +47 -0
  56. package/dist/libultrahdr/mpf-generator.d.ts +20 -0
  57. package/dist/libultrahdr/xmp-generator.d.ts +33 -0
  58. package/dist/libultrahdr.d.ts +0 -3
  59. package/dist/libultrahdr.js +548 -6598
  60. package/dist/libultrahdr.min.js +5 -0
  61. package/dist/libultrahdr.umd.cjs +633 -6686
  62. package/dist/libultrahdr.umd.min.cjs +5 -0
  63. package/dist/third-party.txt +301 -0
  64. package/dist/worker-interface.js +74 -64
  65. package/dist/worker-interface.min.js +5 -0
  66. package/dist/worker-interface.umd.cjs +73 -63
  67. package/dist/worker-interface.umd.min.cjs +5 -0
  68. package/dist/worker.js +103 -88
  69. package/dist/worker.min.js +5 -0
  70. package/dist/worker.umd.cjs +105 -89
  71. package/dist/worker.umd.min.cjs +5 -0
  72. package/package.json +79 -72
  73. package/dist/decode/loaders/LoaderBase.d.ts +0 -45
  74. package/dist/decode/types.d.ts +0 -42
  75. package/dist/libultrahdr/decode-jpeg-metadata.d.ts +0 -28
  76. package/dist/libultrahdr/library.d.ts +0 -9
  77. package/dist/libultrahdr-esm.wasm +0 -0
  78. package/libultrahdr-wasm/build/libultrahdr-debug.js +0 -7156
  79. package/libultrahdr-wasm/build/libultrahdr-debug.wasm +0 -0
  80. package/libultrahdr-wasm/build/libultrahdr-esm.js +0 -6633
  81. package/libultrahdr-wasm/build/libultrahdr-esm.wasm +0 -0
  82. package/libultrahdr-wasm/build/libultrahdr.d.ts +0 -30
  83. package/libultrahdr-wasm/build/libultrahdr.js +0 -6591
  84. package/libultrahdr-wasm/build/libultrahdr.wasm +0 -0
  85. /package/dist/decode/{errors → shared/errors}/GainMapNotFoundError.d.ts +0 -0
  86. /package/dist/decode/{errors → shared/errors}/XMPMetadataNotFoundError.d.ts +0 -0
  87. /package/dist/decode/{utils → shared/utils}/get-html-image-from-blob.d.ts +0 -0
@@ -0,0 +1,424 @@
1
+ /**
2
+ * @monogrid/gainmap-js v3.3.0
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
+ */
5
+
6
+ import { SRGBColorSpace, LinearSRGBColorSpace, HalfFloatType, Loader, LoadingManager, Texture, UVMapping, ClampToEdgeWrapping, LinearFilter, LinearMipMapLinearFilter, RGBAFormat, UnsignedByteType } from 'three';
7
+
8
+ /**
9
+ * Shared decode implementation factory
10
+ * Creates a decode function that prepares a QuadRenderer with the given parameters
11
+ */
12
+ function createDecodeFunction(config) {
13
+ return (params) => {
14
+ const { sdr, gainMap, renderer } = params;
15
+ if (sdr.colorSpace !== SRGBColorSpace) {
16
+ console.warn('SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically');
17
+ sdr.colorSpace = SRGBColorSpace;
18
+ }
19
+ sdr.needsUpdate = true;
20
+ if (gainMap.colorSpace !== LinearSRGBColorSpace) {
21
+ console.warn('Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically');
22
+ gainMap.colorSpace = LinearSRGBColorSpace;
23
+ }
24
+ gainMap.needsUpdate = true;
25
+ const material = config.createMaterial({
26
+ ...params,
27
+ sdr,
28
+ gainMap
29
+ });
30
+ const quadRenderer = config.createQuadRenderer({
31
+ width: sdr.image.width,
32
+ height: sdr.image.height,
33
+ type: HalfFloatType,
34
+ colorSpace: LinearSRGBColorSpace,
35
+ material,
36
+ renderer,
37
+ renderTargetOptions: params.renderTargetOptions
38
+ });
39
+ return quadRenderer;
40
+ };
41
+ }
42
+
43
+ class GainMapNotFoundError extends Error {
44
+ }
45
+
46
+ class XMPMetadataNotFoundError extends Error {
47
+ }
48
+
49
+ const getXMLValue = (xml, tag, defaultValue) => {
50
+ // Check for attribute format first: tag="value"
51
+ const attributeMatch = new RegExp(`${tag}="([^"]*)"`, 'i').exec(xml);
52
+ if (attributeMatch)
53
+ return attributeMatch[1];
54
+ // Check for tag format: <tag>value</tag> or <tag><rdf:li>value</rdf:li>...</tag>
55
+ const tagMatch = new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, 'i').exec(xml);
56
+ if (tagMatch) {
57
+ // Check if it contains rdf:li elements
58
+ const liValues = tagMatch[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);
59
+ if (liValues && liValues.length === 3) {
60
+ return liValues.map(v => v.replace(/<\/?rdf:li>/g, ''));
61
+ }
62
+ return tagMatch[1].trim();
63
+ }
64
+ if (defaultValue !== undefined)
65
+ return defaultValue;
66
+ throw new Error(`Can't find ${tag} in gainmap metadata`);
67
+ };
68
+ const extractXMP = (input) => {
69
+ let str;
70
+ // support node test environment
71
+ if (typeof TextDecoder !== 'undefined')
72
+ str = new TextDecoder().decode(input);
73
+ else
74
+ str = input.toString();
75
+ let start = str.indexOf('<x:xmpmeta');
76
+ while (start !== -1) {
77
+ const end = str.indexOf('x:xmpmeta>', start);
78
+ const xmpBlock = str.slice(start, end + 10);
79
+ try {
80
+ const gainMapMin = getXMLValue(xmpBlock, 'hdrgm:GainMapMin', '0');
81
+ const gainMapMax = getXMLValue(xmpBlock, 'hdrgm:GainMapMax');
82
+ const gamma = getXMLValue(xmpBlock, 'hdrgm:Gamma', '1');
83
+ const offsetSDR = getXMLValue(xmpBlock, 'hdrgm:OffsetSDR', '0.015625');
84
+ const offsetHDR = getXMLValue(xmpBlock, 'hdrgm:OffsetHDR', '0.015625');
85
+ // These are always attributes, so we can use a simpler regex
86
+ const hdrCapacityMinMatch = /hdrgm:HDRCapacityMin="([^"]*)"/.exec(xmpBlock);
87
+ const hdrCapacityMin = hdrCapacityMinMatch ? hdrCapacityMinMatch[1] : '0';
88
+ const hdrCapacityMaxMatch = /hdrgm:HDRCapacityMax="([^"]*)"/.exec(xmpBlock);
89
+ if (!hdrCapacityMaxMatch)
90
+ throw new Error('Incomplete gainmap metadata');
91
+ const hdrCapacityMax = hdrCapacityMaxMatch[1];
92
+ return {
93
+ gainMapMin: Array.isArray(gainMapMin) ? gainMapMin.map(v => parseFloat(v)) : [parseFloat(gainMapMin), parseFloat(gainMapMin), parseFloat(gainMapMin)],
94
+ gainMapMax: Array.isArray(gainMapMax) ? gainMapMax.map(v => parseFloat(v)) : [parseFloat(gainMapMax), parseFloat(gainMapMax), parseFloat(gainMapMax)],
95
+ gamma: Array.isArray(gamma) ? gamma.map(v => parseFloat(v)) : [parseFloat(gamma), parseFloat(gamma), parseFloat(gamma)],
96
+ offsetSdr: Array.isArray(offsetSDR) ? offsetSDR.map(v => parseFloat(v)) : [parseFloat(offsetSDR), parseFloat(offsetSDR), parseFloat(offsetSDR)],
97
+ offsetHdr: Array.isArray(offsetHDR) ? offsetHDR.map(v => parseFloat(v)) : [parseFloat(offsetHDR), parseFloat(offsetHDR), parseFloat(offsetHDR)],
98
+ hdrCapacityMin: parseFloat(hdrCapacityMin),
99
+ hdrCapacityMax: parseFloat(hdrCapacityMax)
100
+ };
101
+ }
102
+ catch (e) {
103
+ // Continue searching for another xmpmeta block if this one fails
104
+ }
105
+ start = str.indexOf('<x:xmpmeta', end);
106
+ }
107
+ };
108
+
109
+ /**
110
+ * MPF Extractor (Multi Picture Format Extractor)
111
+ * By Henrik S Nilsson 2019
112
+ *
113
+ * Extracts images stored in images based on the MPF format (found here: https://www.cipa.jp/e/std/std-sec.html
114
+ * under "CIPA DC-007-Translation-2021 Multi-Picture Format"
115
+ *
116
+ * Overly commented, and without intention of being complete or production ready.
117
+ * Created to extract depth maps from iPhone images, and to learn about image metadata.
118
+ * Kudos to: Phil Harvey (exiftool), Jaume Sanchez (android-lens-blur-depth-extractor)
119
+ */
120
+ class MPFExtractor {
121
+ options;
122
+ constructor(options) {
123
+ this.options = {
124
+ debug: options && options.debug !== undefined ? options.debug : false,
125
+ extractFII: options && options.extractFII !== undefined ? options.extractFII : true,
126
+ extractNonFII: options && options.extractNonFII !== undefined ? options.extractNonFII : true
127
+ };
128
+ }
129
+ extract(imageArrayBuffer) {
130
+ return new Promise((resolve, reject) => {
131
+ const debug = this.options.debug;
132
+ const dataView = new DataView(imageArrayBuffer.buffer);
133
+ // If you're executing this line on a big endian machine, it'll be reversed.
134
+ // bigEnd further down though, refers to the endianness of the image itself.
135
+ if (dataView.getUint16(0) !== 0xffd8) {
136
+ reject(new Error('Not a valid jpeg'));
137
+ return;
138
+ }
139
+ const length = dataView.byteLength;
140
+ let offset = 2;
141
+ let loops = 0;
142
+ let marker; // APP# marker
143
+ while (offset < length) {
144
+ if (++loops > 250) {
145
+ reject(new Error(`Found no marker after ${loops} loops 😵`));
146
+ return;
147
+ }
148
+ if (dataView.getUint8(offset) !== 0xff) {
149
+ reject(new Error(`Not a valid marker at offset 0x${offset.toString(16)}, found: 0x${dataView.getUint8(offset).toString(16)}`));
150
+ return;
151
+ }
152
+ marker = dataView.getUint8(offset + 1);
153
+ if (debug)
154
+ console.log(`Marker: ${marker.toString(16)}`);
155
+ if (marker === 0xe2) {
156
+ if (debug)
157
+ console.log('Found APP2 marker (0xffe2)');
158
+ // Works for iPhone 8 Plus, X, and XSMax. Or any photos of MPF format.
159
+ // Great way to visualize image information in html is using Exiftool. E.g.:
160
+ // ./exiftool.exe -htmldump -wantTrailer photo.jpg > photo.html
161
+ const formatPt = offset + 4;
162
+ /*
163
+ * Structure of the MP Format Identifier
164
+ *
165
+ * Offset Addr. | Code (Hex) | Description
166
+ * +00 ff Marker Prefix <-- offset
167
+ * +01 e2 APP2
168
+ * +02 #n APP2 Field Length
169
+ * +03 #n APP2 Field Length
170
+ * +04 4d 'M' <-- formatPt
171
+ * +05 50 'P'
172
+ * +06 46 'F'
173
+ * +07 00 NULL
174
+ * <-- tiffOffset
175
+ */
176
+ if (dataView.getUint32(formatPt) === 0x4d504600) {
177
+ // Found MPF tag, so we start dig out sub images
178
+ const tiffOffset = formatPt + 4;
179
+ let bigEnd; // Endianness from TIFF header
180
+ // Test for TIFF validity and endianness
181
+ // 0x4949 and 0x4D4D ('II' and 'MM') marks Little Endian and Big Endian
182
+ if (dataView.getUint16(tiffOffset) === 0x4949) {
183
+ bigEnd = false;
184
+ }
185
+ else if (dataView.getUint16(tiffOffset) === 0x4d4d) {
186
+ bigEnd = true;
187
+ }
188
+ else {
189
+ reject(new Error('No valid endianness marker found in TIFF header'));
190
+ return;
191
+ }
192
+ if (dataView.getUint16(tiffOffset + 2, !bigEnd) !== 0x002a) {
193
+ reject(new Error('Not valid TIFF data! (no 0x002A marker)'));
194
+ return;
195
+ }
196
+ // 32 bit number stating the offset from the start of the 8 Byte MP Header
197
+ // to MP Index IFD Least possible value is thus 8 (means 0 offset)
198
+ const firstIFDOffset = dataView.getUint32(tiffOffset + 4, !bigEnd);
199
+ if (firstIFDOffset < 0x00000008) {
200
+ reject(new Error('Not valid TIFF data! (First offset less than 8)'));
201
+ return;
202
+ }
203
+ // Move ahead to MP Index IFD
204
+ // Assume we're at the first IFD, so firstIFDOffset points to
205
+ // MP Index IFD and not MP Attributes IFD. (If we try extract from a sub image,
206
+ // we fail silently here due to this assumption)
207
+ // Count (2 Byte) | MP Index Fields a.k.a. MP Entries (count * 12 Byte) | Offset of Next IFD (4 Byte)
208
+ const dirStart = tiffOffset + firstIFDOffset; // Start of IFD (Image File Directory)
209
+ const count = dataView.getUint16(dirStart, !bigEnd); // Count of MPEntries (2 Byte)
210
+ // Extract info from MPEntries (starting after Count)
211
+ const entriesStart = dirStart + 2;
212
+ let numberOfImages = 0;
213
+ for (let i = entriesStart; i < entriesStart + 12 * count; i += 12) {
214
+ // Each entry is 12 Bytes long
215
+ // Check MP Index IFD tags, here we only take tag 0xb001 = Number of images
216
+ if (dataView.getUint16(i, !bigEnd) === 0xb001) {
217
+ // stored in Last 4 bytes of its 12 Byte entry.
218
+ numberOfImages = dataView.getUint32(i + 8, !bigEnd);
219
+ }
220
+ }
221
+ const nextIFDOffsetLen = 4; // 4 Byte offset field that appears after MP Index IFD tags
222
+ const MPImageListValPt = dirStart + 2 + count * 12 + nextIFDOffsetLen;
223
+ const images = [];
224
+ for (let i = MPImageListValPt; i < MPImageListValPt + numberOfImages * 16; i += 16) {
225
+ const image = {
226
+ MPType: dataView.getUint32(i, !bigEnd),
227
+ size: dataView.getUint32(i + 4, !bigEnd),
228
+ // This offset is specified relative to the address of the MP Endian
229
+ // field in the MP Header, unless the image is a First Individual Image,
230
+ // in which case the value of the offset shall be NULL (0x00000000).
231
+ dataOffset: dataView.getUint32(i + 8, !bigEnd),
232
+ dependantImages: dataView.getUint32(i + 12, !bigEnd),
233
+ start: -1,
234
+ end: -1,
235
+ isFII: false
236
+ };
237
+ if (!image.dataOffset) {
238
+ // dataOffset is 0x00000000 for First Individual Image
239
+ image.start = 0;
240
+ image.isFII = true;
241
+ }
242
+ else {
243
+ image.start = tiffOffset + image.dataOffset;
244
+ image.isFII = false;
245
+ }
246
+ image.end = image.start + image.size;
247
+ images.push(image);
248
+ }
249
+ if (this.options.extractNonFII && images.length) {
250
+ const bufferBlob = new Blob([dataView]);
251
+ const imgs = [];
252
+ for (const image of images) {
253
+ if (image.isFII && !this.options.extractFII) {
254
+ continue; // Skip FII
255
+ }
256
+ const imageBlob = bufferBlob.slice(image.start, image.end + 1, 'image/jpeg');
257
+ // we don't need this
258
+ // const imageUrl = URL.createObjectURL(imageBlob)
259
+ // image.img = document.createElement('img')
260
+ // image.img.src = imageUrl
261
+ imgs.push(imageBlob);
262
+ }
263
+ resolve(imgs);
264
+ }
265
+ }
266
+ }
267
+ offset += 2 + dataView.getUint16(offset + 2);
268
+ }
269
+ });
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Extracts XMP Metadata and the gain map recovery image
275
+ * from a single JPEG file.
276
+ *
277
+ * @category Decoding Functions
278
+ * @group Decoding Functions
279
+ * @param jpegFile an `Uint8Array` containing and encoded JPEG file
280
+ * @returns an sdr `Uint8Array` compressed in JPEG, a gainMap `Uint8Array` compressed in JPEG and the XMP parsed XMP metadata
281
+ * @throws Error if XMP Metadata is not found
282
+ * @throws Error if Gain map image is not found
283
+ * @example
284
+ * import { FileLoader } from 'three'
285
+ * import { extractGainmapFromJPEG } from '@monogrid/gainmap-js'
286
+ *
287
+ * const jpegFile = await new FileLoader()
288
+ * .setResponseType('arraybuffer')
289
+ * .loadAsync('image.jpg')
290
+ *
291
+ * const { sdr, gainMap, metadata } = extractGainmapFromJPEG(jpegFile)
292
+ */
293
+ const extractGainmapFromJPEG = async (jpegFile) => {
294
+ const metadata = extractXMP(jpegFile);
295
+ if (!metadata)
296
+ throw new XMPMetadataNotFoundError('Gain map XMP metadata not found');
297
+ const mpfExtractor = new MPFExtractor({ extractFII: true, extractNonFII: true });
298
+ const images = await mpfExtractor.extract(jpegFile);
299
+ if (images.length !== 2)
300
+ throw new GainMapNotFoundError('Gain map recovery image not found');
301
+ return {
302
+ sdr: new Uint8Array(await images[0].arrayBuffer()),
303
+ gainMap: new Uint8Array(await images[1].arrayBuffer()),
304
+ metadata
305
+ };
306
+ };
307
+
308
+ /**
309
+ * private function, async get image from blob
310
+ *
311
+ * @param blob
312
+ * @returns
313
+ */
314
+ const getHTMLImageFromBlob = (blob) => {
315
+ return new Promise((resolve, reject) => {
316
+ const img = document.createElement('img');
317
+ img.onload = () => { resolve(img); };
318
+ // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
319
+ img.onerror = (e) => { reject(e); };
320
+ img.src = URL.createObjectURL(blob);
321
+ });
322
+ };
323
+
324
+ /**
325
+ * Shared base class for loaders that extracts common logic
326
+ */
327
+ class LoaderBaseShared extends Loader {
328
+ _renderer;
329
+ _renderTargetOptions;
330
+ _internalLoadingManager;
331
+ _config;
332
+ constructor(config, manager) {
333
+ super(manager);
334
+ this._config = config;
335
+ if (config.renderer)
336
+ this._renderer = config.renderer;
337
+ this._internalLoadingManager = new LoadingManager();
338
+ }
339
+ setRenderer(renderer) {
340
+ this._renderer = renderer;
341
+ return this;
342
+ }
343
+ setRenderTargetOptions(options) {
344
+ this._renderTargetOptions = options;
345
+ return this;
346
+ }
347
+ prepareQuadRenderer() {
348
+ if (!this._renderer) {
349
+ 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.');
350
+ }
351
+ const material = this._config.createMaterial({
352
+ gainMapMax: [1, 1, 1],
353
+ gainMapMin: [0, 0, 0],
354
+ gamma: [1, 1, 1],
355
+ offsetHdr: [1, 1, 1],
356
+ offsetSdr: [1, 1, 1],
357
+ hdrCapacityMax: 1,
358
+ hdrCapacityMin: 0,
359
+ maxDisplayBoost: 1,
360
+ gainMap: new Texture(),
361
+ sdr: new Texture()
362
+ });
363
+ return this._config.createQuadRenderer({
364
+ width: 16,
365
+ height: 16,
366
+ type: HalfFloatType,
367
+ colorSpace: LinearSRGBColorSpace,
368
+ material,
369
+ renderer: this._renderer,
370
+ renderTargetOptions: this._renderTargetOptions
371
+ });
372
+ }
373
+ async processImages(sdrBuffer, gainMapBuffer, imageOrientation) {
374
+ const gainMapBlob = gainMapBuffer ? new Blob([gainMapBuffer], { type: 'image/jpeg' }) : undefined;
375
+ const sdrBlob = new Blob([sdrBuffer], { type: 'image/jpeg' });
376
+ let sdrImage;
377
+ let gainMapImage;
378
+ let needsFlip = false;
379
+ if (typeof createImageBitmap === 'undefined') {
380
+ const res = await Promise.all([
381
+ gainMapBlob ? getHTMLImageFromBlob(gainMapBlob) : Promise.resolve(undefined),
382
+ getHTMLImageFromBlob(sdrBlob)
383
+ ]);
384
+ gainMapImage = res[0];
385
+ sdrImage = res[1];
386
+ needsFlip = imageOrientation === 'flipY';
387
+ }
388
+ else {
389
+ const res = await Promise.all([
390
+ gainMapBlob ? createImageBitmap(gainMapBlob, { imageOrientation: imageOrientation || 'flipY' }) : Promise.resolve(undefined),
391
+ createImageBitmap(sdrBlob, { imageOrientation: imageOrientation || 'flipY' })
392
+ ]);
393
+ gainMapImage = res[0];
394
+ sdrImage = res[1];
395
+ }
396
+ return { sdrImage, gainMapImage, needsFlip };
397
+ }
398
+ createTextures(sdrImage, gainMapImage, needsFlip) {
399
+ const gainMap = new Texture(gainMapImage || new ImageData(2, 2), UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, LinearMipMapLinearFilter, RGBAFormat, UnsignedByteType, 1, LinearSRGBColorSpace);
400
+ gainMap.flipY = needsFlip;
401
+ gainMap.needsUpdate = true;
402
+ const sdr = new Texture(sdrImage, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, LinearMipMapLinearFilter, RGBAFormat, UnsignedByteType, 1, SRGBColorSpace);
403
+ sdr.flipY = needsFlip;
404
+ sdr.needsUpdate = true;
405
+ return { gainMap, sdr };
406
+ }
407
+ updateQuadRenderer(quadRenderer, sdrImage, gainMap, sdr, metadata) {
408
+ quadRenderer.width = sdrImage.width;
409
+ quadRenderer.height = sdrImage.height;
410
+ quadRenderer.material.gainMap = gainMap;
411
+ quadRenderer.material.sdr = sdr;
412
+ quadRenderer.material.gainMapMin = metadata.gainMapMin;
413
+ quadRenderer.material.gainMapMax = metadata.gainMapMax;
414
+ quadRenderer.material.offsetHdr = metadata.offsetHdr;
415
+ quadRenderer.material.offsetSdr = metadata.offsetSdr;
416
+ quadRenderer.material.gamma = metadata.gamma;
417
+ quadRenderer.material.hdrCapacityMin = metadata.hdrCapacityMin;
418
+ quadRenderer.material.hdrCapacityMax = metadata.hdrCapacityMax;
419
+ quadRenderer.material.maxDisplayBoost = Math.pow(2, metadata.hdrCapacityMax);
420
+ quadRenderer.material.needsUpdate = true;
421
+ }
422
+ }
423
+
424
+ export { GainMapNotFoundError as G, LoaderBaseShared as L, MPFExtractor as M, XMPMetadataNotFoundError as X, extractXMP as a, createDecodeFunction as c, extractGainmapFromJPEG as e };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @monogrid/gainmap-js v3.3.0
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
+ */
5
+ import{SRGBColorSpace as e,LinearSRGBColorSpace as t,HalfFloatType as a,Loader as r,LoadingManager as n,Texture as i,UVMapping as o,ClampToEdgeWrapping as s,LinearFilter as d,LinearMipMapLinearFilter as p,RGBAFormat as c,UnsignedByteType as l}from"three";function g(r){return n=>{const{sdr:i,gainMap:o,renderer:s}=n;i.colorSpace!==e&&(console.warn("SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically"),i.colorSpace=e),i.needsUpdate=!0,o.colorSpace!==t&&(console.warn("Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically"),o.colorSpace=t),o.needsUpdate=!0;const d=r.createMaterial({...n,sdr:i,gainMap:o});return r.createQuadRenderer({width:i.image.width,height:i.image.height,type:a,colorSpace:t,material:d,renderer:s,renderTargetOptions:n.renderTargetOptions})}}class m extends Error{}class f extends Error{}const h=(e,t,a)=>{const r=new RegExp(`${t}="([^"]*)"`,"i").exec(e);if(r)return r[1];const n=new RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`,"i").exec(e);if(n){const e=n[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);return e&&3===e.length?e.map(e=>e.replace(/<\/?rdf:li>/g,"")):n[1].trim()}if(void 0!==a)return a;throw new Error(`Can't find ${t} in gainmap metadata`)},u=e=>{let t;t="undefined"!=typeof TextDecoder?(new TextDecoder).decode(e):e.toString();let a=t.indexOf("<x:xmpmeta");for(;-1!==a;){const e=t.indexOf("x:xmpmeta>",a),r=t.slice(a,e+10);try{const e=h(r,"hdrgm:GainMapMin","0"),t=h(r,"hdrgm:GainMapMax"),a=h(r,"hdrgm:Gamma","1"),n=h(r,"hdrgm:OffsetSDR","0.015625"),i=h(r,"hdrgm:OffsetHDR","0.015625"),o=/hdrgm:HDRCapacityMin="([^"]*)"/.exec(r),s=o?o[1]:"0",d=/hdrgm:HDRCapacityMax="([^"]*)"/.exec(r);if(!d)throw new Error("Incomplete gainmap metadata");const p=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(a)?a.map(e=>parseFloat(e)):[parseFloat(a),parseFloat(a),parseFloat(a)],offsetSdr:Array.isArray(n)?n.map(e=>parseFloat(e)):[parseFloat(n),parseFloat(n),parseFloat(n)],offsetHdr:Array.isArray(i)?i.map(e=>parseFloat(e)):[parseFloat(i),parseFloat(i),parseFloat(i)],hdrCapacityMin:parseFloat(s),hdrCapacityMax:parseFloat(p)}}catch(e){}a=t.indexOf("<x:xmpmeta",e)}};class x{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,a)=>{const r=this.options.debug,n=new DataView(e.buffer);if(65496!==n.getUint16(0))return void a(new Error("Not a valid jpeg"));const i=n.byteLength;let o,s=2,d=0;for(;s<i;){if(++d>250)return void a(new Error(`Found no marker after ${d} loops 😵`));if(255!==n.getUint8(s))return void a(new Error(`Not a valid marker at offset 0x${s.toString(16)}, found: 0x${n.getUint8(s).toString(16)}`));if(o=n.getUint8(s+1),r&&console.log(`Marker: ${o.toString(16)}`),226===o){r&&console.log("Found APP2 marker (0xffe2)");const e=s+4;if(1297106432===n.getUint32(e)){const r=e+4;let i;if(18761===n.getUint16(r))i=!1;else{if(19789!==n.getUint16(r))return void a(new Error("No valid endianness marker found in TIFF header"));i=!0}if(42!==n.getUint16(r+2,!i))return void a(new Error("Not valid TIFF data! (no 0x002A marker)"));const o=n.getUint32(r+4,!i);if(o<8)return void a(new Error("Not valid TIFF data! (First offset less than 8)"));const s=r+o,d=n.getUint16(s,!i),p=s+2;let c=0;for(let e=p;e<p+12*d;e+=12)45057===n.getUint16(e,!i)&&(c=n.getUint32(e+8,!i));const l=s+2+12*d+4,g=[];for(let e=l;e<l+16*c;e+=16){const t={MPType:n.getUint32(e,!i),size:n.getUint32(e+4,!i),dataOffset:n.getUint32(e+8,!i),dependantImages:n.getUint32(e+12,!i),start:-1,end:-1,isFII:!1};t.dataOffset?(t.start=r+t.dataOffset,t.isFII=!1):(t.start=0,t.isFII=!0),t.end=t.start+t.size,g.push(t)}if(this.options.extractNonFII&&g.length){const e=new Blob([n]),a=[];for(const t of g){if(t.isFII&&!this.options.extractFII)continue;const r=e.slice(t.start,t.end+1,"image/jpeg");a.push(r)}t(a)}}}s+=2+n.getUint16(s+2)}})}}const w=async e=>{const t=u(e);if(!t)throw new f("Gain map XMP metadata not found");const a=new x({extractFII:!0,extractNonFII:!0}),r=await a.extract(e);if(2!==r.length)throw new m("Gain map recovery image not found");return{sdr:new Uint8Array(await r[0].arrayBuffer()),gainMap:new Uint8Array(await r[1].arrayBuffer()),metadata:t}},M=e=>new Promise((t,a)=>{const r=document.createElement("img");r.onload=()=>{t(r)},r.onerror=e=>{a(e)},r.src=URL.createObjectURL(e)});class F extends r{_renderer;_renderTargetOptions;_internalLoadingManager;_config;constructor(e,t){super(t),this._config=e,e.renderer&&(this._renderer=e.renderer),this._internalLoadingManager=new n}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 i,sdr:new i});return this._config.createQuadRenderer({width:16,height:16,type:a,colorSpace:t,material:e,renderer:this._renderer,renderTargetOptions:this._renderTargetOptions})}async processImages(e,t,a){const r=t?new Blob([t],{type:"image/jpeg"}):void 0,n=new Blob([e],{type:"image/jpeg"});let i,o,s=!1;if("undefined"==typeof createImageBitmap){const e=await Promise.all([r?M(r):Promise.resolve(void 0),M(n)]);o=e[0],i=e[1],s="flipY"===a}else{const e=await Promise.all([r?createImageBitmap(r,{imageOrientation:a||"flipY"}):Promise.resolve(void 0),createImageBitmap(n,{imageOrientation:a||"flipY"})]);o=e[0],i=e[1]}return{sdrImage:i,gainMapImage:o,needsFlip:s}}createTextures(a,r,n){const g=new i(r||new ImageData(2,2),o,s,s,d,p,c,l,1,t);g.flipY=n,g.needsUpdate=!0;const m=new i(a,o,s,s,d,p,c,l,1,e);return m.flipY=n,m.needsUpdate=!0,{gainMap:g,sdr:m}}updateQuadRenderer(e,t,a,r,n){e.width=t.width,e.height=t.height,e.material.gainMap=a,e.material.sdr=r,e.material.gainMapMin=n.gainMapMin,e.material.gainMapMax=n.gainMapMax,e.material.offsetHdr=n.offsetHdr,e.material.offsetSdr=n.offsetSdr,e.material.gamma=n.gamma,e.material.hdrCapacityMin=n.hdrCapacityMin,e.material.hdrCapacityMax=n.hdrCapacityMax,e.material.maxDisplayBoost=Math.pow(2,n.hdrCapacityMax),e.material.needsUpdate=!0}}export{m as G,F as L,x as M,f as X,u as a,g as c,w as e};
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.1.0
3
- * With ❤️, by MONOGRID <rnd@monogrid.com>
2
+ * @monogrid/gainmap-js v3.3.0
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
6
- import { RGBAFormat, LinearFilter, ClampToEdgeWrapping, Scene, OrthographicCamera, HalfFloatType, FloatType, Mesh, PlaneGeometry, WebGLRenderTarget, UVMapping, WebGLRenderer, DataTexture, LinearSRGBColorSpace, ShaderMaterial, Texture, IntType, ShortType, ByteType, UnsignedIntType, UnsignedByteType, MeshBasicMaterial } from 'three';
6
+ import { ClampToEdgeWrapping, LinearFilter, Scene, OrthographicCamera, HalfFloatType, FloatType, Mesh, PlaneGeometry, WebGLRenderTarget, RGBAFormat, UVMapping, WebGLRenderer, DataTexture, LinearSRGBColorSpace, ShaderMaterial, Texture, MeshBasicMaterial, IntType, ShortType, ByteType, UnsignedIntType, UnsignedByteType } from 'three';
7
7
 
8
8
  const getBufferForType = (type, width, height) => {
9
9
  let out;
@@ -70,29 +70,24 @@ const canReadPixels = (type, renderer, camera, renderTargetOptions) => {
70
70
  * @group Core
71
71
  */
72
72
  class QuadRenderer {
73
+ _renderer;
74
+ _rendererIsDisposable = false;
75
+ _material;
76
+ _scene;
77
+ _camera;
78
+ _quad;
79
+ _renderTarget;
80
+ _width;
81
+ _height;
82
+ _type;
83
+ _colorSpace;
84
+ _supportsReadPixels = true;
73
85
  /**
74
86
  * Constructs a new QuadRenderer
75
87
  *
76
88
  * @param options Parameters for this QuadRenderer
77
89
  */
78
90
  constructor(options) {
79
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
80
- this._rendererIsDisposable = false;
81
- this._supportsReadPixels = true;
82
- /**
83
- * Renders the input texture using the specified material
84
- */
85
- this.render = () => {
86
- this._renderer.setRenderTarget(this._renderTarget);
87
- try {
88
- this._renderer.render(this._scene, this._camera);
89
- }
90
- catch (e) {
91
- this._renderer.setRenderTarget(null);
92
- throw e;
93
- }
94
- this._renderer.setRenderTarget(null);
95
- };
96
91
  this._width = options.width;
97
92
  this._height = options.height;
98
93
  this._type = options.type;
@@ -105,13 +100,13 @@ class QuadRenderer {
105
100
  // user options
106
101
  type: this._type, // set in class property
107
102
  colorSpace: this._colorSpace, // set in class property
108
- anisotropy: ((_a = options.renderTargetOptions) === null || _a === void 0 ? void 0 : _a.anisotropy) !== undefined ? (_b = options.renderTargetOptions) === null || _b === void 0 ? void 0 : _b.anisotropy : 1,
109
- generateMipmaps: ((_c = options.renderTargetOptions) === null || _c === void 0 ? void 0 : _c.generateMipmaps) !== undefined ? (_d = options.renderTargetOptions) === null || _d === void 0 ? void 0 : _d.generateMipmaps : false,
110
- magFilter: ((_e = options.renderTargetOptions) === null || _e === void 0 ? void 0 : _e.magFilter) !== undefined ? (_f = options.renderTargetOptions) === null || _f === void 0 ? void 0 : _f.magFilter : LinearFilter,
111
- minFilter: ((_g = options.renderTargetOptions) === null || _g === void 0 ? void 0 : _g.minFilter) !== undefined ? (_h = options.renderTargetOptions) === null || _h === void 0 ? void 0 : _h.minFilter : LinearFilter,
112
- samples: ((_j = options.renderTargetOptions) === null || _j === void 0 ? void 0 : _j.samples) !== undefined ? (_k = options.renderTargetOptions) === null || _k === void 0 ? void 0 : _k.samples : undefined,
113
- wrapS: ((_l = options.renderTargetOptions) === null || _l === void 0 ? void 0 : _l.wrapS) !== undefined ? (_m = options.renderTargetOptions) === null || _m === void 0 ? void 0 : _m.wrapS : ClampToEdgeWrapping,
114
- wrapT: ((_o = options.renderTargetOptions) === null || _o === void 0 ? void 0 : _o.wrapT) !== undefined ? (_p = options.renderTargetOptions) === null || _p === void 0 ? void 0 : _p.wrapT : ClampToEdgeWrapping
103
+ anisotropy: options.renderTargetOptions?.anisotropy !== undefined ? options.renderTargetOptions?.anisotropy : 1,
104
+ generateMipmaps: options.renderTargetOptions?.generateMipmaps !== undefined ? options.renderTargetOptions?.generateMipmaps : false,
105
+ magFilter: options.renderTargetOptions?.magFilter !== undefined ? options.renderTargetOptions?.magFilter : LinearFilter,
106
+ minFilter: options.renderTargetOptions?.minFilter !== undefined ? options.renderTargetOptions?.minFilter : LinearFilter,
107
+ samples: options.renderTargetOptions?.samples !== undefined ? options.renderTargetOptions?.samples : undefined,
108
+ wrapS: options.renderTargetOptions?.wrapS !== undefined ? options.renderTargetOptions?.wrapS : ClampToEdgeWrapping,
109
+ wrapT: options.renderTargetOptions?.wrapT !== undefined ? options.renderTargetOptions?.wrapT : ClampToEdgeWrapping
115
110
  };
116
111
  this._material = options.material;
117
112
  if (options.renderer) {
@@ -149,7 +144,7 @@ class QuadRenderer {
149
144
  this._quad.geometry.computeBoundingBox();
150
145
  this._scene.add(this._quad);
151
146
  this._renderTarget = new WebGLRenderTarget(this.width, this.height, rtOptions);
152
- this._renderTarget.texture.mapping = ((_q = options.renderTargetOptions) === null || _q === void 0 ? void 0 : _q.mapping) !== undefined ? (_r = options.renderTargetOptions) === null || _r === void 0 ? void 0 : _r.mapping : UVMapping;
147
+ this._renderTarget.texture.mapping = options.renderTargetOptions?.mapping !== undefined ? options.renderTargetOptions?.mapping : UVMapping;
153
148
  }
154
149
  /**
155
150
  * Instantiates a temporary renderer
@@ -165,6 +160,20 @@ class QuadRenderer {
165
160
  // this._rendererIsDisposable = true
166
161
  return renderer;
167
162
  }
163
+ /**
164
+ * Renders the input texture using the specified material
165
+ */
166
+ render = () => {
167
+ this._renderer.setRenderTarget(this._renderTarget);
168
+ try {
169
+ this._renderer.render(this._scene, this._camera);
170
+ }
171
+ catch (e) {
172
+ this._renderer.setRenderTarget(null);
173
+ throw e;
174
+ }
175
+ this._renderer.setRenderTarget(null);
176
+ };
168
177
  /**
169
178
  * Obtains a Buffer containing the rendered texture.
170
179
  *
@@ -190,11 +199,11 @@ class QuadRenderer {
190
199
  // fixed values
191
200
  this.toArray(), this.width, this.height, RGBAFormat, this._type,
192
201
  // user values
193
- (options === null || options === void 0 ? void 0 : options.mapping) || UVMapping, (options === null || options === void 0 ? void 0 : options.wrapS) || ClampToEdgeWrapping, (options === null || options === void 0 ? void 0 : options.wrapT) || ClampToEdgeWrapping, (options === null || options === void 0 ? void 0 : options.magFilter) || LinearFilter, (options === null || options === void 0 ? void 0 : options.minFilter) || LinearFilter, (options === null || options === void 0 ? void 0 : options.anisotropy) || 1,
202
+ options?.mapping || UVMapping, options?.wrapS || ClampToEdgeWrapping, options?.wrapT || ClampToEdgeWrapping, options?.magFilter || LinearFilter, options?.minFilter || LinearFilter, options?.anisotropy || 1,
194
203
  // fixed value
195
204
  LinearSRGBColorSpace);
196
205
  // set this afterwards, we can't set it in constructor
197
- returnValue.generateMipmaps = (options === null || options === void 0 ? void 0 : options.generateMipmaps) !== undefined ? options === null || options === void 0 ? void 0 : options.generateMipmaps : false;
206
+ returnValue.generateMipmaps = options?.generateMipmaps !== undefined ? options?.generateMipmaps : false;
198
207
  return returnValue;
199
208
  }
200
209
  /**
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @monogrid/gainmap-js v3.3.0
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
+ */
5
+ import{ClampToEdgeWrapping as e,LinearFilter as r,Scene as t,OrthographicCamera as i,HalfFloatType as s,FloatType as a,Mesh as n,PlaneGeometry as h,WebGLRenderTarget as o,RGBAFormat as d,UVMapping as p,WebGLRenderer as _,DataTexture as g,LinearSRGBColorSpace as l,ShaderMaterial as c,Texture as w,MeshBasicMaterial as m,IntType as T,ShortType as u,ByteType as y,UnsignedIntType as f,UnsignedByteType as O}from"three";const b=(e,r,t)=>{let i;switch(e){case O:i=new Uint8ClampedArray(r*t*4);break;case s:i=new Uint16Array(r*t*4);break;case f:i=new Uint32Array(r*t*4);break;case y:i=new Int8Array(r*t*4);break;case u:i=new Int16Array(r*t*4);break;case T:i=new Int32Array(r*t*4);break;case a:i=new Float32Array(r*t*4);break;default:throw new Error("Unsupported data type")}return i};let v;class R{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(_){this._width=_.width,this._height=_.height,this._type=_.type,this._colorSpace=_.colorSpace;const g={format:d,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:void 0!==_.renderTargetOptions?.anisotropy?_.renderTargetOptions?.anisotropy:1,generateMipmaps:void 0!==_.renderTargetOptions?.generateMipmaps&&_.renderTargetOptions?.generateMipmaps,magFilter:void 0!==_.renderTargetOptions?.magFilter?_.renderTargetOptions?.magFilter:r,minFilter:void 0!==_.renderTargetOptions?.minFilter?_.renderTargetOptions?.minFilter:r,samples:void 0!==_.renderTargetOptions?.samples?_.renderTargetOptions?.samples:void 0,wrapS:void 0!==_.renderTargetOptions?.wrapS?_.renderTargetOptions?.wrapS:e,wrapT:void 0!==_.renderTargetOptions?.wrapT?_.renderTargetOptions?.wrapT:e};if(this._material=_.material,_.renderer?this._renderer=_.renderer:(this._renderer=R.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new t,this._camera=new i,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,r,t,i)=>{if(void 0!==v)return v;const s=new o(1,1,i);r.setRenderTarget(s);const a=new n(new h,new m({color:16777215}));r.render(a,t),r.setRenderTarget(null);const d=b(e,s.width,s.height);return r.readRenderTargetPixels(s,0,0,s.width,s.height,d),s.dispose(),a.geometry.dispose(),a.material.dispose(),v=0!==d[0],v})(this._type,this._renderer,this._camera,g)){let e;if(this._type===s)e=this._renderer.extensions.has("EXT_color_buffer_float")?a:void 0;void 0!==e?(console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${a}`),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 n(new h,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new o(this.width,this.height,g),this._renderTarget.texture.mapping=void 0!==_.renderTargetOptions?.mapping?_.renderTargetOptions?.mapping:p}static instantiateRenderer(){const e=new _;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=b(this._type,this._width,this._height);return this._renderer.readRenderTargetPixels(this._renderTarget,0,0,this._width,this._height,e),e}toDataTexture(t){const i=new g(this.toArray(),this.width,this.height,d,this._type,t?.mapping||p,t?.wrapS||e,t?.wrapT||e,t?.magFilter||r,t?.minFilter||r,t?.anisotropy||1,l);return i.generateMipmaps=void 0!==t?.generateMipmaps&&t?.generateMipmaps,i}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&(this._renderer.dispose(),this._renderer.forceContextLoss())}dispose(e){this.disposeOnDemandRenderer(),e&&this.renderTarget.dispose(),this.material instanceof c&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof w&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof w&&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}}export{R as Q};
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.1.0
3
- * With ❤️, by MONOGRID <rnd@monogrid.com>
2
+ * @monogrid/gainmap-js v3.3.0
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
6
6
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @monogrid/gainmap-js v3.3.0
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
+ */
5
+ var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}export{e as c,o as g};
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @monogrid/gainmap-js v3.3.0
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
+ */
5
+ const e=async e=>{if("undefined"==typeof createImageBitmap)throw new Error("createImageBitmap() not supported.");const{source:t,mimeType:a,quality:n,flipY:r}=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,c=i.height;let f;"undefined"!=typeof OffscreenCanvas?f=new OffscreenCanvas(s,c):(f=document.createElement("canvas"),f.width=s,f.height=c);const m=f.getContext("2d");if(!m)throw new Error("Failed to create canvas Context");!0===r&&(m.translate(0,c),m.scale(1,-1)),m.drawImage(i,0,0,s,c);const w=await(async(e,t,a)=>{if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return e.convertToBlob({type:t,quality:a||.9});if(e instanceof HTMLCanvasElement)return new Promise((n,r)=>{e.toBlob(e=>{e?n(e):r(new Error("Failed to convert canvas to blob"))},t,a||.9)});throw new Error("Unsupported canvas element")})(f,a,n||.9);return{data:new Uint8Array(await w.arrayBuffer()),mimeType:a,width:s,height:c}};export{e as c};
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.1.0
3
- * With ❤️, by MONOGRID <rnd@monogrid.com>
2
+ * @monogrid/gainmap-js v3.3.0
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
6
6
  /**
@@ -46,7 +46,6 @@ const compress = async (params) => {
46
46
  if (typeof createImageBitmap === 'undefined')
47
47
  throw new Error('createImageBitmap() not supported.');
48
48
  const { source, mimeType, quality, flipY } = params;
49
- // eslint-disable-next-line no-undef
50
49
  let imageBitmapSource;
51
50
  if ((source instanceof Uint8Array || source instanceof Uint8ClampedArray) && 'sourceMimeType' in params) {
52
51
  imageBitmapSource = new Blob([source], { type: params.sourceMimeType });
@@ -69,6 +68,8 @@ const compress = async (params) => {
69
68
  canvas.width = width;
70
69
  canvas.height = height;
71
70
  }
71
+ // apparently we do need to assert the type here for npx tsc to be happy
72
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
72
73
  const ctx = canvas.getContext('2d');
73
74
  if (!ctx)
74
75
  throw new Error('Failed to create canvas Context');
@@ -1,4 +1,4 @@
1
- import { ByteType, ColorSpace, DataTexture, FloatType, HalfFloatType, IntType, Material, ShortType, TextureDataType, UnsignedByteType, UnsignedIntType, WebGLRenderer, WebGLRenderTarget } from 'three';
1
+ import { ByteType, ColorSpace, DataTexture, FloatType, HalfFloatType, IntType, Material, ShortType, TextureDataType, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedInt101111Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, WebGLRenderer, WebGLRenderTarget } from 'three';
2
2
  import { QuadRendererTextureOptions } from './types';
3
3
  /**
4
4
  * Utility Type that translates `three` texture types to their TypedArray counterparts.
@@ -6,7 +6,7 @@ import { QuadRendererTextureOptions } from './types';
6
6
  * @category Utility
7
7
  * @group Utility
8
8
  */
9
- export type TextureDataTypeToBufferType<TType extends TextureDataType> = TType extends typeof UnsignedByteType ? Uint8ClampedArray : TType extends typeof HalfFloatType ? Uint16Array : TType extends typeof UnsignedIntType ? Uint32Array : TType extends typeof ByteType ? Int8Array : TType extends typeof ShortType ? Int16Array : TType extends typeof IntType ? Int32Array : TType extends typeof FloatType ? Float32Array : never;
9
+ export type TextureDataTypeToBufferType<TType extends TextureDataType> = TType extends typeof UnsignedByteType ? Uint8ClampedArray<ArrayBuffer> : TType extends typeof ByteType ? Int8Array<ArrayBuffer> : TType extends typeof ShortType ? Int16Array<ArrayBuffer> : TType extends typeof UnsignedShortType ? Uint16Array<ArrayBuffer> : TType extends typeof IntType ? Int32Array<ArrayBuffer> : TType extends typeof UnsignedIntType ? Uint32Array<ArrayBuffer> : TType extends typeof FloatType ? Float32Array<ArrayBuffer> : TType extends typeof HalfFloatType ? Uint16Array<ArrayBuffer> : TType extends typeof UnsignedShort4444Type ? Uint16Array<ArrayBuffer> : TType extends typeof UnsignedShort5551Type ? Uint16Array<ArrayBuffer> : TType extends typeof UnsignedInt248Type ? Uint32Array<ArrayBuffer> : TType extends typeof UnsignedInt5999Type ? Uint32Array<ArrayBuffer> : TType extends typeof UnsignedInt101111Type ? Uint32Array<ArrayBuffer> : never;
10
10
  export type QuadRendererOptions<TType extends TextureDataType, TMaterial extends Material> = {
11
11
  /**
12
12
  * Width of the render target