All files / src/lib/compiler/scriptBuilder helpers.ts

57.29% Statements 110/192
35.43% Branches 45/127
67.74% Functions 21/31
49.69% Lines 81/163

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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 4299x 9x         9x 9x                     9x                 9x                       9x                     9x 298x     9x 49x     9x         18x     18x 35x 32x         9x       74x 27x     47x     74x     9x 95x     9x     87x     9x 162x 2x   160x 52x   108x     9x                   9x 52x     9x 5x   5x 1x 4x 2x 2x 2x         9x           17x                                         9x                               9x                   9x 3x     3x     9x                         9x                                                                                                   9x     89x   33x   11x               4x                       3x   3x                           21x   13x   1x                             9x                                           9x 2x     9x 2x     9x 1x     9x 1x     9x       9x       9x                                                                           9x   9x       48x     9x       48x 6x   42x     9x            
import { DMG_PALETTE } from "consts";
import {
  isVariableLocal,
  isVariableTemp,
} from "shared/lib/entities/entitiesHelpers";
import { DistanceUnitType } from "shared/lib/entities/entitiesTypes";
import { decOct } from "shared/lib/helpers/8bit";
import {
  subpxShiftForUnits,
  pxShiftForUnits,
  subpxSnapMaskForUnits,
} from "shared/lib/helpers/subpixels";
import {
  Palette,
  ActorDirection,
  SpriteModeSetting,
} from "shared/lib/resources/types";
import { OperatorSymbol, FunctionSymbol } from "shared/lib/rpn/types";
import {
  shiftLeftScriptValueConst,
  maskScriptValueConst,
} from "shared/lib/scriptValue/helpers";
import {
  ValueOperatorType,
  ValueUnaryOperatorType,
  ScriptValue,
} from "shared/lib/scriptValue/types";
import SparkMD5 from "spark-md5";
import {
  ScriptBuilderRPNOperation,
  ScriptBuilderScene,
  ScriptBuilderEntity,
  ScriptBuilderOverlayWaitFlag,
  ScriptBuilderAxis,
  SFXPriority,
  ASMSFXPriority,
  ASMSpriteMode,
} from "./types";
 
export const rpnUnaryOperators: ScriptBuilderRPNOperation[] = [
  ".ABS",
  ".NOT",
  ".B_NOT",
  ".ISQRT",
  ".RND",
  ".NEG",
];
 
// - Helpers --------------
 
export const isObject = (value: unknown): value is Record<string, unknown> => {
  return typeof value === "object" && value !== null;
};
 
export const getActorIndex = (actorId: string, scene: ScriptBuilderScene) => {
  return (scene.actors || []).findIndex((a) => a.id === actorId) + 1;
};
 
export const getPalette = (
  palettes: Palette[],
  id: string,
  fallbackId: string,
): Palette => {
  Iif (id === "dmg") {
    return DMG_PALETTE as Palette;
  }
  return (
    palettes.find((p) => p.id === id) ||
    palettes.find((p) => p.id === fallbackId) ||
    (DMG_PALETTE as Palette)
  );
};
 
export const getVariableId = (
  variable: string,
  entity?: ScriptBuilderEntity,
) => {
  if (isVariableLocal(variable)) {
    Iif (entity) {
      return `${entity.id}__${variable}`;
    }
  } else Iif (isVariableTemp(variable)) {
    return variable;
  }
  return String(parseInt(variable || "0"));
};
 
export const toValidLabel = (label: string): string => {
  return label.replace(/[^A-Za-z0-9]/g, "_");
};
 
export const buildOverlayWaitCondition = (
  flags: ScriptBuilderOverlayWaitFlag[],
) => {
  return unionFlags(flags, ".UI_WAIT_NONE");
};
 
export const unionFlags = (flags: string[], defaultValue = "0") => {
  if (flags.length === 0) {
    return defaultValue;
  }
  if (flags.length === 1) {
    return flags[0];
  }
  return `^/(${flags.join(" | ")})/`;
};
 
export const andFlags = (flags: string[], defaultValue = "0") => {
  Iif (flags.length === 0) {
    return defaultValue;
  }
  Iif (flags.length === 1) {
    return flags[0];
  }
  return `^/(${flags.join(" & ")})/`;
};
 
