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.

2.6 KB
Raw Blame
// A person's input as raea's FrameInput, in composition px: keys held, the primary pointer and every finger down.
// The stage is the composition scaled uniformly into the screen, so each point is mapped back through its box.
import type { FrameInput } from "raea";

/** window.addEventListener typed by the event's name (bun's globals type the bare addEventListener loosely) */
function on<K extends keyof WindowEventMap>(type: K, f: (e: WindowEventMap[K]) => void) {
  window.addEventListener(type, f);
}

export class Input {
  private keys = new Set<string>();
  private pointer?: { x: number; y: number; down: boolean };
  private touches = new Map<number, { x: number; y: number }>();
  /** set on the first touch, click or key: networks keep sound off until then */
  touched = false;
  private firstTouch: (() => void)[] = [];

  constructor(private stage: HTMLElement, private size: () => { width: number; height: number }) {
    const at = (e: PointerEvent) => {
      const r = this.stage.getBoundingClientRect();
      const { width, height } = this.size();
      return { x: ((e.clientX - r.left) / r.width) * width, y: ((e.clientY - r.top) / r.height) * height };
    };
    const first = () => {
      if (this.touched) return;
      this.touched = true;
      for (const f of this.firstTouch) f();
    };
    on("pointerdown", (e) => {
      first();
      const p = at(e);
      this.pointer = { ...p, down: true };
      this.touches.set(e.pointerId, p);
    });
    on("pointermove", (e) => {
      const p = at(e);
      if (e.isPrimary) this.pointer = { ...p, down: this.pointer?.down ?? false };
      if (this.touches.has(e.pointerId)) this.touches.set(e.pointerId, p);
    });
    const up = (e: PointerEvent) => {
      if (e.isPrimary && this.pointer) this.pointer = { ...this.pointer, down: false };
      this.touches.delete(e.pointerId);
    };
    on("pointerup", up);
    on("pointercancel", up);
    on("keydown", (e) => {
      first();
      this.keys.add(e.key);
    });
    on("keyup", (e) => this.keys.delete(e.key));
    on("blur", () => this.keys.clear());
  }

  /** Runs `f` on the first touch, click or key */
  onFirstTouch(f: () => void) {
    if (this.touched) f();
    else this.firstTouch.push(f);
  }

  /** This frame's input, marked live (a person is playing: raea/games' fold reads it so) */
  now(): FrameInput & { live: true } {
    return {
      keys: [...this.keys],
      ...(this.pointer ? { pointer: { ...this.pointer } } : {}),
      ...(this.touches.size ? { touches: [...this.touches].map(([id, p]) => ({ id, ...p })) } : {}),
      live: true,
    };
  }
}