All files / src/lib/compiler compileSceneTilemaps.ts

96.51% Statements 83/86
82.85% Branches 58/70
100% Functions 15/15
96.42% Lines 81/84

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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 2653x                 3x       3x 3x 3x 3x             3x 3x           3x         3x                                         3x   3x                 28x     28x         28x 4x     4x                               24x   24x 27x 27x 24x                 24x           24x 24x   24x   24x 9519x 9519x 2153x   7366x     24x 24x   24x 1x         1x 1x     24x 3x 3x 1080x 1080x 1080x   1080x 3x 1080x 1080x 1080x   3x                             21x 21x 7599x   36x 25x 35x 21x 21x 21x 21x     21x 21x 40x 40x   21x 7599x       7599x 7599x         7599x   21x 21x 21x                 21x                               3x               11x       23x   3x 3x 3x       3x     3x                         3x  
import {
  TILE_FIRST_CHUNK_SIZE,
  TILE_BANK_SIZE,
  FLAG_VRAM_BANK_1,
  MAX_BACKGROUND_TILES_CGB,
  MAX_BACKGROUND_TILES,
  SCREEN_WIDTH,
  SCREEN_HEIGHT,
} from "consts";
import {
  imageTileAllocationColorOnly,
  imageTileAllocationDefault,
} from "lib/compiler/tileAllocation";
import { readFileToTilesDataArray } from "lib/tiles/readFileToTiles";
import { padArrayEnd } from "shared/lib/helpers/array";
import { assetFilename } from "shared/lib/helpers/assets";
import l10n from "shared/lib/lang/l10n";
import {
  Tileset,
  ColorModeSetting,
  SceneTilemapData,
  Scene,
} from "shared/lib/resources/types";
import { autoFlipTileData } from "shared/lib/tiles/autoFlip";
import {
  tileArrayToTileData,
  hashTileData,
  toTileLookup,
  tilesAndLookupToTilemap,
} from "shared/lib/tiles/tileData";
import {
  flattenTilemapLayers,
  buildSceneTilesetLookup,
  decodeSceneTileRef,
} from "shared/lib/tiles/sceneTilemapData";
import promiseLimit from "lib/helpers/promiseLimit";
 
type PrecompiledSceneTilemapData = {
  id: string;
  name: string;
  symbol: string;
  width: number;
  height: number;
  commonTilesetId?: string;
  vramData: [number[], number[]];
  tilemap: number[];
  attr: number[];
  is360: boolean;
  colorMode: ColorModeSetting;
  tilesetLength: number;
};
 
type CompileImageOptions = {
  warnings: (msg: string) => void;
};
 
const BLANK_TILE = new Uint8Array(16);
 
