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