export const toASMVar = (symbol: string) => {
  return symbol.toUpperCase().replace(/[^A-Z0-9]/g, "_");
};
 
export const toASMDir = (direction: string) => {
  Iif (direction === "left") {
    return ".DIR_LEFT";
  } else if (direction === "right") {
    return ".DIR_RIGHT";
  } else if (direction === "up") {
    return ".DIR_UP";
  } else if (direction === "down") {
    return ".DIR_DOWN";
  }
  return ".DIR_DOWN";
};
 
export const toASMMoveFlags = (
  moveType: string,
  useCollisions: boolean | Array<"walls" | "actors">,
  relative?: boolean,
  relativeUnits?: DistanceUnitType,
) => {
  return unionFlags(
    ([] as string[]).concat(
      useCollisions === true ? ".ACTOR_ATTR_CHECK_COLL" : [],
      Array.isArray(useCollisions) && useCollisions.includes("walls")
        ? ".ACTOR_ATTR_CHECK_COLL_WALLS"
        : [],
      Array.isArray(useCollisions) && useCollisions.includes("actors")
        ? ".ACTOR_ATTR_CHECK_COLL_ACTORS"
        : [],
      moveType === "horizontal" ? ".ACTOR_ATTR_H_FIRST" : [],
      moveType === "diagonal" ? ".ACTOR_ATTR_DIAGONAL" : [],
      relative && relativeUnits === "pixels"
        ? ".ACTOR_ATTR_RELATIVE_SNAP_PX"
        : [],
      relative && relativeUnits === "tiles"
        ? ".ACTOR_ATTR_RELATIVE_SNAP_TILE"
        : [],
    ),
  );
};
 
export const toASMCameraLock = (
  axis: ScriptBuilderAxis[],
  preventScroll: ActorDirection[],
) => {
  return unionFlags(
    ([] as string[]).concat(
      axis.includes("x") ? ".CAMERA_LOCK_X" : [],
      axis.includes("y") ? ".CAMERA_LOCK_Y" : [],
      preventScroll.includes("left") ? ".CAMERA_LOCK_X_MIN" : [],
      preventScroll.includes("right") ? ".CAMERA_LOCK_X_MAX" : [],
      preventScroll.includes("up") ? ".CAMERA_LOCK_Y_MIN" : [],
      preventScroll.includes("down") ? ".CAMERA_LOCK_Y_MAX" : [],
    ),
  );
};
 
export const toASMSoundPriority = (priority: SFXPriority): ASMSFXPriority => {
  Iif (priority === "low") {
    return ".SFX_PRIORITY_MINIMAL";
  }
  Iif (priority === "high") {
    return ".SFX_PRIORITY_HIGH";
  }
  return ".SFX_PRIORITY_NORMAL";
};
 
export const toASMSpriteMode = (mode: SpriteModeSetting): ASMSpriteMode => {
  Iif (mode === "8x8") {
    return ".MODE_8X8";
  }
  return ".MODE_8X16";
};
 
export const dirToAngle = (direction: string) => {
  if (direction === "left") {
    return 192;
  } else if (direction === "right") {
    return 64;
  } else if (direction === "up") {
    return 0;
  } else Iif (direction === "down") {
    return 128;
  }
  return 0;
};
 
export const toScriptOperator = (
  operator: OperatorSymbol,
): ScriptBuilderRPNOperation => {
  switch (operator) {
    case "+":
      return ".ADD";
    case "-":
      return ".SUB";
    case "/":
      return ".DIV";
    case "*":
      return ".MUL";
    case "%":
      return ".MOD";
    case "&":
      return ".B_AND";
    case "|":
      return ".B_OR";
    case "^":
      return ".B_XOR";
    case "~":
      return ".B_NOT";
    case "!":
      return ".NOT";
    case "==":
      return ".EQ";
    case "!=":
      return ".NE";
    case "<":
      return ".LT";
    case "<=":
      return ".LTE";
    case ">":
      return ".GT";
    case ">=":
      return ".GTE";
    case "&&":
      return ".AND";
    case "||":
      return ".OR";
    case "<<":
      return ".SHL";
    case ">>":
      return ".SHR";
    case "neg":
      return ".NEG";
  }
  assertUnreachable(operator);
};
 