export const compileTilemapLayers = async (
  scene: Scene & { tilemap: SceneTilemapData },
  tilesetsLookup: Record<string, Tileset>,
  commonTileset: Tileset | undefined,
  colorMode: ColorModeSetting,
  projectPath: string,
  autoTileFlipEnabled: boolean,
  { warnings }: CompileImageOptions,
): Promise<PrecompiledSceneTilemapData> => {
  const sceneTilemap = scene.tilemap;
 
  const isInvalidSize =
    scene.width < SCREEN_WIDTH ||
    scene.height < SCREEN_HEIGHT ||
    scene.width > 255 ||
    scene.height > 255;
 
  if (isInvalidSize) {
    warnings(
      `Tilemap used by scene "${scene.name}" is an invalid size ${scene.width}x${scene.height}`,
    );
    return {
      id: scene.id,
      name: scene.name,
      symbol: `${scene.symbol}_bg`,
      width: SCREEN_WIDTH,
      height: SCREEN_HEIGHT,
      vramData: [[...BLANK_TILE], []],
      tilemap: new Array(SCREEN_WIDTH * SCREEN_HEIGHT).fill(0),
      attr: new Array(SCREEN_WIDTH * SCREEN_HEIGHT).fill(0),
      is360: false,
      colorMode,
      commonTilesetId: commonTileset?.id,
      tilesetLength: 1,
    };
  }
 
  const sourceTiles = new Map<string, Uint8Array[]>();
 
  for (const { id: tilesetId } of sceneTilemap.tilesets) {
    const tileset = tilesetsLookup[tilesetId];
    if (tileset) {
      sourceTiles.set(
        tilesetId,
        await readFileToTilesDataArray(
          assetFilename(projectPath, "tilesets", tileset),
        ),
      );
    }
  }
 
  const commonTileData = commonTileset
    ? await readFileToTilesDataArray(
        assetFilename(projectPath, "tilesets", commonTileset),
      )
    : [];
 
  const refs = flattenTilemapLayers(sceneTilemap, scene.width, scene.height);
  const sceneAttrs = sceneTilemap.tileColors ?? [];
 
  const tilesetLookup = buildSceneTilesetLookup(sceneTilemap);
 
  let cellTiles = refs.map((value) => {
    const ref = decodeSceneTileRef(value, tilesetLookup);
    if (!ref) {
      return BLANK_TILE;
    }
    return sourceTiles.get(ref.tilesetId)?.[ref.tileIndex] ?? BLANK_TILE;
  });
 
  let attrs = sceneAttrs;
  const cgbOnly = colorMode === "color";
 
  if (cgbOnly && autoTileFlipEnabled) {
    const flipped = autoFlipTileData({
      tileData: cellTiles,
      tileColors: attrs,
      commonTileData,
    });
    cellTiles = flipped.tileData;
    attrs = flipped.tileAttrs;
  }
 
  if (scene.type === "LOGO") {
    const logoTileCount = SCREEN_WIDTH * SCREEN_HEIGHT;
    const logoTiles = Array.from({ length: logoTileCount }, (_, index) => {
      const x = index % SCREEN_WIDTH;
      const y = Math.floor(index / SCREEN_WIDTH);
      return cellTiles[y * scene.width + x] ?? BLANK_TILE;
    });
    const tilemap = Array.from({ length: logoTileCount }, (_, index) => index);
    const attr = Array.from({ length: logoTileCount }, (_, index) => {
      const x = index % SCREEN_WIDTH;
      const y = Math.floor(index / SCREEN_WIDTH);
      return attrs[y * scene.width + x] ?? 0;
    });
    return {
      id: scene.id,
      name: scene.name,
      symbol: `${scene.symbol}_bg`,
      width: SCREEN_WIDTH,
      height: SCREEN_HEIGHT,
      vramData: [[...tileArrayToTileData(logoTiles)], []],
      tilemap,
      attr,
      is360: true,
      colorMode,
      tilesetLength: logoTileCount,
    };
  }
 
  const commonHashes = new Set(commonTileData.map(hashTileData));
  const uniqueTiles = Array.from(
    new Map(cellTiles.map((tile) => [hashTileData(tile), tile])).entries(),
  )
    .filter(([hash]) => !commonHashes.has(hash))
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([, tile]) => tile);
  const tilesetData = [...commonTileData, ...uniqueTiles];
  const tilesetDataLookup = toTileLookup(tilesetData);
  const tilemap = tilesAndLookupToTilemap(cellTiles, tilesetDataLookup);
  const allocation = cgbOnly
    ? imageTileAllocationColorOnly
    : imageTileAllocationDefault;
  const vramData: [number[], number[]] = [[], []];
  Object.values(tilesetDataLookup).forEach((tile, index, tiles) => {
    const { inVRAM2 } = allocation(index, tiles.length);
    vramData[inVRAM2 ? 1 : 0].push(...tile);
  });
  const attr = padArrayEnd(attrs, tilemap.length, 0).map((value, index) => {
    const { inVRAM2, tileIndex } = allocation(
      tilemap[index] ?? 0,
      Object.keys(tilesetDataLookup).length,
    );
    if (tileIndex < TILE_FIRST_CHUNK_SIZE) {
      tilemap[index] = tileIndex;
    } else E{
      const bankSize = vramData[inVRAM2 ? 1 : 0].length / 16;
      tilemap[index] = tileIndex + Math.max(TILE_BANK_SIZE - bankSize, 0);
    }
    return inVRAM2 ? value | FLAG_VRAM_BANK_1 : value;
  });
  const tilesetLength = Object.keys(tilesetDataLookup).length;
  const maxTiles = cgbOnly ? MAX_BACKGROUND_TILES_CGB : MAX_BACKGROUND_TILES;
  Iif (tilesetLength > maxTiles) {
    warnings(
      l10n("WARNING_TILEMAP_TOO_MANY_TILES", {
        tilesetLength,
        maxTilesetLength: maxTiles,
      }),
    );
  }
 
  return {
    id: scene.id,
    name: scene.name,
    symbol: `${scene.symbol}_bg`,
    width: scene.width,
    height: scene.height,
    vramData,
    tilemap,
    attr,
    is360: false,
    colorMode,
    commonTilesetId: commonTileset?.id,
    tilesetLength,
  };
};
 
const compileSceneTilemaps = (
  scenes: Scene[],
  tilesetsLookup: Record<string, Tileset>,
  projectColorMode: ColorModeSetting,
  projectPath: string,
  autoTileFlipEnabled: boolean,
  { warnings }: CompileImageOptions,
): Promise<PrecompiledSceneTilemapData[]> => {
  return promiseLimit(
    10,
    scenes
      .filter((scene): scene is Scene & { tilemap: SceneTilemapData } =>
        Boolean(scene.tilemap),
      )
      .map((scene) => () => {
        const tilemap = scene.tilemap;
        const commonTileset = scene.tilesetId
          ? tilesetsLookup[scene.tilesetId]
          : undefined;
        const colorMode =
          projectColorMode === "mono" || scene.colorModeOverride === "none"
            ? projectColorMode
            : scene.colorModeOverride;
        return compileTilemapLayers(
          { ...scene, tilemap },
          tilesetsLookup,
          commonTileset,
          colorMode,
          projectPath,
          autoTileFlipEnabled,
          { warnings },
        );
      }),
  );
};
 
export default compileSceneTilemaps;