All files / src/lib/compiler compileSprites.ts

87.27% Statements 96/110
61.11% Branches 33/54
91.66% Functions 22/24
86.91% Lines 93/107

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 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 3105x 5x 5x         5x 5x               5x         5x 5x 5x 5x 5x 5x                                             5x               96x                   5x           14x     14x   14x       14x 14x     63x       14x               14x   14x   14x   14x           112x     112x 56x 56x 56x     96x 96x     96x         96x                                         96x                         96x 96x 96x   96x                 14x 14x 14x 112x 56x 56x 7x 7x   56x       14x 14x 112x 112x 112x 49x   63x 63x   112x           14x     14x 13x 13x     14x                 14x     5x                 8x     7x 7x               8x 7x   7x 7x   8x               8x             8x     8x 8x   8x         8x 8x 8x     8x     8x     5x 112x 112x       49x 49x 49x         49x 49x     63x     5x  
import promiseLimit from "lib/helpers/promiseLimit";
import { indexedImageTo2bppSpriteData } from "shared/lib/sprites/spriteData";
import {
  animationMapBySpriteType,
  toEngineOrder,
} from "shared/lib/sprites/helpers";
import { IndexedImage } from "shared/lib/tiles/indexedImage";
import { assetFilename } from "shared/lib/helpers/assets";
import { optimiseTiles } from "lib/sprites/readSpriteData";
import { ReferencedSprite } from "./precompile/determineUsedAssets";
import {
  ColorModeSetting,
  ObjPalette,
  Sprite,
  SpriteModeSetting,
} from "shared/lib/resources/types";
import {
  spriteTileAllocationColorOnly,
  spriteTileAllocationDefault,
} from "lib/compiler/tileAllocation";
 
const S_PALETTE = 0x10;
const S_FLIPX = 0x20;
const S_FLIPY = 0x40;
const S_PRIORITY = 0x80;
const S_GBC_PALETTE_MASK = 0x7;
const S_VRAM2 = 0x8;
 
interface AnimationOffset {
  start: number;
  end: number;
}
 
export type PrecompiledSpriteSheetData = Sprite & {
  vramData: [number[], number[]];
  tiles: IndexedImage[];
  metasprites: SpriteTileData[][];
  animationOffsets: AnimationOffset[];
  metaspritesOrder: number[];
  colorMode: ColorModeSetting;
};
 
interface SpriteTileData {
  tile: number;
  x: number;
  y: number;
  props: number;
}
 
const makeProps = (
  objPalette: ObjPalette,
  paletteIndex: number,
  flipX: boolean,
  flipY: boolean,
  priority: boolean,
  inVRAM2: boolean,
): number => {
  return (
    (objPalette === "OBP1" ? S_PALETTE : 0) +
    (flipX ? S_FLIPX : 0) +
    (flipY ? S_FLIPY : 0) +
    (priority ? S_PRIORITY : 0) +
    (paletteIndex & S_GBC_PALETTE_MASK) +
    (inVRAM2 ? S_VRAM2 : 0)
  );
};
 
