gb-image-decoder 1.3.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const ohash = require('ohash');
4
+
3
5
  var BlendMode = /* @__PURE__ */ ((BlendMode2) => {
4
6
  BlendMode2["NORMAL"] = "normal";
5
7
  BlendMode2["NORMAL_S"] = "normal_s";
@@ -58,57 +60,18 @@ const SKIP_LINE = "skip";
58
60
  const TILE_PIXEL_WIDTH = 8;
59
61
  const TILE_PIXEL_HEIGHT = 8;
60
62
  const TILES_PER_LINE = 20;
63
+ const TILES_PER_COLUMN = 18;
64
+ const FRAME_WIDTH = 2;
61
65
  const BW_PALETTE = [16777215, 11184810, 5592405, 0];
62
66
  const BW_PALETTE_HEX = ["#ffffff", "#aaaaaa", "#555555", "#000000"];
63
- const BLACK_LINE = [
64
- BLACK,
65
- BLACK,
66
- BLACK,
67
- BLACK,
68
- BLACK,
69
- BLACK,
70
- BLACK,
71
- BLACK,
72
- BLACK,
73
- BLACK,
74
- BLACK,
75
- BLACK,
76
- BLACK,
77
- BLACK,
78
- BLACK,
79
- BLACK,
80
- BLACK,
81
- BLACK,
82
- BLACK,
83
- BLACK
84
- ];
85
- const WHITE_LINE = [
86
- WHITE,
87
- WHITE,
88
- WHITE,
89
- WHITE,
90
- WHITE,
91
- WHITE,
92
- WHITE,
93
- WHITE,
94
- WHITE,
95
- WHITE,
96
- WHITE,
97
- WHITE,
98
- WHITE,
99
- WHITE,
100
- WHITE,
101
- WHITE,
102
- WHITE,
103
- WHITE,
104
- WHITE,
105
- WHITE
106
- ];
107
- const defaultPalette = {
108
- r: [0, 84, 172, 255],
109
- g: [0, 84, 172, 255],
110
- b: [0, 84, 172, 255],
111
- n: [0, 85, 170, 255],
67
+ const BLACK_LINE = Array(TILES_PER_LINE).fill(BLACK);
68
+ const WHITE_LINE = Array(TILES_PER_LINE).fill(WHITE);
69
+ const RGBN_SHADES = [0, 85, 170, 255];
70
+ const defaultRGBNPalette = {
71
+ r: RGBN_SHADES,
72
+ g: RGBN_SHADES,
73
+ b: RGBN_SHADES,
74
+ n: RGBN_SHADES,
112
75
  blend: BlendMode.MULTIPLY
113
76
  };
114
77
 
@@ -145,18 +108,17 @@ const decodeTile = (rawBytes = BLACK) => {
145
108
  return pixels;
146
109
  };
147
110
 
148
- const tileIndexIsPartOfFrame = (tileIndex, imageStartLine, handleExportFrame = ExportFrameMode.FRAMEMODE_KEEP) => {
111
+ const tileIndexIsPartOfFrame = (tileIndex, imageStartLine, handleExportFrame) => {
149
112
  if (handleExportFrame === ExportFrameMode.FRAMEMODE_CROP) {
150
113
  return false;
151
114
  }
152
- const checkIndex = tileIndex - (handleExportFrame === ExportFrameMode.FRAMEMODE_KEEP ? 0 : 20);
153
- if (checkIndex < imageStartLine * 20) {
115
+ if (tileIndex < imageStartLine * 20) {
154
116
  return true;
155
117
  }
156
- if (checkIndex >= imageStartLine * 20 + 280) {
118
+ if (tileIndex >= imageStartLine * 20 + 280) {
157
119
  return true;
158
120
  }
159
- switch (checkIndex % 20) {
121
+ switch (tileIndex % 20) {
160
122
  case 0:
161
123
  case 1:
162
124
  case 18:
@@ -171,12 +133,14 @@ const getRGBValue = ({
171
133
  pixels,
172
134
  index,
173
135
  tileIndex,
174
- imageStartLine,
175
- handleExportFrame,
176
- colorData,
177
- frameColorData
136
+ imageContext: {
137
+ imageStartLine,
138
+ handleExportFrame,
139
+ imagePalette,
140
+ framePalette
141
+ }
178
142
  }) => {
179
- const palette = tileIndexIsPartOfFrame(tileIndex, imageStartLine, handleExportFrame) ? frameColorData : colorData;
143
+ const palette = tileIndexIsPartOfFrame(tileIndex, imageStartLine, handleExportFrame) ? framePalette : imagePalette;
180
144
  const value = palette[pixels[index]];
181
145
  return {
182
146
  // eslint-disable-next-line no-bitwise
@@ -188,495 +152,403 @@ const getRGBValue = ({
188
152
  };
189
153
  };
190
154
 
191
- const createCanvasElement = () => {
192
- try {
193
- return document.createElement("canvas");
194
- } catch (error) {
195
- throw new Error("cannot create canvas element");
196
- }
197
- };
198
- const createImageData = (rawImageData, width, height) => new ImageData(rawImageData, width, height);
199
-
200
- var __defProp$1 = Object.defineProperty;
201
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
202
- var __publicField$1 = (obj, key, value) => {
203
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
204
- return value;
205
- };
206
- class Decoder {
207
- constructor(options) {
208
- __publicField$1(this, "canvas");
209
- __publicField$1(this, "tiles");
210
- __publicField$1(this, "colors");
211
- __publicField$1(this, "frameColors");
212
- __publicField$1(this, "rawImageData");
213
- __publicField$1(this, "lockFrame");
214
- __publicField$1(this, "colorData");
215
- __publicField$1(this, "frameColorData");
216
- __publicField$1(this, "tilesPerLine");
217
- __publicField$1(this, "imageStartLine");
218
- __publicField$1(this, "canvasCreator");
219
- __publicField$1(this, "imageDataCreator");
220
- this.canvas = null;
221
- this.tiles = [];
222
- this.colors = [];
223
- this.frameColors = [];
224
- this.rawImageData = null;
225
- this.lockFrame = false;
226
- this.colorData = [...BW_PALETTE];
227
- this.frameColorData = [...BW_PALETTE];
228
- this.tilesPerLine = options?.tilesPerLine || TILES_PER_LINE;
229
- this.imageStartLine = 2;
230
- this.canvasCreator = options?.canvasCreator || createCanvasElement;
231
- this.imageDataCreator = options?.imageDataCreator || createImageData;
232
- }
233
- update({
234
- canvas,
235
- tiles,
236
- palette,
237
- framePalette,
238
- imageStartLine = 2
239
- }) {
240
- const startLineChanged = this.setImageStartLine(imageStartLine);
241
- const canvasChanged = canvas ? this.setCanvas(canvas) : false;
242
- const usedFramePalette = this.tilesPerLine === TILES_PER_LINE ? framePalette : palette;
243
- const palettesChanged = this.setPalettes(palette, usedFramePalette);
244
- if (startLineChanged || canvasChanged || palettesChanged || !this.tiles.length) {
245
- this.tiles = [];
246
- }
247
- const tilesChanged = this.setTiles(tiles);
248
- const newHeight = this.getHeight();
249
- const newWidth = this.getWidth();
250
- if (!this.canvas) {
251
- return;
252
- }
253
- if (newHeight === 0) {
254
- this.canvas.height = 0;
255
- return;
155
+ class UrlCache {
156
+ static rendered = {};
157
+ static rendering = {};
158
+ async getUrl(hash) {
159
+ if (UrlCache.rendered.hasOwnProperty(hash)) {
160
+ return UrlCache.rendered[hash];
256
161
  }
257
- if (this.canvas.height !== newHeight || this.canvas.width !== newWidth || !this.rawImageData?.length) {
258
- this.canvas.height = newHeight;
259
- this.canvas.width = newWidth;
260
- const newRawImageData = new Uint8ClampedArray(newWidth * newHeight * 4);
261
- this.rawImageData?.forEach((value, index) => {
262
- newRawImageData[index] = value;
263
- });
264
- this.rawImageData = newRawImageData;
162
+ if (UrlCache.rendering.hasOwnProperty(hash)) {
163
+ const url = await UrlCache.rendering[hash];
164
+ return url;
265
165
  }
266
- tilesChanged.forEach(({ index, newTile }) => {
267
- this.renderTile(index, newTile);
268
- });
269
- this.updateCanvas(newWidth, newHeight);
166
+ return null;
270
167
  }
271
- setImageStartLine(imageStartLine) {
272
- if (this.imageStartLine === imageStartLine) {
273
- return false;
168
+ async setUrl(hash, promise) {
169
+ if (UrlCache.rendered.hasOwnProperty(hash) || UrlCache.rendering.hasOwnProperty(hash)) {
170
+ console.warn("hash already exists!");
274
171
  }
275
- this.imageStartLine = imageStartLine;
276
- return true;
172
+ UrlCache.rendering[hash] = promise;
173
+ UrlCache.rendered[hash] = await promise;
174
+ delete UrlCache.rendering[hash];
277
175
  }
278
- updateCanvas(newWidth, newHeight) {
279
- if (!this.canvas || !this.rawImageData?.length) {
176
+ }
177
+
178
+ const toObjectUrl = async (canvas) => new Promise((resolve, reject) => {
179
+ canvas.toBlob((blob) => {
180
+ if (!blob) {
181
+ reject(new Error("Could not generate Blob from canvas"));
280
182
  return;
281
183
  }
282
- const context = this.canvas.getContext("2d");
283
- const imageData = this.imageDataCreator(this.rawImageData, newWidth, newHeight);
284
- context?.putImageData(imageData, 0, 0);
285
- }
286
- getScaledCanvas(scaleFactor, handleExportFrame = ExportFrameMode.FRAMEMODE_KEEP) {
287
- let handleFrameMode = handleExportFrame;
288
- if ((this.tiles.length !== 360 || this.tilesPerLine !== TILES_PER_LINE) && handleFrameMode !== ExportFrameMode.FRAMEMODE_KEEP) {
289
- handleFrameMode = ExportFrameMode.FRAMEMODE_KEEP;
184
+ try {
185
+ resolve(URL.createObjectURL(blob));
186
+ } catch (error) {
187
+ reject(error);
290
188
  }
291
- const {
292
- initialHeight,
293
- initialWidth,
294
- tilesPerLine
295
- } = this.getScaledCanvasSize(handleFrameMode);
296
- const canvas = this.canvasCreator();
189
+ });
190
+ });
191
+ const dataUrlFromRawOutput = async ({
192
+ data,
193
+ dimensions: { width, height }
194
+ }, scaleFactor, hash, canvasCreator) => {
195
+ const urlCache = new UrlCache();
196
+ urlCache.setUrl(hash, new Promise((resolve) => {
197
+ const canvas = canvasCreator();
198
+ canvas.width = width * scaleFactor;
199
+ canvas.height = height * scaleFactor;
297
200
  const context = canvas.getContext("2d");
298
- if (!context) {
299
- throw new Error("no canvas context");
300
- }
301
- canvas.width = initialWidth * scaleFactor;
302
- canvas.height = initialHeight * scaleFactor;
303
- this.getExportTiles(handleFrameMode).forEach((tile, index) => {
304
- this.paintTileScaled(decodeTile(tile), index, context, scaleFactor, tilesPerLine, handleFrameMode);
305
- });
306
- return canvas;
307
- }
308
- getScaledCanvasSize(handleExportFrame) {
309
- const FRAME_TILES = 4;
310
- const width = this.getWidth();
311
- const height = this.getHeight();
312
- switch (handleExportFrame) {
313
- case ExportFrameMode.FRAMEMODE_KEEP:
314
- return {
315
- initialHeight: height,
316
- initialWidth: width,
317
- tilesPerLine: this.tilesPerLine
318
- };
319
- case ExportFrameMode.FRAMEMODE_CROP:
320
- return {
321
- initialHeight: height - TILE_PIXEL_HEIGHT * FRAME_TILES,
322
- initialWidth: width - TILE_PIXEL_WIDTH * FRAME_TILES,
323
- tilesPerLine: this.tilesPerLine - FRAME_TILES
324
- };
325
- case ExportFrameMode.FRAMEMODE_SQUARE_BLACK:
326
- case ExportFrameMode.FRAMEMODE_SQUARE_WHITE:
327
- return {
328
- initialHeight: height + 2 * TILE_PIXEL_HEIGHT,
329
- initialWidth: width,
330
- tilesPerLine: this.tilesPerLine
331
- };
332
- default:
333
- throw new Error(`unknown export mode ${handleExportFrame}`);
334
- }
335
- }
336
- getExportTiles(handleExportFrame) {
337
- if (!this.tiles) {
338
- throw new Error("no tiles to export");
339
- }
340
- switch (handleExportFrame) {
341
- case ExportFrameMode.FRAMEMODE_KEEP:
342
- return this.tiles;
343
- case ExportFrameMode.FRAMEMODE_CROP:
344
- return this.tiles.reduce((acc, tile, index) => tileIndexIsPartOfFrame(index, this.imageStartLine, ExportFrameMode.FRAMEMODE_KEEP) ? acc : [...acc, tile], []);
345
- case ExportFrameMode.FRAMEMODE_SQUARE_BLACK:
346
- return [
347
- ...BLACK_LINE,
348
- ...this.tiles,
349
- ...BLACK_LINE
350
- ];
351
- case ExportFrameMode.FRAMEMODE_SQUARE_WHITE:
352
- return [
353
- ...WHITE_LINE,
354
- ...this.tiles,
355
- ...WHITE_LINE
356
- ];
357
- default:
358
- throw new Error(`unknown export mode ${handleExportFrame}`);
359
- }
360
- }
361
- setCanvas(canvas) {
362
- if (this.canvas === canvas) {
363
- return false;
364
- }
365
- this.canvas = canvas;
366
- return true;
201
+ const imageData = new ImageData(data, canvas.width, canvas.height);
202
+ context?.putImageData(imageData, 0, 0);
203
+ resolve(toObjectUrl(canvas));
204
+ }));
205
+ const url = await urlCache.getUrl(hash);
206
+ if (!url) {
207
+ throw new Error("error generating image");
367
208
  }
368
- setPalettes(palette, framePalette) {
369
- if (this.colors[0] === palette[0] && this.colors[1] === palette[1] && this.colors[2] === palette[2] && this.colors[3] === palette[3] && this.frameColors[0] === framePalette[0] && this.frameColors[1] === framePalette[1] && this.frameColors[2] === framePalette[2] && this.frameColors[3] === framePalette[3]) {
370
- return false;
371
- }
372
- this.colors = palette;
373
- this.frameColors = framePalette;
374
- this.colors.forEach((color, index) => {
375
- this.colorData[index] = color.length !== 7 ? BW_PALETTE[index] : parseInt(color.substring(1), 16);
376
- });
377
- this.frameColors.forEach((color, index) => {
378
- this.frameColorData[index] = color.length !== 7 ? BW_PALETTE[index] : parseInt(color.substring(1), 16);
379
- });
380
- return true;
209
+ return url;
210
+ };
211
+
212
+ const createCanvasElement = () => {
213
+ try {
214
+ return document.createElement("canvas");
215
+ } catch (error) {
216
+ throw new Error("cannot create canvas element");
381
217
  }
382
- setTiles(tiles) {
383
- const changedTiles = tiles.reduce((acc, newTile, index) => {
384
- const changed = newTile !== this.tiles[index];
385
- if (!changed) {
386
- return acc;
387
- }
388
- return [
389
- ...acc,
390
- {
391
- index,
392
- newTile
393
- }
394
- ];
395
- }, []);
396
- this.tiles = tiles;
397
- return changedTiles;
218
+ };
219
+
220
+ const padLines = {
221
+ [ExportFrameMode.FRAMEMODE_SQUARE_BLACK]: BLACK_LINE,
222
+ [ExportFrameMode.FRAMEMODE_SQUARE_WHITE]: WHITE_LINE
223
+ };
224
+ const getPalettes = (imagePalette, framePalette, tilesPerLine) => {
225
+ if (tilesPerLine !== TILES_PER_LINE) {
226
+ return {
227
+ imagePalette,
228
+ framePalette: imagePalette
229
+ };
398
230
  }
399
- renderTile(tileIndex, rawLine) {
400
- if (rawLine === SKIP_LINE) {
401
- this.paintTile(null, tileIndex);
402
- } else {
403
- const tile = decodeTile(rawLine);
404
- this.paintTile(tile, tileIndex);
231
+ return {
232
+ imagePalette,
233
+ framePalette
234
+ };
235
+ };
236
+ const getDimensions$1 = (tilesLength, tilesPerLine) => ({
237
+ width: TILE_PIXEL_WIDTH * tilesPerLine,
238
+ height: TILE_PIXEL_HEIGHT * Math.ceil(tilesLength / tilesPerLine)
239
+ });
240
+ const getCroppedTiles = (tiles, imageContext) => ({
241
+ tiles: tiles.reduce((acc, tile, index) => tileIndexIsPartOfFrame(index, imageContext.imageStartLine, ExportFrameMode.FRAMEMODE_KEEP) ? acc : [...acc, tile], []),
242
+ dimensions: { width: 128, height: 112 },
243
+ contextUpdates: { tilesPerLine: 16, imageStartLine: 0 }
244
+ });
245
+ const getPaddedSquare = (tiles, padLine, imageContext) => {
246
+ let wholeImageStartLine = imageContext.imageStartLine - FRAME_WIDTH - 1;
247
+ const paddedTiles = [...tiles];
248
+ const square20by20tiles = TILES_PER_LINE ** 2;
249
+ while (paddedTiles.length < square20by20tiles || wholeImageStartLine < 0) {
250
+ paddedTiles.unshift(...padLine);
251
+ paddedTiles.push(...padLine);
252
+ wholeImageStartLine += 1;
253
+ }
254
+ const startIndex = wholeImageStartLine * TILES_PER_LINE;
255
+ return {
256
+ tiles: paddedTiles.slice(startIndex, startIndex + square20by20tiles),
257
+ dimensions: { width: 160, height: 160 },
258
+ contextUpdates: { tilesPerLine: 20, imageStartLine: 3 }
259
+ };
260
+ };
261
+ const applyCrop = (tiles, imageContext) => {
262
+ const checkFrameMode = imageContext.tilesPerLine !== TILES_PER_LINE ? ExportFrameMode.FRAMEMODE_KEEP : imageContext.handleExportFrame;
263
+ switch (checkFrameMode) {
264
+ case ExportFrameMode.FRAMEMODE_KEEP: {
265
+ return {
266
+ tiles,
267
+ dimensions: getDimensions$1(tiles.length, imageContext.tilesPerLine),
268
+ contextUpdates: {}
269
+ };
405
270
  }
406
- }
407
- // This paints the tile with a specified offset and pixel width
408
- paintTile(pixels, index) {
409
- if (!this.rawImageData) {
410
- return;
271
+ case ExportFrameMode.FRAMEMODE_CROP: {
272
+ return getCroppedTiles(tiles, imageContext);
411
273
  }
412
- const tileXOffset = index % this.tilesPerLine;
413
- const tileYOffset = Math.floor(index / this.tilesPerLine);
414
- const pixelXOffset = TILE_PIXEL_WIDTH * tileXOffset;
415
- const pixelYOffset = TILE_PIXEL_HEIGHT * tileYOffset;
416
- for (let x = 0; x < TILE_PIXEL_WIDTH; x += 1) {
417
- for (let y = 0; y < TILE_PIXEL_HEIGHT; y += 1) {
418
- const rawIndex = (pixelXOffset + x + (pixelYOffset + y) * this.tilesPerLine * TILE_PIXEL_WIDTH) * 4;
419
- if (pixels !== null) {
420
- const color = getRGBValue({
421
- pixels,
422
- index: y * TILE_PIXEL_WIDTH + x,
423
- tileIndex: index,
424
- imageStartLine: this.imageStartLine,
425
- handleExportFrame: ExportFrameMode.FRAMEMODE_KEEP,
426
- colorData: this.colorData,
427
- frameColorData: this.frameColorData
428
- });
429
- this.rawImageData[rawIndex] = color.r;
430
- this.rawImageData[rawIndex + 1] = color.g;
431
- this.rawImageData[rawIndex + 2] = color.b;
432
- this.rawImageData[rawIndex + 3] = 255;
433
- } else {
434
- this.rawImageData[rawIndex] = 0;
435
- this.rawImageData[rawIndex + 1] = 0;
436
- this.rawImageData[rawIndex + 2] = 0;
437
- this.rawImageData[rawIndex + 3] = 0;
438
- }
439
- }
274
+ case ExportFrameMode.FRAMEMODE_SQUARE_BLACK:
275
+ case ExportFrameMode.FRAMEMODE_SQUARE_WHITE: {
276
+ const padLine = padLines[checkFrameMode];
277
+ return getPaddedSquare(tiles, padLine, imageContext);
440
278
  }
279
+ default:
280
+ throw new Error(`unknown export mode ${imageContext.handleExportFrame}`);
441
281
  }
442
- paintTileScaled(pixels, index, canvasContext, pixelSize, tilesPerLine, handleExportFrame) {
443
- const tileXOffset = index % tilesPerLine;
444
- const tileYOffset = Math.floor(index / tilesPerLine);
445
- const pixelXOffset = TILE_PIXEL_WIDTH * tileXOffset * pixelSize;
446
- const pixelYOffset = TILE_PIXEL_HEIGHT * tileYOffset * pixelSize;
447
- for (let x = 0; x < TILE_PIXEL_WIDTH; x += 1) {
448
- for (let y = 0; y < TILE_PIXEL_HEIGHT; y += 1) {
282
+ };
283
+ const paintTile = (rawImageData, pixels, index, imageContext) => {
284
+ const tileXOffset = index % imageContext.tilesPerLine;
285
+ const tileYOffset = Math.floor(index / imageContext.tilesPerLine);
286
+ const pixelXOffset = TILE_PIXEL_WIDTH * tileXOffset;
287
+ const pixelYOffset = TILE_PIXEL_HEIGHT * tileYOffset;
288
+ for (let x = 0; x < TILE_PIXEL_WIDTH; x += 1) {
289
+ for (let y = 0; y < TILE_PIXEL_HEIGHT; y += 1) {
290
+ const rawIndex = (pixelXOffset + x + (pixelYOffset + y) * imageContext.tilesPerLine * TILE_PIXEL_WIDTH) * 4;
291
+ if (pixels !== null) {
449
292
  const color = getRGBValue({
450
293
  pixels,
451
294
  index: y * TILE_PIXEL_WIDTH + x,
452
295
  tileIndex: index,
453
- imageStartLine: this.imageStartLine,
454
- handleExportFrame,
455
- colorData: this.colorData,
456
- frameColorData: this.frameColorData
296
+ imageContext
457
297
  });
458
- canvasContext.fillStyle = `rgb(${color.r}, ${color.g}, ${color.b})`;
459
- canvasContext.fillRect(
460
- pixelXOffset + x * pixelSize,
461
- pixelYOffset + y * pixelSize,
462
- pixelSize + 1,
463
- pixelSize + 1
464
- );
298
+ rawImageData[rawIndex] = color.r;
299
+ rawImageData[rawIndex + 1] = color.g;
300
+ rawImageData[rawIndex + 2] = color.b;
301
+ rawImageData[rawIndex + 3] = 255;
302
+ } else {
303
+ rawImageData[rawIndex] = 0;
304
+ rawImageData[rawIndex + 1] = 0;
305
+ rawImageData[rawIndex + 2] = 0;
306
+ rawImageData[rawIndex + 3] = 0;
465
307
  }
466
308
  }
467
309
  }
468
- getHeight() {
469
- return TILE_PIXEL_HEIGHT * Math.ceil(this.tiles.length / this.tilesPerLine);
470
- }
471
- getWidth() {
472
- return TILE_PIXEL_WIDTH * this.tilesPerLine;
473
- }
474
- }
475
-
476
- const hx2 = (n) => (n || 0).toString(16).padStart(2, "0");
477
- const paletteTemplates = {
478
- r: (v) => `#${hx2(v)}0000`,
479
- g: (v) => `#00${hx2(v)}00`,
480
- b: (v) => `#0000${hx2(v)}`,
481
- n: (v) => `#${hx2(v)}${hx2(v)}${hx2(v)}`
482
310
  };
483
-
484
- var __defProp = Object.defineProperty;
485
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
486
- var __publicField = (obj, key, value) => {
487
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
488
- return value;
311
+ const renderTile = (rawImageData, rawLine, index, imageContext) => {
312
+ if (rawLine === SKIP_LINE) {
313
+ paintTile(rawImageData, null, index, imageContext);
314
+ } else {
315
+ const tile = decodeTile(rawLine);
316
+ paintTile(rawImageData, tile, index, imageContext);
317
+ }
489
318
  };
490
- const createChannel = (key, decoderOptions) => {
491
- const canvas = decoderOptions.canvasCreator();
492
- const decoder = new Decoder(decoderOptions);
493
- decoder.update({
494
- framePalette: [],
495
- canvas,
496
- tiles: [],
497
- palette: []
498
- });
319
+ const getFullParams$1 = (params) => ({
320
+ tiles: params.tiles,
321
+ imagePalette: params.imagePalette,
322
+ framePalette: params.framePalette || params.imagePalette,
323
+ imageStartLine: typeof params.imageStartLine === "number" ? params.imageStartLine : FRAME_WIDTH,
324
+ tilesPerLine: params.tilesPerLine || TILES_PER_LINE,
325
+ scaleFactor: params.scaleFactor || 1,
326
+ handleExportFrame: params.handleExportFrame || ExportFrameMode.FRAMEMODE_KEEP
327
+ });
328
+ const scaleRawImageData = (data, width, height, scale) => {
329
+ const newWidth = width * scale;
330
+ const newHeight = height * scale;
331
+ const scaled = new Uint8ClampedArray(newWidth * newHeight * 4);
332
+ for (let y = 0; y < height; y += 1) {
333
+ for (let x = 0; x < width; x += 1) {
334
+ const srcIndex = (y * width + x) * 4;
335
+ const r = data[srcIndex];
336
+ const g = data[srcIndex + 1];
337
+ const b = data[srcIndex + 2];
338
+ const a = data[srcIndex + 3];
339
+ for (let dy = 0; dy < scale; dy += 1) {
340
+ for (let dx = 0; dx < scale; dx += 1) {
341
+ const destX = x * scale + dx;
342
+ const destY = y * scale + dy;
343
+ const destIndex = (destY * newWidth + destX) * 4;
344
+ scaled[destIndex] = r;
345
+ scaled[destIndex + 1] = g;
346
+ scaled[destIndex + 2] = b;
347
+ scaled[destIndex + 3] = a;
348
+ }
349
+ }
350
+ }
351
+ }
499
352
  return {
500
- key,
501
- decoder,
502
- canvas
353
+ data: scaled,
354
+ dimensions: {
355
+ width: newWidth,
356
+ height: newHeight
357
+ }
503
358
  };
504
359
  };
505
- class RGBNDecoder {
506
- constructor(options) {
507
- __publicField(this, "canvas");
508
- __publicField(this, "palette");
509
- __publicField(this, "lockFrame");
510
- __publicField(this, "channels");
511
- __publicField(this, "tilesPerLine");
512
- __publicField(this, "canvasCreator");
513
- __publicField(this, "imageDataCreator");
514
- this.canvas = null;
515
- this.palette = defaultPalette;
516
- this.lockFrame = false;
517
- this.tilesPerLine = options?.tilesPerLine || TILES_PER_LINE;
518
- this.canvasCreator = options?.canvasCreator || createCanvasElement;
519
- this.imageDataCreator = options?.imageDataCreator || createImageData;
520
- const channelDecoderOptions = {
521
- tilesPerLine: this.tilesPerLine,
522
- canvasCreator: this.canvasCreator,
523
- imageDataCreator: this.imageDataCreator
524
- };
525
- this.channels = {
526
- r: createChannel(ChannelKey.R, channelDecoderOptions),
527
- g: createChannel(ChannelKey.G, channelDecoderOptions),
528
- b: createChannel(ChannelKey.B, channelDecoderOptions),
529
- n: createChannel(ChannelKey.N, channelDecoderOptions)
530
- };
531
- }
532
- update({
533
- canvas,
360
+ const getRawMonochromeImageData = (params) => {
361
+ const {
534
362
  tiles,
535
- palette,
536
- lockFrame = false
537
- }) {
538
- const canvasChanged = canvas ? this.setCanvas(canvas) : false;
539
- const paletteChanged = this.setPalette(palette);
540
- const lockFrameChanged = this.setLockFrame(lockFrame);
541
- const shouldUpdate = canvasChanged || paletteChanged || lockFrameChanged;
542
- const canvases = this.setTiles(tiles);
543
- const { width: newWidth, height: newHeight } = this.getDimensions(canvases);
544
- if (!shouldUpdate) {
545
- return;
546
- }
547
- if (!this.canvas) {
548
- return;
549
- }
550
- if (newHeight === 0) {
551
- this.canvas.height = 0;
552
- return;
553
- }
554
- if (this.canvas.height !== newHeight) {
555
- this.canvas.height = newHeight;
556
- }
557
- if (this.canvas.width !== newWidth) {
558
- this.canvas.width = newWidth;
559
- }
560
- const context = this.canvas?.getContext("2d");
561
- if (!context) {
562
- return;
563
- }
564
- this.blendCanvases(context, canvases);
565
- }
566
- setPalette(palette) {
567
- if (!palette) {
568
- return false;
569
- }
570
- if (JSON.stringify(this.palette) === JSON.stringify(palette)) {
571
- return false;
572
- }
573
- this.palette = palette;
574
- return true;
575
- }
576
- setCanvas(canvas) {
577
- if (this.canvas === canvas) {
578
- return false;
579
- }
580
- this.canvas = canvas;
581
- return true;
363
+ imageStartLine,
364
+ imagePalette,
365
+ framePalette,
366
+ tilesPerLine,
367
+ handleExportFrame,
368
+ scaleFactor
369
+ } = params;
370
+ const imageContext = {
371
+ tilesPerLine,
372
+ imageStartLine,
373
+ handleExportFrame,
374
+ ...getPalettes(imagePalette, framePalette, tilesPerLine || TILES_PER_LINE)
375
+ };
376
+ const {
377
+ tiles: usedTiles,
378
+ dimensions: {
379
+ width,
380
+ height
381
+ },
382
+ contextUpdates
383
+ } = applyCrop(tiles, imageContext);
384
+ const updatedContext = {
385
+ ...imageContext,
386
+ ...contextUpdates
387
+ };
388
+ if (!height || !width) {
389
+ throw new Error("Image has no dimensions");
582
390
  }
583
- setLockFrame(lockFrame) {
584
- if (lockFrame !== this.lockFrame) {
585
- this.lockFrame = lockFrame;
586
- return true;
587
- }
588
- return false;
391
+ const rawImageData = new Uint8ClampedArray(width * height * 4);
392
+ usedTiles.forEach((newTile, index) => {
393
+ renderTile(rawImageData, newTile, index, updatedContext);
394
+ });
395
+ return scaleRawImageData(rawImageData, width, height, scaleFactor);
396
+ };
397
+ const getMonochromeImageUrl = async (params, canvasCreator = createCanvasElement) => {
398
+ const urlCache = new UrlCache();
399
+ const fullParams = getFullParams$1(params);
400
+ const hash = ohash.hash(fullParams);
401
+ const cachedUrl = await urlCache.getUrl(hash);
402
+ if (cachedUrl) {
403
+ return cachedUrl;
404
+ }
405
+ const rawOutput = getRawMonochromeImageData(fullParams);
406
+ return dataUrlFromRawOutput(rawOutput, fullParams.scaleFactor, hash, canvasCreator);
407
+ };
408
+
409
+ const getFullParams = (params) => ({
410
+ tiles: params.tiles,
411
+ palette: params.palette,
412
+ lockFrame: params.lockFrame || false,
413
+ imageStartLine: typeof params.imageStartLine === "number" ? params.imageStartLine : FRAME_WIDTH,
414
+ tilesPerLine: params.tilesPerLine || TILES_PER_LINE,
415
+ scaleFactor: params.scaleFactor || 1,
416
+ handleExportFrame: params.handleExportFrame || ExportFrameMode.FRAMEMODE_KEEP
417
+ });
418
+ const singleChannelPalette = (palette, channelKey) => {
419
+ switch (channelKey) {
420
+ case ChannelKey.R:
421
+ return palette.map((shade) => (shade & 255) << 16).reverse();
422
+ case ChannelKey.G:
423
+ return palette.map((shade) => (shade & 255) << 8).reverse();
424
+ case ChannelKey.B:
425
+ return palette.map((shade) => shade & 255).reverse();
426
+ default:
427
+ return palette.map((shade) => {
428
+ const base = shade & 255;
429
+ return (base << 16) + (base << 8) + base;
430
+ }).reverse();
589
431
  }
590
- setTiles(tiles) {
591
- return channels.reduce((acc, key) => {
592
- const channel = this.channels[key];
593
- channel.tiles = tiles[key];
594
- const channelColors = this.palette[key];
595
- const paletteFunction = paletteTemplates[key];
596
- if (!channel.tiles || !channelColors) {
597
- return acc;
598
- }
599
- const palette = [
600
- paletteFunction(channelColors[3]),
601
- paletteFunction(channelColors[2]),
602
- paletteFunction(channelColors[1]),
603
- paletteFunction(channelColors[0])
604
- ];
605
- channel.decoder.update({
606
- canvas: channel.canvas,
607
- tiles: channel.tiles,
608
- framePalette: this.lockFrame ? BW_PALETTE_HEX : palette,
609
- palette
610
- });
611
- return {
612
- ...acc,
613
- [key]: channel.canvas
614
- };
615
- }, {});
432
+ };
433
+ const getDimensions = (canvases) => Object.values(canvases).reduce((acc, current) => {
434
+ if (current.width === 0 || current.height === 0) {
435
+ return acc;
616
436
  }
617
- blendCanvases(targetContext, sourceCanvases) {
618
- channels.forEach((key) => {
619
- const sourceCanvas = sourceCanvases[key];
620
- if (sourceCanvas && sourceCanvas.width && sourceCanvas.height) {
621
- if (key === ChannelKey.N) {
622
- if (this.palette.blend === BlendMode.NORMAL) {
623
- return;
624
- }
625
- targetContext.globalCompositeOperation = blendModeNewName(this.palette.blend);
626
- } else {
627
- targetContext.globalCompositeOperation = "lighter";
437
+ return {
438
+ width: Math.max(current.width, acc.width),
439
+ height: Math.max(current.height, acc.height)
440
+ };
441
+ }, { width: 0, height: 0 });
442
+ const blendCanvases = (sourceCanvases, blendMode, canvasCreator) => {
443
+ const dimensions = getDimensions(sourceCanvases);
444
+ const targetCanvas = canvasCreator();
445
+ targetCanvas.width = dimensions.width;
446
+ targetCanvas.height = dimensions.height;
447
+ const targetContext = targetCanvas.getContext("2d");
448
+ channels.forEach((key) => {
449
+ const sourceCanvas = sourceCanvases[key];
450
+ if (sourceCanvas && sourceCanvas.width && sourceCanvas.height) {
451
+ if (key === ChannelKey.N) {
452
+ if (blendMode === BlendMode.NORMAL) {
453
+ return;
628
454
  }
629
- targetContext.drawImage(sourceCanvas, 0, 0);
455
+ targetContext.globalCompositeOperation = blendModeNewName(blendMode);
456
+ } else {
457
+ targetContext.globalCompositeOperation = "lighter";
630
458
  }
459
+ targetContext.drawImage(sourceCanvas, 0, 0);
460
+ }
461
+ });
462
+ const imageData = targetContext.getImageData(0, 0, dimensions.width, dimensions.height);
463
+ return {
464
+ data: imageData.data,
465
+ dimensions: {
466
+ width: imageData.width,
467
+ height: imageData.height
468
+ }
469
+ };
470
+ };
471
+ const getRawRGBNImageData = (params, canvasCreator) => {
472
+ const {
473
+ tiles,
474
+ imageStartLine,
475
+ palette,
476
+ lockFrame,
477
+ tilesPerLine,
478
+ handleExportFrame,
479
+ scaleFactor
480
+ } = params;
481
+ const canvases = Object.entries(tiles).reduce((acc, [key, channelTiles]) => {
482
+ const channelKey = key;
483
+ const channelShades = palette[channelKey] || RGBN_SHADES;
484
+ const channelPalette = singleChannelPalette(channelShades, channelKey);
485
+ const lockFramePalette = lockFrame ? singleChannelPalette(RGBN_SHADES, channelKey) : channelPalette;
486
+ const {
487
+ data,
488
+ dimensions
489
+ } = getRawMonochromeImageData({
490
+ imagePalette: channelPalette,
491
+ framePalette: lockFramePalette,
492
+ handleExportFrame,
493
+ imageStartLine,
494
+ scaleFactor,
495
+ tiles: channelTiles,
496
+ tilesPerLine
631
497
  });
632
- }
633
- getScaledCanvas(scaleFactor, handleExportFrame = ExportFrameMode.FRAMEMODE_KEEP) {
634
- const canvas = this.canvasCreator();
635
- const canvases = channels.reduce((acc, key) => {
636
- const channel = this.channels[key];
637
- const channelCanvas = channel.decoder.getScaledCanvas(scaleFactor, handleExportFrame);
638
- return {
639
- ...acc,
640
- [key]: channelCanvas
641
- };
642
- }, {});
643
- const { width, height } = this.getDimensions(canvases);
644
- canvas.width = width;
645
- canvas.height = height;
498
+ const canvas = canvasCreator();
499
+ canvas.width = dimensions.width;
500
+ canvas.height = dimensions.height;
646
501
  const context = canvas.getContext("2d");
647
- if (!context) {
648
- throw new Error("no canvas context");
649
- }
650
- context.fillStyle = "#000000";
651
- context.fillRect(0, 0, 500, 500);
652
- this.blendCanvases(context, canvases);
653
- return canvas;
654
- }
655
- getDimensions(canvases) {
656
- return Object.values(canvases).reduce((acc, current) => {
657
- if (current.width === 0 || current.height === 0) {
658
- return acc;
659
- }
660
- return {
661
- width: Math.max(current.width, acc.width),
662
- height: Math.max(current.height, acc.height)
663
- };
664
- }, { width: 0, height: 0 });
665
- }
666
- }
502
+ const imageData = new ImageData(data, dimensions.width, dimensions.height);
503
+ context.putImageData(imageData, 0, 0);
504
+ return {
505
+ ...acc,
506
+ [channelKey]: canvas
507
+ };
508
+ }, {});
509
+ return blendCanvases(canvases, palette.blend || BlendMode.NORMAL, canvasCreator);
510
+ };
511
+ const getRGBNImageUrl = async (params, canvasCreator = createCanvasElement) => {
512
+ const urlCache = new UrlCache();
513
+ const fullParams = getFullParams(params);
514
+ const hash = ohash.hash(fullParams);
515
+ const cachedUrl = await urlCache.getUrl(hash);
516
+ if (cachedUrl) {
517
+ return cachedUrl;
518
+ }
519
+ const rawOutput = getRawRGBNImageData(fullParams, canvasCreator);
520
+ return dataUrlFromRawOutput(rawOutput, fullParams.scaleFactor, hash, canvasCreator);
521
+ };
667
522
 
668
523
  const maxTiles = (rgbnTiles) => Math.max(...channels.map((key) => rgbnTiles[key]?.length || 0));
669
524
 
525
+ exports.BLACK = BLACK;
526
+ exports.BLACK_LINE = BLACK_LINE;
670
527
  exports.BW_PALETTE = BW_PALETTE;
671
528
  exports.BW_PALETTE_HEX = BW_PALETTE_HEX;
672
529
  exports.BlendMode = BlendMode;
673
530
  exports.ChannelKey = ChannelKey;
674
- exports.Decoder = Decoder;
675
531
  exports.ExportFrameMode = ExportFrameMode;
676
- exports.RGBNDecoder = RGBNDecoder;
532
+ exports.FRAME_WIDTH = FRAME_WIDTH;
533
+ exports.RGBN_SHADES = RGBN_SHADES;
677
534
  exports.SKIP_LINE = SKIP_LINE;
535
+ exports.TILES_PER_COLUMN = TILES_PER_COLUMN;
536
+ exports.TILES_PER_LINE = TILES_PER_LINE;
537
+ exports.TILE_PIXEL_HEIGHT = TILE_PIXEL_HEIGHT;
538
+ exports.TILE_PIXEL_WIDTH = TILE_PIXEL_WIDTH;
539
+ exports.UrlCache = UrlCache;
540
+ exports.WHITE = WHITE;
541
+ exports.WHITE_LINE = WHITE_LINE;
678
542
  exports.blendModeNewName = blendModeNewName;
543
+ exports.channels = channels;
679
544
  exports.decodeTile = decodeTile;
545
+ exports.defaultRGBNPalette = defaultRGBNPalette;
546
+ exports.getDimensions = getDimensions$1;
547
+ exports.getMonochromeImageUrl = getMonochromeImageUrl;
548
+ exports.getRGBNImageUrl = getRGBNImageUrl;
680
549
  exports.getRGBValue = getRGBValue;
550
+ exports.getRawMonochromeImageData = getRawMonochromeImageData;
551
+ exports.getRawRGBNImageData = getRawRGBNImageData;
681
552
  exports.maxTiles = maxTiles;
553
+ exports.scaleRawImageData = scaleRawImageData;
682
554
  exports.tileIndexIsPartOfFrame = tileIndexIsPartOfFrame;