export const valueFunctionToScriptOperator = (
  operator: ValueOperatorType | ValueUnaryOperatorType,
): ScriptBuilderRPNOperation => {
  switch (operator) {
    case "add":
      return ".ADD";
    case "sub":
      return ".SUB";
    case "div":
      return ".DIV";
    case "mul":
      return ".MUL";
    case "mod":
      return ".MOD";
    case "eq":
      return ".EQ";
    case "ne":
      return ".NE";
    case "lt":
      return ".LT";
    case "lte":
      return ".LTE";
    case "gt":
      return ".GT";
    case "gte":
      return ".GTE";
    case "min":
      return ".MIN";
    case "max":
      return ".MAX";
    case "and":
      return ".AND";
    case "or":
      return ".OR";
    case "abs":
      return ".ABS";
    case "atan2":
      return ".ATAN2";
    case "isqrt":
      return ".ISQRT";
    case "not":
      return ".NOT";
    case "shl":
      return ".SHL";
    case "shr":
      return ".SHR";
    case "bAND":
      return ".B_AND";
    case "bOR":
      return ".B_OR";
    case "bXOR":
      return ".B_XOR";
    case "bNOT":
      return ".B_NOT";
    case "rnd":
      return ".RND";
    case "neg":
      return ".NEG";
  }
  assertUnreachable(operator);
};
 
export const funToScriptOperator = (
  fun: FunctionSymbol,
): ScriptBuilderRPNOperation => {
  switch (fun) {
    case "min":
      return ".MIN";
    case "max":
      return ".MAX";
    case "abs":
      return ".ABS";
    case "atan2":
      return ".ATAN2";
    case "isqrt":
      return ".ISQRT";
    case "rnd":
      return ".RND";
    case "neg":
      return ".SUB";
  }
  assertUnreachable(fun);
};
 
export const textCodeSetSpeed = (speed: number): string => {
  return `\\001\\${decOct(speed + 1)}`;
};
 
export const textCodeSetFont = (fontIndex: number): string => {
  return `\\002\\${decOct(fontIndex + 1)}`;
};
 
export const textCodeGoto = (x: number, y: number): string => {
  return `\\003\\${decOct(x)}\\${decOct(y)}`;
};
 
export const textCodeGotoRel = (x: number, y: number): string => {
  return `\\004\\${decOct(x)}\\${decOct(y)}`;
};
 
export const textCodeInput = (mask: number): string => {
  return `\\006\\${decOct(mask)}`;
};
 
export const assertUnreachable = (_x: never): never => {
  throw new Error("Didn't expect to get here");
};
 
export const toProjectileHash = ({
  spriteSheetId,
  spriteStateId,
  speed,
  animSpeed,
  loopAnim,
  lifeTime,
  initialOffset,
  destroyOnHit,
  collisionGroup,
  collisionMask,
}: {
  spriteSheetId: string;
  spriteStateId: string;
  speed: number;
  animSpeed: number;
  loopAnim: boolean;
  lifeTime: number;
  initialOffset: number;
  destroyOnHit: boolean;
  collisionGroup: string;
  collisionMask: string[];
}) =>
  SparkMD5.hash(
    JSON.stringify({
      spriteSheetId,
      spriteStateId,
      speed,
      animSpeed,
      loopAnim,
      lifeTime,
      initialOffset,
      destroyOnHit,
      collisionGroup,
      collisionMask: [...collisionMask].sort(),
    }),
  );
 
export const fadeSpeeds = [0x0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f];
 
export const scriptValueToSubpixels = (
  value: ScriptValue,
  units: DistanceUnitType,
) => {
  return shiftLeftScriptValueConst(value, subpxShiftForUnits(units));
};
 
export const scriptValueToPixels = (
  value: ScriptValue,
  units: DistanceUnitType,
) => {
  if (units === "pixels") {
    return value;
  }
  return shiftLeftScriptValueConst(value, pxShiftForUnits(units));
};
 
export const snapScriptValueToUnits = (
  value: ScriptValue,
  units: DistanceUnitType,
) => {
  return maskScriptValueConst(value, subpxSnapMaskForUnits(units));
};