gb-image-decoder 1.3.1 → 2.0.1

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