All files / src/components/sprites/preview SpriteSliceCanvas.worker.ts

0% Statements 0/42
0% Branches 0/5
0% Functions 0/3
0% Lines 0/41

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82                                                                                                                                                                   
import { colorizeSpriteData } from "shared/lib/helpers/color";
 
// eslint-disable-next-line no-restricted-globals
const workerCtx: Worker = self as unknown as Worker;
 
interface CacheRecord {
  // canvas: OffscreenCanvas;
  // ctx: OffscreenCanvasRenderingContext2D;
  img: ImageBitmap;
}
 
export interface SpriteSliceCanvasResult {
  id: number;
  canvasImage: ImageBitmap;
}
 
const cache: Record<string, CacheRecord> = {};
 
workerCtx.onmessage = async (evt) => {
  const id = evt.data.id;
  const src = evt.data.src;
  const offsetX = evt.data.offsetX;
  const offsetY = evt.data.offsetY;
  const width = evt.data.width;
  const height = evt.data.height;
  const flipX = evt.data.flipX;
  const flipY = evt.data.flipY;
  const objPalette = evt.data.objPalette;
  const palette = evt.data.palette;
 
  let img: ImageBitmap;
 
  if (cache[src]) {
    // Using Cached Data
    img = cache[src].img;
  } else {
    const imgblob = await fetch(src).then((r) => r.blob());
    img = await createImageBitmap(imgblob);
    cache[src] = {
      img,
    };
  }
 
  // Fetch New Data
  const canvas = new OffscreenCanvas(width, height);
  const tmpCtx = canvas.getContext("2d");
  Iif (!tmpCtx) {
    return;
  }
  const ctx = tmpCtx;
 
  // Draw Sprite
  ctx.save();
  Iif (flipX) {
    ctx.translate(width, 0);
    ctx.scale(-1, 1);
  }
  Iif (flipY) {
    ctx.translate(0, height);
    ctx.scale(1, -1);
  }
  ctx.drawImage(img, -offsetX, -offsetY);
  ctx.restore();
 
  // Colorize
  const imageData = ctx.getImageData(0, 0, width, height);
  colorizeSpriteData(imageData.data, objPalette, palette);
  ctx.putImageData(imageData, 0, 0);
 
  const canvasImage = canvas.transferToImageBitmap();
  const res: SpriteSliceCanvasResult = { id, canvasImage };
  workerCtx.postMessage(res, [canvasImage]);
};
 
// -----------------------------------------------------------------
 
export default class W extends Worker {
  constructor() {
    super("");
  }
}