Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

4.9 KB
Raw Blame
// interpolate: map a number through keyframes (spec: "interpolate maps a number through keyframes").
import type { EasingFn } from "./easing";

export type ExtrapolateMode = "extend" | "clamp" | "identity" | "wrap";

export interface InterpolateOptions {
  /** the curve between keyframes: one for all, or one a segment */
  easing?: EasingFn | EasingFn[];
  /** below the first keyframe: extend the line (default), clamp to it, identity (the input itself) or wrap */
  extrapolateLeft?: ExtrapolateMode;
  /** past the last keyframe: extend (default), clamp, identity or wrap */
  extrapolateRight?: ExtrapolateMode;
}

const identityEase: EasingFn = (p) => p;

/** the keyframes as written, so the call can be found in the source */
const list = (xs: readonly unknown[]) => `[${xs.map((x) => (typeof x === "string" ? JSON.stringify(x) : String(x))).join(", ")}]`;
// a NaN keyframe is almost always a value that isn't there yet: a prop or field left out, or arithmetic on one
const HOW = ": a keyframe came from a missing prop or field (undefined), or arithmetic on one; give it a number";

function checkRanges(input: readonly number[], output: readonly number[]): void {
  if (!Array.isArray(input) || !Array.isArray(output)) {
    throw new TypeError("interpolate: the input and output keyframes must be arrays");
  }
  if (input.length !== output.length) {
    throw new RangeError(
      `interpolate: input has ${input.length} keyframes but output has ${output.length}; they must match`,
    );
  }
  if (input.length < 1) throw new RangeError("interpolate: at least one keyframe is needed");
  for (let i = 0; i < input.length; i++) {
    if (typeof input[i] !== "number" || Number.isNaN(input[i])) {
      throw new TypeError(`interpolate: input[${i}] is not a number (${input[i]}) in interpolate(…, ${list(input)}, ${list(output)})${HOW}`);
    }
    if (typeof output[i] !== "number" || Number.isNaN(output[i])) {
      throw new TypeError(`interpolate: output[${i}] is not a number (${output[i]}) in interpolate(…, ${list(input)}, ${list(output)})${HOW}`);
    }
  }
  for (let i = 0; i + 1 < input.length; i++) {
    if (!(input[i + 1] > input[i])) {
      throw new RangeError(
        `interpolate: input must strictly increase, but input[${i}] = ${input[i]} is followed by input[${i + 1}] = ${input[i + 1]}`,
      );
    }
  }
}

function easeFor(easing: InterpolateOptions["easing"], segment: number, segments: number): EasingFn {
  if (easing === undefined) return identityEase;
  if (typeof easing === "function") return easing;
  if (Array.isArray(easing)) {
    if (easing.length !== segments) {
      throw new RangeError(
        `interpolate: an easing array needs one function per segment (${segments}), got ${easing.length}`,
      );
    }
    return easing[segment];
  }
  throw new TypeError("interpolate: easing must be a function or an array of functions");
}

function checkMode(mode: string, side: string): ExtrapolateMode {
  if (mode === "extend" || mode === "clamp" || mode === "identity" || mode === "wrap") return mode;
  throw new RangeError(`interpolate: ${side} must be extend, clamp, identity or wrap, got "${mode}"`);
}

/** `x` mapped from the `input` range onto the `output` range, piece by piece: `input` rises, and the two have the same
 * length. `options.easing` shapes each piece; `extrapolateLeft` and `extrapolateRight` say what happens outside the
 * range (`extend`, the default, carries on; `clamp` holds the end value; `identity` returns `x`; `wrap` repeats). */
export function interpolate(
  x: number,
  input: readonly number[],
  output: readonly number[],
  options: InterpolateOptions = {},
): number {
  if (typeof x !== "number" || !Number.isFinite(x)) {
    throw new RangeError(`interpolate: x must be a finite number, got ${x}`);
  }
  checkRanges(input, output);
  const segments = input.length - 1;
  // validate the easing option up front so a wrong-length array fails whatever x is
  if (Array.isArray(options.easing)) easeFor(options.easing, 0, segments);
  if (segments === 0) return output[0];

  const left = checkMode(options.extrapolateLeft ?? "extend", "extrapolateLeft");
  const right = checkMode(options.extrapolateRight ?? "extend", "extrapolateRight");
  const first = input[0];
  const last = input[segments];

  let v = x;
  if (v < first || v > last) {
    const mode = v < first ? left : right;
    if (mode === "clamp") return v < first ? output[0] : output[segments];
    if (mode === "identity") return v;
    if (mode === "wrap") {
      const width = last - first;
      v = first + ((((v - first) % width) + width) % width);
    }
    // extend: fall through with v outside the range; the end segment's line is continued below
  }

  // pick the segment: the end segments also cover the extension beyond them
  let i = 0;
  while (i < segments - 1 && v > input[i + 1]) i++;
  const span = input[i + 1] - input[i];
  const p = (v - input[i]) / span;
  const eased = easeFor(options.easing, i, segments)(p);
  return output[i] + eased * (output[i + 1] - output[i]);
}