export const compileSprite = async (
  spriteSheet: ReferencedSprite,
  cgbOnly: boolean,
  projectRoot: string,
  defaultSpriteMode: SpriteModeSetting,
): Promise<PrecompiledSpriteSheetData> => {
  const filename = assetFilename(projectRoot, "sprites", spriteSheet);
 
  const spriteMode: SpriteModeSetting =
    spriteSheet.spriteMode ?? defaultSpriteMode ?? "8x16";
 
  const tileAllocationStrategy = cgbOnly
    ? spriteTileAllocationColorOnly
    : spriteTileAllocationDefault;
 
  const metasprites = spriteSheet.states
    .map((state) => state.animations)
    .flat()
    .map((animation) => {
      return animation.frames.map((frame) => frame.tiles);
    })
    .flat();
 
  const { tiles, lookup } = await optimiseTiles(
    filename,
    spriteSheet.canvasWidth,
    spriteSheet.canvasHeight,
    metasprites,
    spriteMode,
  );
 
  const fixedXOffset = spriteSheet.canvasOriginX - 8;
  const fixedYOffset =
    (spriteMode === "8x16" ? 0 : -8) + spriteSheet.canvasOriginY - 8;
 
  const animationDefs: SpriteTileData[][][] = spriteSheet.states
    .map((state) =>
      toEngineOrder(
        animationMapBySpriteType(
          state.animations,
          state.animationType,
          state.flipLeft,
          (animation, flip) => {
            Iif (!animation) {
              return [];
            }
            return animation.frames.map((frame) => {
              let currentX = fixedXOffset;
              let currentY = fixedYOffset;
              return [...frame.tiles]
                .reverse()
                .map((tile) => {
                  const optimisedTile = lookup[tile.id];
                  Iif (!optimisedTile) {
                    return null;
                  }
                  const { tileIndex, inVRAM2 } = tileAllocationStrategy(
                    optimisedTile.tile,
                    tiles.length,
                    spriteMode,
                  );
                  Iif (flip) {
                    const data: SpriteTileData = {
                      tile: tileIndex,
                      x:
                        (spriteSheet.canvasWidth > 8 ? 8 : 0) -
                        tile.x -
                        currentX,
                      y: -tile.y - currentY,
                      props: makeProps(
                        tile.objPalette,
                        tile.paletteIndex,
                        !optimisedTile.flipX,
                        optimisedTile.flipY,
                        tile.priority,
                        inVRAM2,
                      ),
                    };
                    currentX = (spriteSheet.canvasWidth > 8 ? 8 : 0) - tile.x;
                    currentY = -tile.y;
                    return data;
                  }
                  const data: SpriteTileData = {
                    tile: tileIndex,
                    x: tile.x - currentX,
                    y: -tile.y - currentY,
                    props: makeProps(
                      tile.objPalette,
                      tile.paletteIndex,
                      optimisedTile.flipX,
                      optimisedTile.flipY,
                      tile.priority,
                      inVRAM2,
                    ),
                  };
                  currentX = tile.x;
                  currentY = -tile.y;
                  return data;
                })
                .filter((tile) => tile) as SpriteTileData[];
            });
          },
        ),
      ),
    )
    .flat();
 
  // const uniqFrames: SpriteTileData[][] = [];
  const uniqFramesLookup: Record<string, number> = {};
  const uniqFrames: SpriteTileData[][] = [];
  const uniqMap = animationDefs.map((animationDef) => {
    return animationDef.map((frame) => {
      const key = JSON.stringify(frame); // Any hash function can work here
      if (uniqFramesLookup[key] === undefined) {
        uniqFramesLookup[key] = uniqFrames.length;
        uniqFrames.push(frame);
      }
      return uniqFramesLookup[key];
    });
  });
 
  const orderedFrames: number[] = [];
  const animationOffsets = uniqMap.map((uniqIndexes) => {
    let start = 0;
    const matchIndex = firstIndexOfMatch(orderedFrames, uniqIndexes);
    if (matchIndex > -1) {
      start = matchIndex;
    } else {
      start = orderedFrames.length;
      orderedFrames.push(...uniqIndexes);
    }
    return {
      start,
      end: start + Math.max(0, uniqIndexes.length - 1),
    };
  });
 
  const vramData: [number[], number[]] = [[], []];
 
  // Split tiles into VRAM banks based on allocation strategy
  tiles.map(indexedImageTo2bppSpriteData).forEach((tile, i) => {
    const { inVRAM2 } = tileAllocationStrategy(i, tiles.length, spriteMode);
    vramData[inVRAM2 ? 1 : 0].push(...tile);
  });
 
  const precompiled: PrecompiledSpriteSheetData = {
    ...spriteSheet,
    vramData,
    tiles,
    metasprites: uniqFrames,
    animationOffsets,
    metaspritesOrder: orderedFrames,
  };
 
  return precompiled;
};
 
const compileSprites = async (
  spriteSheets: ReferencedSprite[],
  projectRoot: string,
  defaultSpriteMode: SpriteModeSetting,
): Promise<{
  spritesData: PrecompiledSpriteSheetData[];
  statesOrder: string[];
  stateReferences: string[];
}> => {
  const spritesData = await promiseLimit(
    10,
    spriteSheets.map(
      (spriteSheet) => () =>
        compileSprite(
          spriteSheet,
          spriteSheet.colorMode === "color",
          projectRoot,
          defaultSpriteMode,
        ),
    ),
  );
  const stateNames = spritesData
    .map((sprite) => sprite.states)
    .flat()
    .map((state) => state.name)
    .filter((name) => name.length > 0);
 
  const stateCounts = stateNames.reduce(
    (memo, name) => {
      name in memo ? (memo[name] += 1) : (memo[name] = 1);
      return memo;
    },
    {} as Record<string, number>,
  );
 
  const statesOrder = Object.keys(stateCounts).sort((a, b) => {
    if (stateCounts[a] === stateCounts[b]) {
      return 0;
    }
    return stateCounts[a] < stateCounts[b] ? 1 : -1;
  });
 
  statesOrder.unshift("");
 
  // Build reference names for states
  const stateReferences: string[] = [];
  statesOrder.forEach((name) => {
    const refName =
      (name || "Default")
        .replace(/ /g, "_")
        .replace(/[^a-zA-Z0-9_]/g, "")
        .toUpperCase() || "S";
 
    let insertName = `STATE_${refName}`;
    let insNum = 1;
    while (stateReferences.includes(insertName)) {
      insertName = `STATE_${refName}_${insNum++}`;
    }
    stateReferences.push(insertName);
  });
 
  return { spritesData, statesOrder, stateReferences };
};
 
const firstIndexOfMatch = <T>(arr: T[], pattern: T[]): number => {
  for (
    let i = 0;
    i < arr.length && i < arr.length - (pattern.length - 1);
    i++
  ) {
    let found = true;
    for (let j = 0; j < pattern.length; j++) {
      Iif (arr[i + j] !== pattern[j]) {
        found = false;
        break;
      }
    }
    Eif (found) {
      return i;
    }
  }
  return -1;
};
 
export default compileSprites;