All files / src/components/rendering TilemapLayersCanvas.tsx

92.98% Statements 53/57
61.53% Branches 16/26
100% Functions 13/13
94.64% Lines 53/56

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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 1951x 1x 1x           1x 1x           1x 1x                                                 1x       4x 1x 1x 1x                   1x                     4x   4x 4x 4x   4x 4x 3x   4x 4x 4x   4x   4x   1x       4x   4x 1x                     4x   4x   4x       4x 1x 1x     3x   3x         3x 3x 3x 3x 3x         4x 3x     4x 4x   4x         4x 4x 4x                   4x                                               4x                     1x  
import React, { memo, useCallback, useEffect, useMemo, useRef } from "react";
import { useAppSelector, shallowEqualArray } from "store/hooks";
import { assetURL } from "shared/lib/helpers/assets";
import type {
  MonoBGPPalette,
  Palette,
  SceneTilemapData,
} from "shared/lib/resources/types";
import { TILE_SIZE } from "consts";
import { getSettings } from "store/features/settings/settingsState";
import type { RootState } from "store/configureStore";
import type {
  TilemapLayersCanvasResult,
  TilemapLayersWorkerTileset,
} from "./TilemapLayersCanvas.worker";
import { scheduleFlattenTilemap } from "./tilemapLayersScheduler";
import {
  createTilemapLayersWorkerHandle,
  TilemapLayersWorkerHandle,
} from "./tilemapLayersWorkerPool";
 
interface TilemapLayersCanvasProps {
  width: number;
  height: number;
  tilemap: SceneTilemapData;
  tileColors: number[];
  palettes: Palette[];
  previewAsMono?: boolean;
  monoBGP: MonoBGPPalette;
  priority?: boolean;
}
 
type TilemapLayersTileset = {
  id: string;
  width: number;
  height: number;
  filename: string;
  plugin?: string;
  _v?: number;
};
 
const sceneTilemapTilesetsSelector = (
  state: RootState,
  snapshotIds: string[],
): Array<TilemapLayersTileset | undefined> =>
  snapshotIds.map((tilesetId) => {
    const tileset = state.project.present.entities.tilesets.entities[tilesetId];
    Iif (!tileset) return undefined;
    return {
      id: tileset.id,
      width: tileset.width,
      height: tileset.height,
      filename: tileset.filename,
      plugin: tileset.plugin,
      _v: tileset._v,
    };
  });
 
const TilemapLayersCanvas = memo(
  ({
    width,
    height,
    tilemap,
    tileColors,
    palettes,
    previewAsMono,
    monoBGP,
    priority,
  }: TilemapLayersCanvasProps) => {
    const canvasRef = useRef<HTMLCanvasElement>(null);
 
    const canvasId = useRef(`${Date.now()}-${Math.random()}`);
    const nextRequestSequence = useRef(0);
    const lastRenderedSequence = useRef(0);
 
    const worker = useRef<TilemapLayersWorkerHandle | null>(null);
    if (!worker.current) {
      worker.current = createTilemapLayersWorkerHandle(canvasId.current);
    }
    const workerHandle = worker.current;
    const colorCorrection = useAppSelector(
      (state) => getSettings(state).colorCorrection,
    );
    const tilesets = useAppSelector(
      (state) =>
        sceneTilemapTilesetsSelector(
          state,
          tilemap.tilesets.map(({ id }) => id),
        ),
      shallowEqualArray,
    );
    const workerTilesets = useMemo(
      (): Array<TilemapLayersWorkerTileset | undefined> =>
        tilesets.map((tileset) =>
          tileset
            ? {
                id: tileset.id,
                width: tileset.width,
                src: assetURL("tilesets", tileset),
              }
            : undefined,
        ),
      [tilesets],
    );
 
    const onWorkerComplete = useCallback(
      (event: MessageEvent<TilemapLayersCanvasResult>) => {
        const { canvasId: resultCanvasId, sequence, canvasImage } = event.data;
 
        Iif (resultCanvasId !== canvasId.current) {
          return;
        }
 
        if (!canvasRef.current || sequence <= lastRenderedSequence.current) {
          canvasImage.close?.();
          return;
        }
 
        const ctx = canvasRef.current.getContext("2d");
 
        Iif (!ctx) {
          canvasImage.close?.();
          return;
        }
 
        ctx.clearRect(0, 0, width * TILE_SIZE, height * TILE_SIZE);
        ctx.imageSmoothingEnabled = false;
        ctx.drawImage(canvasImage, 0, 0);
        canvasImage.close?.();
        lastRenderedSequence.current = sequence;
      },
      [height, width],
    );
 
    useEffect(() => {
      return workerHandle.subscribe(onWorkerComplete);
    }, [onWorkerComplete, workerHandle]);
 
    useEffect(() => {
      const sequence = ++nextRequestSequence.current;
 
      return scheduleFlattenTilemap(
        tilemap,
        width,
        height,
        (flattenedTiles) => {
          const tiles = new Uint32Array(flattenedTiles);
          const workerTileColors = Uint8Array.from(tileColors);
          workerHandle.request(
            {
              canvasId: canvasId.current,
              sequence,
              width,
              height,
              tiles,
              tileColors: workerTileColors,
              tilesetSnapshots: tilemap.tilesets,
              tilesets: workerTilesets,
              palettes: palettes.map((palette) => palette.colors),
              previewAsMono,
              monoBGP,
              colorCorrection,
            },
            [tiles.buffer, workerTileColors.buffer],
          );
        },
        priority,
      );
    }, [
      colorCorrection,
      height,
      monoBGP,
      palettes,
      priority,
      previewAsMono,
      tileColors,
      tilemap,
      width,
      workerHandle,
      workerTilesets,
    ]);
 
    return (
      <canvas
        ref={canvasRef}
        width={width * TILE_SIZE}
        height={height * TILE_SIZE}
        style={{ display: "block", imageRendering: "pixelated" }}
      />
    );
  },
);
 
export default TilemapLayersCanvas;