All files / src/lib/fonts fontData.ts

84.21% Statements 80/95
66.66% Branches 26/39
75% Functions 9/12
82.95% Lines 73/88

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 18659x 59x 59x             59x                                     59x 59x 59x 59x 59x 59x     59x 59x   59x     26x 26x 26x 26x 26x 26x 26x   26x 26x 26x 26x 26x 21x 21x 21x   21x             26x 348160x             26x 340x 5440x             5440x   5440x 285x     5440x               26x 26x 26x 5440x 5440x 4957x   5440x   26x 26x     26x   5440x   26x                                               4957x 26x   26x                     59x 348160x 7008x   341152x 69578x   271574x     271574x     271574x     59x 26x 4957x 4957x 26x 26x 26x 4957x 4957x   26x     59x   5440x    
import Path from "path";
import { readJson } from "fs-extra";
import {
  ImageIndexFunction,
  IndexedImage,
  indexedImageTo2bppTileData,
  sliceIndexedImage,
  trimIndexedImageHorizontal,
} from "shared/lib/tiles/indexedImage";
import { readFileToIndexedImage } from "lib/tiles/readFileToTiles";
 
export interface CompiledFontData {
  name: string;
  table: number[];
  widths: number[];
  data: Uint8Array;
  isVariableWidth: boolean;
  is1Bit: boolean;
  mapping: Record<string, number>;
}
 
interface CharacterData {
  width: number;
  data: IndexedImage;
}
 
type CharLookup = Record<string, CharacterData>;
 
enum Color {
  White = 0,
  Light = 1,
  Mid = 2,
  Dark = 3,
  Transparent = 255,
}
 
const TILE_SIZE = 8;
const FIRST_CHAR = 32;
 
export const readFileToFontData = async (
  filename: string,
): Promise<CompiledFontData> => {
  const name = Path.basename(filename);
  const image = await readFileToIndexedImage(filename, fontDataIndexFn);
  const tileWidth = Math.floor(image.width / TILE_SIZE);
  const tileHeight = Math.floor(image.height / TILE_SIZE);
  const chars: CharacterData[] = [];
  let is1Bit = true;
  let isVariableWidth = false;
 
  const metadataFilename = filename.replace(/\.png$/i, ".json");
  let mapping: Record<string, number> = {};
  let tableMapping: Record<string, number> = {};
  try {
    const metadataFile = await readJson(metadataFilename);
    Eif (typeof metadataFile === "object") {
      Eif (metadataFile.mapping && typeof metadataFile.mapping === "object") {
        mapping = metadataFile.mapping;
      }
      Iif (metadataFile.table && typeof metadataFile.table === "object") {
        tableMapping = metadataFile.table;
      }
    }
  } catch {}
 
  // Determine if font is only using white & black pixels
  for (let i = 0; i < image.data.length; i++) {
    Iif (image.data[i] === Color.Light || image.data[i] === Color.Mid) {
      is1Bit = false;
      break;
    }
  }
 
  // Build tile list
  for (let ty = 0; ty < tileHeight; ty++) {
    for (let tx = 0; tx < tileWidth; tx++) {
      const tile = sliceIndexedImage(
        image,
        tx * TILE_SIZE,
        ty * TILE_SIZE,
        TILE_SIZE,
        TILE_SIZE,
      );
      const trimmedTile = trimIndexedImageHorizontal(tile, Color.Transparent);
 
      if (trimmedTile.data.width < TILE_SIZE) {
        isVariableWidth = true;
      }
 
      chars.push({
        width: trimmedTile.data.width,
        data: sliceIndexedImage(trimmedTile.data, 0, 0, TILE_SIZE, TILE_SIZE),
      });
    }
  }
 
  // Build unique tiles list
  const uniqueTilesLookup: CharLookup = {};
  const charKeys: string[] = [];
  for (const char of chars) {
    const key = hashChar(char.data, char.width);
    if (!uniqueTilesLookup[key]) {
      uniqueTilesLookup[key] = char;
    }
    charKeys.push(key);
  }
  const uniqueTileKeys = Object.keys(uniqueTilesLookup);
  const uniqueTiles = Object.values(uniqueTilesLookup);
 
  // Construct output data
  let table = (
    tileHeight < 16 ? (Array.from(Array(FIRST_CHAR)) as number[]).fill(0) : []
  ).concat(charKeys.map((key) => uniqueTileKeys.indexOf(key)));
 
  Iif (Object.keys(tableMapping).length) {
    //get highest mapped char
    const mappingKeys = Object.keys(tableMapping)
      .map((mappingKey) => {
        return mappingKey.charCodeAt(0);
      })
      .filter((charcode) => {
        return charcode < 256;
      });
    const maxValue = Math.max(...mappingKeys) + 1;
    //adjust the table size to fit tableMapping
    if (table.length < maxValue) {
      table = table.concat(
        (Array.from(Array(maxValue - table.length)) as number[]).fill(0),
      );
    }
    //modify the table with the tableMapping
    Object.entries(tableMapping).forEach(([key, value]) => {
      const tableIndex = key.charCodeAt(0); //get ascii value of mapped char
      if (tableIndex < 256) {
        table[tableIndex] = value; //assign mapped value to table
      }
    });
  }
  const widths = uniqueTiles.map((tile) => tile.width);
  const data = charLookupToTileData(uniqueTilesLookup);
 
  return {
    name,
    table,
    widths,
    data,
    isVariableWidth,
    is1Bit,
    mapping,
  };
};
 
const fontDataIndexFn: ImageIndexFunction = (r, g, b, _a) => {
  if (g > 249 || (r > 249 && b > 249)) {
    return Color.Transparent;
  }
  if (g < 65) {
    return Color.Dark;
  }
  Iif (g < 130) {
    return Color.Mid;
  }
  Iif (g < 205) {
    return Color.Light;
  }
  return Color.White;
};
 
const charLookupToTileData = (lookup: CharLookup): Uint8Array => {
  const chars = Object.values(lookup);
  const charsData = chars.map((char) => indexedImageTo2bppTileData(char.data));
  const size = charsData.reduce((memo, char) => memo + char.length, 0);
  const output = new Uint8Array(size);
  let index = 0;
  for (const charData of charsData) {
    output.set(charData, index);
    index += charData.length;
  }
  return output;
};
 
const hashChar = (char: IndexedImage, width: number): string => {
  // Will do for now...
  return `${width}_${JSON.stringify(char.data)}`;
};