This commit is contained in:
2026-10-15 18:19:09 +02:00
parent 919d3b25dd
commit 3617098951
25 changed files with 3390 additions and 102 deletions
+89
View File
@@ -0,0 +1,89 @@
/**
* animation.ts — frame sequencing for animated sprites.
*
* Owns: a clip (list of frames + fps + loop mode) and the elapsed time
* inside it. Does not own: what a "walk" is, which clip should be playing,
* or anything about drawing.
*
* The output — `frame` — is a CanvasImageSource, which plugs directly
* into the renderer's `SpriteDraw.image` field with no conversion.
*/
export interface AnimationClip {
/** Ordered frames. Any CanvasImageSource: HTMLImageElement, ImageBitmap, canvas, … */
frames: CanvasImageSource[];
/** Playback rate in frames per second. */
fps: number;
/** Default true. When false, holds the last frame after one pass. */
loop?: boolean;
}
export class Animator {
private clip: AnimationClip | null = null;
private elapsed = 0;
private finished = false;
private active = false;
/** Begin playing a clip. If it's already the current clip, this is a no-op. */
play(clip: AnimationClip | null): void {
if (clip === this.clip) return;
this.clip = clip;
this.elapsed = 0;
this.finished = false;
this.active = clip !== null && clip.frames.length > 0;
}
/** Force a restart of the current clip. */
restart(): void {
if (!this.clip) return;
this.elapsed = 0;
this.finished = false;
this.active = this.clip.frames.length > 0;
}
stop(): void {
this.active = false;
}
/** Advance by `dt` seconds. */
update(dt: number): void {
if (!this.active || !this.clip || this.finished) return;
this.elapsed += dt;
if (!this.clip.loop) {
const duration = this.clip.frames.length / this.clip.fps;
if (this.elapsed >= duration) {
this.elapsed = duration;
this.finished = true;
}
}
}
/** Current frame image, or null if no clip is playing. */
get frame(): CanvasImageSource | null {
if (!this.clip || !this.clip.frames.length) return null;
return this.clip.frames[this.frameIndex];
}
/** Current frame index within the clip. */
get frameIndex(): number {
if (!this.clip || !this.clip.frames.length) return 0;
const raw = Math.floor(this.elapsed * this.clip.fps);
return this.clip.loop ? raw % this.clip.frames.length : Math.min(raw, this.clip.frames.length - 1);
}
/** True when a non-looping clip has reached its final frame. */
get done(): boolean {
return this.finished;
}
/** Time elapsed in the current clip, seconds. */
get time(): number {
return this.elapsed;
}
get currentClip(): AnimationClip | null {
return this.clip;
}
}
+34
View File
@@ -0,0 +1,34 @@
export class ImageCache {
private images = new Map<string, HTMLImageElement>();
async load(urls: string[]): Promise<void> {
const results = await Promise.all(
urls.map(
url =>
new Promise<[string, HTMLImageElement]>((resolve, reject) => {
const img = new Image();
img.onload = () => resolve([url, img]);
img.onerror = () => reject(new Error(`Could not load "${url}"`));
img.src = url;
}),
),
);
this.images = new Map(results);
}
get(url: string): HTMLImageElement | undefined {
return this.images.get(url);
}
largestSize(urls: string[]): { w: number; h: number } {
let w = 0;
let h = 0;
for (const url of urls) {
const img = this.images.get(url);
if (!img) continue;
w = Math.max(w, img.naturalWidth);
h = Math.max(h, img.naturalHeight);
}
return { w, h };
}
}
+300
View File
@@ -0,0 +1,300 @@
export interface Vec2 {
x: number;
y: number;
}
export interface RigidBodyConfig {
/** Top-left corner position, px. */
position: Vec2;
/** Width in px. */
width: number;
/** Height in px. */
height: number;
/** Default 1. Use 0 for a static body. */
mass?: number;
/** Bounciness, 0–1. 0 = no bounce, 1 = perfectly elastic. Default 0.4. */
restitution?: number;
/** Coulomb friction coefficient. Default 0.3. */
friction?: number;
/** Air resistance as fraction of velocity lost per second. Default 0. */
linearDamping?: number;
}
export class RigidBody {
/* --- kinematics --- */
position: Vec2;
velocity: Vec2;
/** Force accumulator. Cleared at the end of every substep. */
force: Vec2 = { x: 0, y: 0 };
/* --- shape --- */
width: number;
height: number;
/* --- material --- */
mass: number;
inverseMass: number;
restitution: number;
friction: number;
linearDamping: number;
/* --- contacts (per-substep; reset at the start of each substep) --- */
onGround = false;
onCeiling = false;
onLeftWall = false;
onRightWall = false;
constructor(config: RigidBodyConfig) {
this.position = { ...config.position };
this.velocity = { x: 0, y: 0 };
this.width = config.width;
this.height = config.height;
this.mass = config.mass ?? 1;
this.inverseMass = this.mass > 0 ? 1 / this.mass : 0;
this.restitution = config.restitution ?? 0.4;
this.friction = config.friction ?? 0.3;
this.linearDamping = config.linearDamping ?? 0;
}
/* --- geometry --- */
get left(): number {
return this.position.x;
}
get right(): number {
return this.position.x + this.width;
}
get top(): number {
return this.position.y;
}
get bottom(): number {
return this.position.y + this.height;
}
get centerX(): number {
return this.position.x + this.width / 2;
}
get centerY(): number {
return this.position.y + this.height / 2;
}
/* --- force application --- */
/**
* Add a continuous force (N). Accumulates until the next substep, when
* it's converted to acceleration via `a = F/m` and then cleared.
* Apply every frame for a sustained push (wind, thrust).
*/
applyForce(f: Vec2): void {
this.force.x += f.x;
this.force.y += f.y;
}
/**
* Add an instantaneous velocity change (kg·px/s). Applied immediately.
* Use for one-shot pushes: throws, hits, explosions.
*/
applyImpulse(i: Vec2): void {
this.velocity.x += i.x * this.inverseMass;
this.velocity.y += i.y * this.inverseMass;
}
/** Overwrite velocity directly. No mass scaling. */
setVelocity(v: Vec2): void {
this.velocity.x = v.x;
this.velocity.y = v.y;
}
/** Clear the force accumulator. Called by the world after each substep. */
clearForces(): void {
this.force.x = 0;
this.force.y = 0;
}
}
/* ------------------------------------------------------------------ */
/* World */
/* ------------------------------------------------------------------ */
export interface PhysicsSolverConfig {
/** Playfield width, px. */
width: number;
/** Playfield height, px. */
height: number;
/** Thickness of the floor strip at the bottom, px. Default 0. */
floorHeight?: number;
/** Constant acceleration applied to every body. Default {0, 1500}. */
gravity?: Vec2;
/** Physics tick length in seconds. Default 1/120. */
fixedDt?: number;
/** Max substeps per `step()` call. Default 8. */
maxSubsteps?: number;
/** Vertical speed below which a ground contact is treated as resting, px/s. Default 40. */
restVelocityThreshold?: number;
}
export class PhysicsSolver {
gravity: Vec2;
width: number;
height: number;
rbArray: RigidBody[] = [];
readonly fixedDt: number;
readonly maxSubsteps: number;
readonly restVelocityThreshold: number;
private dtAccumulator = 0;
constructor(config: PhysicsSolverConfig) {
this.gravity = config.gravity ?? { x: 0, y: 1500 };
this.width = config.width;
this.height = config.height;
this.fixedDt = config.fixedDt ?? 1 / 120;
this.maxSubsteps = config.maxSubsteps ?? 8;
this.restVelocityThreshold = config.restVelocityThreshold ?? 40;
}
resize(width: number, height: number, floorHeight?: number): void {
this.width = width;
this.height = height;
for (const b of this.rbArray) {
b.position.x = clamp(b.position.x, 0, this.width - b.width);
}
}
addBody(rb: RigidBody): RigidBody {
this.rbArray.push(rb);
return rb;
}
removeBody(rb: RigidBody): void {
const i = this.rbArray.indexOf(rb);
if (i >= 0) this.rbArray.splice(i, 1);
}
/* -------------------------------------------------------------- */
/**
* Advance the simulation by `dt` seconds of real time.
* Consumes from an accumulator and runs as many fixed substeps as fit.
*/
step(dt: number): void {
this.dtAccumulator += dt;
let substeps = 0;
while (this.dtAccumulator >= this.fixedDt && substeps < this.maxSubsteps) {
this.fixedStep(this.fixedDt);
this.dtAccumulator -= this.fixedDt;
substeps++;
}
// If we hit the cap, drop the backlog rather than spiral.
if (substeps >= this.maxSubsteps) this.dtAccumulator = 0;
}
/**
* Run exactly one fixed substep, ignoring the accumulator.
* For deterministic tests and headless simulation.
*/
stepOnce(): void {
this.fixedStep(this.fixedDt);
}
/* -------------------------------------------------------------- */
private fixedStep(dt: number): void {
for (const rb of this.rbArray) {
rb.onGround = false;
rb.onCeiling = false;
rb.onLeftWall = false;
rb.onRightWall = false;
this.integrate(rb, dt);
this.resolveWorldCollisions(rb, dt);
}
}
private integrate(rb: RigidBody, dt: number): void {
if (rb.inverseMass === 0) return;
// Gravity as a force: F = m·g
rb.force.x += this.gravity.x * rb.mass;
rb.force.y += this.gravity.y * rb.mass;
// F = m·a → a = F/m. Then v += a·dt.
rb.velocity.x += rb.force.x * rb.inverseMass * dt;
rb.velocity.y += rb.force.y * rb.inverseMass * dt;
// Linear damping: fraction of velocity lost per second.
if (rb.linearDamping > 0) {
const retain = Math.pow(1 - rb.linearDamping, dt);
rb.velocity.x *= retain;
rb.velocity.y *= retain;
}
// Integrate position from the *new* velocity (semi-implicit Euler).
rb.position.x += rb.velocity.x * dt;
rb.position.y += rb.velocity.y * dt;
rb.clearForces();
}
private resolveWorldCollisions(rb: RigidBody, dt: number): void {
if (rb.position.y > this.height - rb.height * 0.5) {
rb.position.y = this.height - rb.height * 0.5;
rb.onGround = true;
if (rb.velocity.y > 0) {
if (rb.velocity.y < this.restVelocityThreshold) {
// Too slow to bounce meaningfully — rest.
rb.velocity.y = 0;
} else {
rb.velocity.y = -rb.velocity.y * rb.restitution;
}
}
// Coulomb friction: decelerate by μ·g each second while touching.
if (rb.friction > 0 && Math.abs(rb.velocity.x) > 0) {
const pressureForce = rb.friction * Math.abs(this.gravity.y);
const dv = pressureForce * dt;
if (Math.abs(rb.velocity.x) <= dv) {
rb.velocity.x = 0;
} else {
rb.velocity.x -= Math.sign(rb.velocity.x) * dv;
}
}
}
/* --- ceiling --- */
if (rb.top < 0) {
rb.position.y = 0;
rb.onCeiling = true;
if (rb.velocity.y < 0) {
rb.velocity.y = -rb.velocity.y * rb.restitution;
}
}
/* --- left wall --- */
if (rb.left < 0) {
rb.position.x = 0;
rb.onLeftWall = true;
if (rb.velocity.x < 0) {
rb.velocity.x = -rb.velocity.x * rb.restitution;
}
}
/* --- right wall --- */
if (rb.right > this.width) {
rb.position.x = this.width - rb.width;
rb.onRightWall = true;
if (rb.velocity.x > 0) {
rb.velocity.x = -rb.velocity.x * rb.restitution;
}
}
}
}
/* ------------------------------------------------------------------ */
export function clamp(v: number, lo: number, hi: number): number {
return Math.min(Math.max(v, lo), hi);
}
+423
View File
@@ -0,0 +1,423 @@
/**
* renderer.ts — standalone 2D canvas renderer.
*
* Knows nothing about what it's drawing. Takes a data description of a
* frame and paints it. Owns:
* - the canvas and its DPI scaling
* - a scratch canvas for reflection compositing
* - pixel-art crispness (imageSmoothingEnabled, integer rounding)
*
* Does not own:
* - the animation loop (caller calls `render()` per frame)
* - resize detection (caller calls `resize()` explicitly)
* - any game concept (states, needs, physics, interactions)
*
* All coordinates and sizes are in CSS pixels. DPI is handled internally.
*/
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
export type Anchor =
| "top-left"
| "top-center"
| "top-right"
| "center-left"
| "center"
| "center-right"
| "bottom-left"
| "bottom-center"
| "bottom-right";
export interface RendererConfig {
canvas: HTMLCanvasElement;
/** Disable image smoothing and round positions. Default true. */
pixelArt?: boolean;
/** Cap on devicePixelRatio. Prevents 4x canvases on exotic displays. Default 3. */
maxDpr?: number;
/** Fill colour applied after clear. Default null (transparent). */
backgroundColor?: string | null;
}
export interface SpriteDraw {
image: CanvasImageSource;
/** Anchor position in CSS px. What (x, y) refers to depends on `anchor`. */
x: number;
y: number;
/** Display size in CSS px. */
width: number;
height: number;
/** Default 'top-left'. */
anchor?: Anchor;
/** Flip horizontally. Default false. */
mirrored?: boolean;
/** Overall opacity 0–1. Default 1. */
alpha?: number;
/** Additional x scale applied about the anchor. 1 = normal. */
scaleX?: number;
/** Additional y scale applied about the anchor. 1 = normal. */
scaleY?: number;
}
export interface ShadowDraw {
/** Ellipse centre in CSS px. */
cx: number;
cy: number;
/** Ellipse radii in CSS px. */
rx: number;
ry: number;
color?: string;
alpha?: number;
}
export interface ReflectionDraw {
image: CanvasImageSource;
x: number;
y: number;
width: number;
height: number;
anchor?: Anchor;
mirrored?: boolean;
alpha?: number;
/** Fade toward the far edge, 0–1. 0 = no fade, 1 = fully faded. Default 0. */
fade?: number;
/** Colour wash applied via `source-atop`. */
tint?: string;
/** Which way the reflection fades. Default 'down'. */
fadeDirection?: "down" | "up";
}
export interface TextDraw {
content: string;
/** Text area in CSS px. */
x: number;
y: number;
width: number;
height: number;
/** Full CSS font string, e.g. "12px monospace". */
font?: string;
color?: string;
align?: "left" | "center" | "right";
/** Anchor for the text block within the rect. Default 'top'. */
baseline?: "top" | "middle" | "bottom";
/** Multiplier over font size. Default 1.2. */
lineHeight?: number;
/** Word-wrap to `width`. Default true. */
wrap?: boolean;
/** Typewriter reveal: characters 0..charsShown visible. Default Infinity. */
charsShown?: number;
}
/**
* A complete frame description. The renderer draws slots in a fixed order:
* shadow → reflection → sprite → bubble → text
* Any slot may be omitted.
*/
export interface RenderFrame {
shadow?: ShadowDraw;
reflection?: ReflectionDraw;
sprite?: SpriteDraw;
bubble?: SpriteDraw;
text?: TextDraw;
}
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
/**
* Offset from the anchor point to the image's top-left corner.
* Use this to compute hit-test rectangles that match what the renderer drew.
*/
export function anchorOffset(anchor: Anchor, w: number, h: number): { ox: number; oy: number } {
const hx = anchor.includes("left") ? 0 : anchor.includes("right") ? -w : -w / 2;
const hy = anchor.startsWith("top") ? 0 : anchor.startsWith("bottom") ? -h : -h / 2;
return { ox: hx, oy: hy };
}
function parseFontSize(font?: string): number {
if (!font) return 11;
const m = /(\d+(?:\.\d+)?)px/.exec(font);
return m ? parseFloat(m[1]) : 11;
}
function wrapText(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string[] {
const words = text.split(/\s+/).filter(Boolean);
const lines: string[] = [];
let line = "";
for (const word of words) {
const candidate = line ? `${line} ${word}` : word;
if (ctx.measureText(candidate).width <= maxWidth) {
line = candidate;
} else {
if (line) lines.push(line);
line = word;
}
}
if (line) lines.push(line);
return lines;
}
/* ------------------------------------------------------------------ */
/* Renderer */
/* ------------------------------------------------------------------ */
export class Renderer {
readonly canvas: HTMLCanvasElement;
/** Exposed for escape-hatch drawing. Reset on every resize. */
readonly ctx: CanvasRenderingContext2D;
private pixelArt: boolean;
private maxDpr: number;
private backgroundColor: string | null;
private dpr = 1;
private cssW = 0;
private cssH = 0;
// Scratch canvas for reflection compositing.
private reflCanvas: HTMLCanvasElement;
private reflCtx: CanvasRenderingContext2D;
private reflW = 0;
private reflH = 0;
constructor(cfg: RendererConfig) {
this.canvas = cfg.canvas;
const ctx = this.canvas.getContext("2d");
if (!ctx) throw new Error("Renderer: could not acquire 2D context");
this.ctx = ctx;
this.pixelArt = cfg.pixelArt ?? true;
this.maxDpr = cfg.maxDpr ?? 3;
this.backgroundColor = cfg.backgroundColor ?? null;
this.reflCanvas = document.createElement("canvas");
const rctx = this.reflCanvas.getContext("2d");
if (!rctx) throw new Error("Renderer: could not acquire reflection context");
this.reflCtx = rctx;
}
/* -------------------------------------------------------------- */
/* Sizing */
/* -------------------------------------------------------------- */
/**
* Sync the canvas backing store to its displayed size.
* Safe to call every frame — early-returns if nothing changed.
* Handles dpr changes when the window moves between displays.
*/
resize(cssW: number, cssH: number): void {
const w = Math.max(1, cssW);
const h = Math.max(1, cssH);
const newDpr = Math.min(typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1, this.maxDpr);
if (w === this.cssW && h === this.cssH && newDpr === this.dpr) return;
this.cssW = w;
this.cssH = h;
this.dpr = newDpr;
this.canvas.width = Math.round(w * newDpr);
this.canvas.height = Math.round(h * newDpr);
this.ctx.setTransform(newDpr, 0, 0, newDpr, 0, 0);
this.ctx.imageSmoothingEnabled = !this.pixelArt;
}
get size(): { width: number; height: number; dpr: number } {
return { width: this.cssW, height: this.cssH, dpr: this.dpr };
}
/* -------------------------------------------------------------- */
/* Frame */
/* -------------------------------------------------------------- */
render(frame: RenderFrame): void {
this.clear();
if (frame.shadow) this.drawShadow(frame.shadow);
if (frame.reflection) this.drawReflection(frame.reflection);
if (frame.sprite) this.drawSprite(frame.sprite);
if (frame.bubble) this.drawSprite(frame.bubble);
if (frame.text) this.drawText(frame.text);
}
/** Clear the canvas. Fills with `backgroundColor` if set. */
clear(): void {
this.ctx.clearRect(0, 0, this.cssW, this.cssH);
if (this.backgroundColor) {
this.ctx.fillStyle = this.backgroundColor;
this.ctx.fillRect(0, 0, this.cssW, this.cssH);
}
}
/* -------------------------------------------------------------- */
/* Primitives */
/* -------------------------------------------------------------- */
/** Draw a filled ellipse. Used for contact shadows. */
drawShadow(s: ShadowDraw): void {
const { ctx } = this;
const alpha = s.alpha ?? 0.3;
if (alpha <= 0) return;
ctx.save();
ctx.globalAlpha = alpha;
ctx.fillStyle = s.color ?? "#000";
ctx.beginPath();
ctx.ellipse(s.cx, s.cy, s.rx, s.ry, 0, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
/** Draw an image with anchor, mirroring, and about-anchor scaling. */
drawSprite(d: SpriteDraw): void {
const { ctx } = this;
const alpha = d.alpha ?? 1;
if (alpha <= 0) return;
const { ox, oy } = anchorOffset(d.anchor ?? "top-left", d.width, d.height);
const ax = this.round(d.x);
const ay = this.round(d.y);
const sx = (d.mirrored ? -1 : 1) * (d.scaleX ?? 1);
const sy = d.scaleY ?? 1;
ctx.save();
ctx.globalAlpha = alpha;
if (sx !== 1 || sy !== 1) {
// Scale about the anchor point so squash keeps the feet planted.
ctx.translate(ax, ay);
ctx.scale(sx, sy);
ctx.drawImage(d.image, ox, oy, d.width, d.height);
} else {
ctx.drawImage(d.image, ax + ox, ay + oy, d.width, d.height);
}
ctx.restore();
}
/**
* Draw a mirrored reflection. Composited via an offscreen scratch canvas
* so tint and fade can be applied as compound operations, then drawn to
* the main canvas in one pass.
*/
drawReflection(r: ReflectionDraw): void {
const alpha = r.alpha ?? 1;
if (alpha <= 0.01) return;
const pw = Math.max(1, Math.round(r.width * this.dpr));
const ph = Math.max(1, Math.round(r.height * this.dpr));
if (this.reflW !== pw || this.reflH !== ph) {
this.reflCanvas.width = pw;
this.reflCanvas.height = ph;
this.reflW = pw;
this.reflH = ph;
}
const rc = this.reflCtx;
rc.setTransform(1, 0, 0, 1, 0, 0);
rc.globalCompositeOperation = "source-over";
rc.globalAlpha = 1;
rc.clearRect(0, 0, pw, ph);
rc.imageSmoothingEnabled = !this.pixelArt;
// 1. Draw the image, flipped vertically (and horizontally if mirrored).
rc.save();
rc.translate(r.mirrored ? pw : 0, ph);
rc.scale(r.mirrored ? -1 : 1, -1);
rc.drawImage(r.image, 0, 0, pw, ph);
rc.restore();
// 2. Colour wash — only paints over pixels that exist.
if (r.tint) {
rc.globalCompositeOperation = "source-atop";
rc.fillStyle = r.tint;
rc.fillRect(0, 0, pw, ph);
}
// 3. Fade — erases pixels progressively toward the far edge.
const fade = Math.min(Math.max(r.fade ?? 0, 0), 1);
if (fade > 0) {
rc.globalCompositeOperation = "destination-out";
const grad = rc.createLinearGradient(0, 0, 0, ph);
const topA = r.fadeDirection === "up" ? fade : 0;
const botA = r.fadeDirection === "up" ? 0 : fade;
grad.addColorStop(0, `rgba(0,0,0,${topA})`);
grad.addColorStop(1, `rgba(0,0,0,${botA})`);
rc.fillStyle = grad;
rc.fillRect(0, 0, pw, ph);
}
rc.globalCompositeOperation = "source-over";
// 4. Composite to the main canvas at device-aligned position.
const { ox, oy } = anchorOffset(r.anchor ?? "top-left", r.width, r.height);
const x = this.round(r.x) + ox;
const y = this.round(r.y) + oy;
const ctx = this.ctx;
ctx.save();
ctx.globalAlpha = alpha;
ctx.drawImage(this.reflCanvas, x, y, r.width, r.height);
ctx.restore();
}
/**
* Draw text within a rect. Optional word-wrap and typewriter reveal.
* Reveal is cumulative across wrapped lines, so "hello world" with
* charsShown = 7 shows "hello w" with nothing on the second line.
*/
drawText(t: TextDraw): void {
if (!t.content) return;
const { ctx } = this;
const fontSize = parseFontSize(t.font);
const lineHeight = (t.lineHeight ?? 1.2) * fontSize;
const align = t.align ?? "center";
const baseline = t.baseline ?? "top";
const charsShown = t.charsShown ?? Infinity;
ctx.save();
ctx.font = t.font ?? "11px monospace";
ctx.fillStyle = t.color ?? "#000";
ctx.textBaseline = baseline === "middle" ? "middle" : baseline;
ctx.textAlign = align;
const lines = t.wrap === false ? [t.content] : wrapText(ctx, t.content, t.width);
// Horizontal anchor for textAlign.
const anchorX = align === "left" ? t.x : align === "right" ? t.x + t.width : t.x + t.width / 2;
// Vertical anchor for the text block.
const baseY = baseline === "top" ? t.y : baseline === "bottom" ? t.y + t.height : t.y + t.height / 2;
let cursor = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const visible = Math.max(0, Math.min(line.length, charsShown - cursor));
if (visible <= 0) break;
const yy =
baseline === "top"
? baseY + i * lineHeight
: baseline === "bottom"
? baseY - (lines.length - 1 - i) * lineHeight
: baseY - ((lines.length - 1) / 2 - i) * lineHeight;
ctx.fillText(line.slice(0, visible), anchorX, yy);
cursor += line.length;
if (visible < line.length) break;
}
ctx.restore();
}
/* -------------------------------------------------------------- */
private round(v: number): number {
return this.pixelArt ? Math.round(v) : v;
}
}
+182
View File
@@ -0,0 +1,182 @@
/**
* animation.ts — frame sequencing.
*
* An AnimationClip is a list of frames + fps + loop flag. An Animator plays
* one clip at a time and exposes the current frame. It knows nothing about
* what the frames contain.
*
* `staticSprite` and `animatedSprite` produce SpriteSlot-conforming objects.
* Both have the same interface — the renderer can't tell them apart.
*/
import type { SpriteFrame, SpriteSlot } from "./entity.ts";
export interface AnimationClip {
frames: CanvasImageSource[];
fps: number;
/** Default true. When false, holds the last frame after one pass. */
loop?: boolean;
}
/* ------------------------------------------------------------------ */
/* Animator */
/* ------------------------------------------------------------------ */
export class Animator {
private clip: AnimationClip | null = null;
private elapsed = 0;
private finished = false;
private playing = false;
/** Begin playing a clip. No-op if it's already the current clip. */
play(clip: AnimationClip | null): void {
if (clip === this.clip) return;
this.clip = clip;
this.elapsed = 0;
this.finished = false;
this.playing = clip !== null && clip.frames.length > 0;
}
/** Restart the current clip from frame zero. */
restart(): void {
if (this.clip === null) return;
this.elapsed = 0;
this.finished = false;
this.playing = this.clip.frames.length > 0;
}
/** Freeze the clip. Does not clear the current frame. */
stop(): void {
this.playing = false;
}
/**
* Advance by `dt` seconds.
* `timeScale` multiplies the rate. Use it to make playback speed
* proportional to something — ground speed, for example.
*/
update(dt: number, timeScale = 1): void {
const c = this.clip;
if (!this.playing || c === null || this.finished) return;
this.elapsed += dt * timeScale;
if (c.loop === false) {
const duration = c.frames.length / c.fps;
if (this.elapsed >= duration) {
this.elapsed = duration;
this.finished = true;
}
}
}
get frame(): CanvasImageSource | null {
const c = this.clip;
if (c === null || c.frames.length === 0) return null;
return c.frames[this.frameIndex] ?? null;
}
get frameIndex(): number {
const c = this.clip;
if (c === null || c.frames.length === 0) return 0;
const raw = Math.floor(this.elapsed * c.fps);
if (c.loop === false) return Math.min(raw, c.frames.length - 1);
return raw % c.frames.length;
}
get done(): boolean {
return this.finished;
}
get time(): number {
return this.elapsed;
}
get currentClip(): AnimationClip | null {
return this.clip;
}
}
/* ------------------------------------------------------------------ */
/* Image sizing */
/* ------------------------------------------------------------------ */
/**
* Best-effort size detection across CanvasImageSource variants.
* HTMLImageElement uses naturalWidth/naturalHeight; everything else
* (canvas, ImageBitmap, OffscreenCanvas, video) uses width/height.
*/
export function imageSize(image: CanvasImageSource): { width: number; height: number } {
const anyImg = image as unknown as Record<string, unknown>;
const nw = anyImg.naturalWidth;
const nh = anyImg.naturalHeight;
if (typeof nw === "number" && typeof nh === "number") {
return { width: nw, height: nh };
}
const w = anyImg.width;
const h = anyImg.height;
if (typeof w === "number" && typeof h === "number") {
return { width: w, height: h };
}
return { width: 0, height: 0 };
}
/* ------------------------------------------------------------------ */
/* Sprite factories */
/* ------------------------------------------------------------------ */
/** A sprite slot that always returns the same frame. */
export function staticSprite(image: CanvasImageSource, scale = 1): SpriteSlot {
const size = imageSize(image);
const frame: SpriteFrame = {
image,
width: size.width * scale,
height: size.height * scale,
};
return {
frame: () => frame,
};
}
export interface AnimatedSpriteOptions {
loop?: boolean;
scale?: number;
}
export interface AnimatedSprite extends SpriteSlot {
readonly animator: Animator;
}
/**
* A sprite slot backed by an Animator. The animator is exposed so callers
* can swap clips or restart playback without rebuilding the slot.
*/
export function animatedSprite(
frames: CanvasImageSource[],
fps: number,
opts: AnimatedSpriteOptions = {},
): AnimatedSprite {
const scale = opts.scale ?? 1;
const clip: AnimationClip = {
frames,
fps,
loop: opts.loop ?? true,
};
const animator = new Animator();
animator.play(clip);
const first = frames[0];
const size = first !== undefined ? imageSize(first) : { width: 0, height: 0 };
const displayWidth = size.width * scale;
const displayHeight = size.height * scale;
return {
animator,
update: (dt: number) => animator.update(dt),
frame: () => {
const img = animator.frame;
if (img === null) return null;
return { image: img, width: displayWidth, height: displayHeight };
},
};
}
+48
View File
@@ -0,0 +1,48 @@
/**
* camera.ts — optional view transform.
*
* Identity by default: `toScreen` returns the input unchanged, `toWorld`
* is the inverse. Every world coordinate in the renderer is passed through
* `camera.toScreen()` before drawing, so the default path is a no-op
* multiply.
*
* Follow/target logic is not implemented in v1. The class exists so a
* camera can be introduced without a renderer change.
*/
import type { Vec2 } from "./physics.ts";
export interface CameraConfig {
/** World coordinate of the viewport's top-left corner. Default {0,0}. */
position?: Vec2;
/** Scale factor. Default 1. */
zoom?: number;
}
export class Camera {
position: Vec2;
zoom: number;
constructor(cfg: CameraConfig = {}) {
this.position = { x: cfg.position?.x ?? 0, y: cfg.position?.y ?? 0 };
this.zoom = cfg.zoom ?? 1;
}
/** Identity when position is {0,0} and zoom is 1. */
toScreen(world: Vec2): Vec2 {
return {
x: (world.x - this.position.x) * this.zoom,
y: (world.y - this.position.y) * this.zoom,
};
}
toWorld(screen: Vec2): Vec2 {
return {
x: screen.x / this.zoom + this.position.x,
y: screen.y / this.zoom + this.position.y,
};
}
/** Reserved for follow logic. No-op in v1. */
update(_dt: number): void {}
}
+224
View File
@@ -0,0 +1,224 @@
/**
* entity.ts — the entity model.
*
* An entity is a plain object with a transform and optional slots. Slots are
* self-contained interfaces — presence of a slot means the entity participates
* in that subsystem. There is no inheritance and no subclassing; composition
* happens by populating slots.
*
* Hierarchy is one-level in practice: a parent moves its children, children
* never move their parent. No deep trees.
*/
import type { RigidBody, Vec2 } from "./physics.ts";
import type { Anchor } from "./renderer.ts";
/* ------------------------------------------------------------------ */
/* Transform */
/* ------------------------------------------------------------------ */
export interface Transform {
/** Position relative to the parent (or world if no parent). */
position: Vec2;
/** Anchor for the sprite, and rotation/scale pivot. */
anchor: Anchor;
scaleX: number;
scaleY: number;
opacity: number;
/** Radians. Currently unused by the renderer; reserved. */
rotation: number;
}
export const DEFAULT_TRANSFORM: Readonly<Transform> = {
position: { x: 0, y: 0 },
anchor: "top-left",
scaleX: 1,
scaleY: 1,
opacity: 1,
rotation: 0,
};
/* ------------------------------------------------------------------ */
/* Slots */
/* ------------------------------------------------------------------ */
export interface SpriteFrame {
image: CanvasImageSource;
width: number;
height: number;
}
export interface SpriteSlot {
/** Current frame, or null if nothing should be drawn. */
frame(): SpriteFrame | null;
/** Optional per-frame update for animated sprites. */
update?(dt: number): void;
}
export interface BodySlot {
body: RigidBody;
/**
* If true (default), the body's position is copied into the entity's
* transform every frame by the physics system.
*/
syncTransform?: boolean;
}
export interface ShadowSlot {
/** Horizontal radius as a fraction of sprite width. Default 0.4. */
rx?: number;
/** Vertical radius as a fraction of sprite height. Default 0.08. */
ry?: number;
color?: string;
alpha?: number;
/** Vertical squash per 100px of height. Default 0.5. */
shrinkByHeight?: number;
/** Fade per 100px of height. Default 0.85. */
fadeByHeight?: number;
/** Height at which the shadow disappears entirely. Default 200. */
maxHeight?: number;
}
export interface ReflectionSlot {
opacity?: number;
fade?: number;
/** Fade per 100px of height. */
fadeByHeight?: number;
tint?: string;
}
export interface BubbleTextConfig {
content: string;
font?: string;
color?: string;
align?: "left" | "center" | "right";
padding?: { top: number; right: number; bottom: number; left: number };
lineHeight?: number;
wrap?: boolean;
/** Typewriter reveal, 0..content.length. Omit for full text. */
charsShown?: number;
}
export interface BubbleSlot {
image: CanvasImageSource;
width: number;
height: number;
/** Offset from sprite top-center, in px. Default 0. */
anchorX?: number;
/** Positive = above the head. Default 4. */
anchorY?: number;
text?: BubbleTextConfig;
}
export interface CustomSlot {
draw?: (ctx: CanvasRenderingContext2D, entity: Entity) => void;
update?: (entity: Entity, dt: number) => void;
}
/* ------------------------------------------------------------------ */
/* Entity */
/* ------------------------------------------------------------------ */
export type SlotKey = "sprite" | "body" | "shadow" | "reflection" | "bubble" | "custom";
export interface Entity {
readonly id: string;
parent: Entity | null;
readonly children: Entity[];
visible: boolean;
destroyed: boolean;
readonly transform: Transform;
sprite?: SpriteSlot;
body?: BodySlot;
shadow?: ShadowSlot;
reflection?: ReflectionSlot;
bubble?: BubbleSlot;
custom?: CustomSlot;
/** Arbitrary tags for filtering: `world.entitiesWith(...)` doesn't cover this. */
readonly tags: Set<string>;
/** Arbitrary user data. Feature systems (needs, chatter) store state here. */
readonly data: Record<string, unknown>;
}
/* ------------------------------------------------------------------ */
/* Factory */
/* ------------------------------------------------------------------ */
export interface EntityOptions {
id?: string;
parent?: Entity;
visible?: boolean;
transform?: Partial<Transform>;
sprite?: SpriteSlot;
body?: BodySlot;
shadow?: ShadowSlot;
reflection?: ReflectionSlot;
bubble?: BubbleSlot;
custom?: CustomSlot;
tags?: string[];
data?: Record<string, unknown>;
}
let nextEntityId = 0;
export function createEntity(opts: EntityOptions = {}): Entity {
const entity: Entity = {
id: opts.id ?? `entity-${nextEntityId++}`,
parent: opts.parent ?? null,
children: [],
visible: opts.visible ?? true,
destroyed: false,
transform: {
position: opts.transform?.position ?? { x: 0, y: 0 },
anchor: opts.transform?.anchor ?? DEFAULT_TRANSFORM.anchor,
scaleX: opts.transform?.scaleX ?? DEFAULT_TRANSFORM.scaleX,
scaleY: opts.transform?.scaleY ?? DEFAULT_TRANSFORM.scaleY,
opacity: opts.transform?.opacity ?? DEFAULT_TRANSFORM.opacity,
rotation: opts.transform?.rotation ?? DEFAULT_TRANSFORM.rotation,
},
tags: new Set(opts.tags ?? []),
data: opts.data ?? {},
};
if (opts.sprite !== undefined) entity.sprite = opts.sprite;
if (opts.body !== undefined) entity.body = opts.body;
if (opts.shadow !== undefined) entity.shadow = opts.shadow;
if (opts.reflection !== undefined) entity.reflection = opts.reflection;
if (opts.bubble !== undefined) entity.bubble = opts.bubble;
if (opts.custom !== undefined) entity.custom = opts.custom;
if (opts.parent !== undefined) opts.parent.children.push(entity);
return entity;
}
/* ------------------------------------------------------------------ */
/* World transform */
/* ------------------------------------------------------------------ */
/**
* Compose the transform of an entity with its ancestors. Recomputed on
* demand. For the shallow trees this library encourages, caching isn't
* worth the invalidation bookkeeping.
*/
export function getWorldTransform(entity: Entity): Transform {
if (entity.parent === null) return entity.transform;
const parent = getWorldTransform(entity.parent);
return {
position: {
x: parent.position.x + entity.transform.position.x,
y: parent.position.y + entity.transform.position.y,
},
anchor: entity.transform.anchor,
scaleX: parent.scaleX * entity.transform.scaleX,
scaleY: parent.scaleY * entity.transform.scaleY,
opacity: parent.opacity * entity.transform.opacity,
rotation: parent.rotation + entity.transform.rotation,
};
}
+41
View File
@@ -0,0 +1,41 @@
export { anchorOffset, Canvas2DRenderer } from "./renderer.ts";
export type {
Anchor,
ReflectionDraw,
Renderer,
RendererConfig,
RendererSize,
ShadowDraw,
SpriteDraw,
TextDraw,
} from "./renderer.ts";
export { PhysicsSolver, RigidBody } from "./physics.ts";
export type { BodyConfig, BodyType, SolverConfig, Vec2 } from "./physics.ts";
export { createEntity, DEFAULT_TRANSFORM, getWorldTransform } from "./entity.ts";
export type {
BodySlot,
BubbleSlot,
BubbleTextConfig,
CustomSlot,
Entity,
EntityOptions,
ReflectionSlot,
ShadowSlot,
SlotKey,
SpriteFrame,
SpriteSlot,
Transform,
} from "./entity.ts";
export type { System } from "./system.ts";
export { Camera } from "./camera.ts";
export type { CameraConfig } from "./camera.ts";
export { World } from "./world.ts";
export type { WorldConfig, WorldStats } from "./world.ts";
export { animatedSprite, Animator, imageSize, staticSprite } from "./animation.ts";
export type { AnimatedSprite, AnimatedSpriteOptions, AnimationClip } from "./animation.ts";
+296
View File
@@ -0,0 +1,296 @@
/**
* physics.ts — rigid AABB bodies with world collisions.
*
* The solver:
* - integrates forces and velocity each step
* - resolves collisions against floor, ceiling, and side walls
* - applies restitution and Coulomb friction at contacts
* - never knows about entities, sprites, or rendering
*
* Coordinate system:
* - x grows right, y grows down
* - position is the top-left corner of the AABB
* - gravity is a positive-y acceleration
* - units: pixels, seconds
*
* Design notes:
* Bodies carry an `id` and a `type` tag so future constraint solvers can
* reference them. The solver has distinct integrate/collide phases so a
* constraint phase can be inserted between them later.
*/
export interface Vec2 {
x: number;
y: number;
}
export type BodyType = "box";
export interface BodyConfig {
/** Top-left corner. */
position: Vec2;
width: number;
height: number;
/** Default 1. Set to 0 for a static (immovable) body. */
mass?: number;
/** Bounciness, 0–1. Default 0.4. */
restitution?: number;
/** Coulomb friction coefficient. Default 0.3. */
friction?: number;
/** Fraction of velocity lost per second. Default 0 (no damping). */
linearDamping?: number;
}
export interface SolverConfig {
width: number;
height: number;
/** Thickness of the floor strip at the bottom, px. Default 0. */
floorHeight?: number;
/** Default { x: 0, y: 1000 }. */
gravity?: Vec2;
/**
* Vertical speed below which a ground contact snaps to rest instead of
* bouncing. Prevents jitter. Default 20.
*/
restVelocityThreshold?: number;
}
let nextBodyId = 0;
/* ------------------------------------------------------------------ */
/* RigidBody */
/* ------------------------------------------------------------------ */
export class RigidBody {
readonly id: number;
readonly type: BodyType = "box";
readonly position: Vec2;
readonly velocity: Vec2;
/** Force accumulator. Cleared after each step. */
readonly force: Vec2;
readonly width: number;
readonly height: number;
readonly mass: number;
readonly inverseMass: number;
readonly restitution: number;
readonly friction: number;
readonly linearDamping: number;
/** Contact flags, valid after step(). Cleared at the start of each step. */
onGround = false;
onCeiling = false;
onLeftWall = false;
onRightWall = false;
constructor(cfg: BodyConfig) {
this.id = nextBodyId++;
this.position = { x: cfg.position.x, y: cfg.position.y };
this.velocity = { x: 0, y: 0 };
this.force = { x: 0, y: 0 };
this.width = cfg.width;
this.height = cfg.height;
this.mass = cfg.mass ?? 1;
this.inverseMass = this.mass > 0 ? 1 / this.mass : 0;
this.restitution = cfg.restitution ?? 0.4;
this.friction = cfg.friction ?? 0.3;
this.linearDamping = cfg.linearDamping ?? 0;
}
get left(): number {
return this.position.x;
}
get right(): number {
return this.position.x + this.width;
}
get top(): number {
return this.position.y;
}
get bottom(): number {
return this.position.y + this.height;
}
get centerX(): number {
return this.position.x + this.width * 0.5;
}
get centerY(): number {
return this.position.y + this.height * 0.5;
}
/** Add a continuous force. Accumulates until the next step. */
applyForce(f: Vec2): void {
this.force.x += f.x;
this.force.y += f.y;
}
/** Instantaneous velocity change. `v += impulse / mass`. */
applyImpulse(i: Vec2): void {
this.velocity.x += i.x * this.inverseMass;
this.velocity.y += i.y * this.inverseMass;
}
/** Overwrite velocity directly, bypassing mass. */
setVelocity(v: Vec2): void {
this.velocity.x = v.x;
this.velocity.y = v.y;
}
/** Zero the force accumulator. Called by the solver after each step. */
clearForces(): void {
this.force.x = 0;
this.force.y = 0;
}
}
/* ------------------------------------------------------------------ */
/* PhysicsSolver */
/* ------------------------------------------------------------------ */
export class PhysicsSolver {
gravity: Vec2;
width: number;
height: number;
floorHeight: number;
restVelocityThreshold: number;
readonly bodies: RigidBody[] = [];
constructor(cfg: SolverConfig) {
this.gravity = cfg.gravity ?? { x: 0, y: 1000 };
this.width = cfg.width;
this.height = cfg.height;
this.floorHeight = cfg.floorHeight ?? 0;
this.restVelocityThreshold = cfg.restVelocityThreshold ?? 20;
}
/** World-space Y of the floor surface. */
get floorY(): number {
return this.height - this.floorHeight;
}
addBody(body: RigidBody): RigidBody {
this.bodies.push(body);
return body;
}
removeBody(body: RigidBody): void {
const i = this.bodies.indexOf(body);
if (i >= 0) this.bodies.splice(i, 1);
}
/** Update world dimensions. Clamps any body that would be out of bounds. */
resize(width: number, height: number, floorHeight?: number): void {
this.width = width;
this.height = height;
if (floorHeight !== undefined) this.floorHeight = floorHeight;
for (const body of this.bodies) {
if (body.left < 0) body.position.x = 0;
if (body.right > this.width) body.position.x = this.width - body.width;
if (body.bottom > this.floorY) body.position.y = this.floorY - body.height;
}
}
/**
* Advance by `dt` seconds.
* Each body is integrated, then its collisions against the world are
* resolved. Contact flags are cleared before integration.
*/
step(dt: number): void {
for (const body of this.bodies) {
body.onGround = false;
body.onCeiling = false;
body.onLeftWall = false;
body.onRightWall = false;
this.integrate(body, dt);
this.resolveWorldCollisions(body, dt);
}
}
/* -------------------------------------------------------------- */
private integrate(body: RigidBody, dt: number): void {
// Static bodies ignore gravity and integration.
if (body.inverseMass === 0) return;
// Gravity as a force: F += m · g. This makes the acceleration
// mass-independent since a = F / m = g.
body.force.x += this.gravity.x * body.mass;
body.force.y += this.gravity.y * body.mass;
// v += (F / m) · dt
body.velocity.x += body.force.x * body.inverseMass * dt;
body.velocity.y += body.force.y * body.inverseMass * dt;
// Damping: multiplicative decay, frame-rate independent.
if (body.linearDamping > 0) {
const retain = Math.pow(1 - body.linearDamping, dt);
body.velocity.x *= retain;
body.velocity.y *= retain;
}
// Semi-implicit Euler: use the just-updated velocity.
body.position.x += body.velocity.x * dt;
body.position.y += body.velocity.y * dt;
body.clearForces();
}
private resolveWorldCollisions(body: RigidBody, dt: number): void {
const floorY = this.floorY;
/* --- floor --- */
if (body.bottom > floorY) {
body.position.y = floorY - body.height;
body.onGround = true;
if (body.velocity.y > 0) {
if (body.velocity.y < this.restVelocityThreshold) {
body.velocity.y = 0;
} else {
body.velocity.y = -body.velocity.y * body.restitution;
}
}
if (body.friction > 0 && body.velocity.x !== 0) {
// Coulomb friction: deceleration μ·|g| per second.
const frictionAccel = body.friction * Math.abs(this.gravity.y);
const dv = frictionAccel * dt;
if (Math.abs(body.velocity.x) <= dv) {
body.velocity.x = 0;
} else {
body.velocity.x -= Math.sign(body.velocity.x) * dv;
}
}
}
/* --- ceiling --- */
if (body.top < 0) {
body.position.y = 0;
body.onCeiling = true;
if (body.velocity.y < 0) {
body.velocity.y = -body.velocity.y * body.restitution;
}
}
/* --- left wall --- */
if (body.left < 0) {
body.position.x = 0;
body.onLeftWall = true;
if (body.velocity.x < 0) {
body.velocity.x = -body.velocity.x * body.restitution;
}
}
/* --- right wall --- */
if (body.right > this.width) {
body.position.x = this.width - body.width;
body.onRightWall = true;
if (body.velocity.x > 0) {
body.velocity.x = -body.velocity.x * body.restitution;
}
}
}
}
View File
+404
View File
@@ -0,0 +1,404 @@
/**
* renderer.ts — Canvas 2D renderer.
*
* The Renderer interface is backend-agnostic. Canvas2DRenderer is the only
* implementation shipped. Everything else in shimejic draws through this
* interface, never through `ctx` directly (except via the escape hatch).
*
* Pixel-art correctness:
* - imageSmoothingEnabled is disabled on every context that draws bitmaps
* - draw positions are rounded to integers when pixelArt is true
* - the canvas CSS property `image-rendering: pixelated` is expected to be
* set by the caller (or by a framework adapter); the renderer cannot set
* CSS from TypeScript
*
* DPI:
* The backing store is sized to cssSize × devicePixelRatio. A transform is
* set so all draw calls think in CSS pixels. Every primitive takes CSS
* pixel coordinates.
*/
/* ------------------------------------------------------------------ */
/* Public types */
/* ------------------------------------------------------------------ */
export type Anchor =
| "top-left"
| "top-center"
| "top-right"
| "center-left"
| "center"
| "center-right"
| "bottom-left"
| "bottom-center"
| "bottom-right";
export interface RendererSize {
width: number;
height: number;
dpr: number;
}
export interface RendererConfig {
canvas: HTMLCanvasElement;
/** Disable smoothing and round to integer positions. Default true. */
pixelArt?: boolean;
/** Cap on devicePixelRatio. Default 3. */
maxDpr?: number;
/** Override for testing. Default: window.devicePixelRatio || 1. */
devicePixelRatio?: number;
/** Fill colour applied after clear. Omit for transparent. */
backgroundColor?: string;
/**
* Factory for offscreen scratch canvases (used by reflections).
* Defaults to document.createElement('canvas'). Inject for tests.
*/
createCanvas?: () => HTMLCanvasElement;
}
export interface SpriteDraw {
image: CanvasImageSource;
/** Anchor position in CSS pixels. Meaning depends on `anchor`. */
x: number;
y: number;
width: number;
height: number;
/** Default 'top-left'. */
anchor?: Anchor;
/** Flip horizontally. Default false. */
mirrored?: boolean;
/** Overall alpha, 0–1. Default 1. */
alpha?: number;
/** Additional x scale about the anchor. Default 1. */
scaleX?: number;
/** Additional y scale about the anchor. Default 1. */
scaleY?: number;
}
export interface ShadowDraw {
cx: number;
cy: number;
rx: number;
ry: number;
color?: string;
alpha?: number;
}
export interface ReflectionDraw {
image: CanvasImageSource;
x: number;
y: number;
width: number;
height: number;
anchor?: Anchor;
mirrored?: boolean;
alpha?: number;
/** Fade toward the far edge, 0–1. Default 0. */
fade?: number;
/** Colour wash applied with source-atop. Omit for no tint. */
tint?: string;
/** Which way the reflection fades. Default 'down'. */
fadeDirection?: "down" | "up";
}
export interface TextDraw {
content: string;
x: number;
y: number;
width: number;
height: number;
/** Full CSS font string, e.g. "12px monospace". */
font?: string;
color?: string;
align?: "left" | "center" | "right";
baseline?: "top" | "middle" | "bottom";
/** Multiplier over font size. Default 1.2. */
lineHeight?: number;
/** Word-wrap to width. Default true. */
wrap?: boolean;
/** Reveal only the first N characters (cumulative across lines). Default Infinity. */
charsShown?: number;
}
export interface Renderer {
resize(cssW: number, cssH: number): void;
clear(): void;
drawSprite(d: SpriteDraw): void;
drawShadow(s: ShadowDraw): void;
drawReflection(r: ReflectionDraw): void;
drawText(t: TextDraw): void;
readonly size: RendererSize;
/** Escape hatch. Prefer primitives. */
readonly ctx: CanvasRenderingContext2D;
}
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
/** Offset from the anchor point to the image's top-left corner. */
export function anchorOffset(anchor: Anchor, w: number, h: number): { ox: number; oy: number } {
const hx = anchor.includes("left") ? 0 : anchor.includes("right") ? -w : -w / 2;
const hy = anchor.startsWith("top") ? 0 : anchor.startsWith("bottom") ? -h : -h / 2;
return { ox: hx, oy: hy };
}
function parseFontSize(font: string | undefined): number {
if (!font) return 11;
const m = /(\d+(?:\.\d+)?)px/.exec(font);
return m?.[1] !== undefined ? parseFloat(m[1]) : 11;
}
function wrapText(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string[] {
const words = text.split(/\s+/).filter(Boolean);
const lines: string[] = [];
let line = "";
for (const word of words) {
const candidate = line.length > 0 ? `${line} ${word}` : word;
if (ctx.measureText(candidate).width <= maxWidth) {
line = candidate;
} else {
if (line.length > 0) lines.push(line);
line = word;
}
}
if (line.length > 0) lines.push(line);
return lines;
}
/* ------------------------------------------------------------------ */
/* Canvas2DRenderer */
/* ------------------------------------------------------------------ */
export class Canvas2DRenderer implements Renderer {
readonly ctx: CanvasRenderingContext2D;
readonly canvas: HTMLCanvasElement;
private readonly pixelArt: boolean;
private readonly maxDpr: number;
private readonly dprOverride: number | undefined;
private readonly backgroundColor: string | undefined;
private readonly createCanvas: () => HTMLCanvasElement;
private dpr = 1;
private cssW = 0;
private cssH = 0;
private reflCanvas: HTMLCanvasElement | null = null;
private reflCtx: CanvasRenderingContext2D | null = null;
private reflW = 0;
private reflH = 0;
constructor(cfg: RendererConfig) {
this.canvas = cfg.canvas;
const ctx = this.canvas.getContext("2d");
if (!ctx) throw new Error("Canvas2DRenderer: could not acquire 2D context");
this.ctx = ctx;
this.pixelArt = cfg.pixelArt ?? true;
this.maxDpr = cfg.maxDpr ?? 3;
this.dprOverride = cfg.devicePixelRatio;
this.backgroundColor = cfg.backgroundColor;
this.createCanvas = cfg.createCanvas ?? (() => document.createElement("canvas"));
// Sensible default transform so early draws aren't unscaled.
this.applyTransform();
}
get size(): RendererSize {
return { width: this.cssW, height: this.cssH, dpr: this.dpr };
}
resize(cssW: number, cssH: number): void {
const w = Math.max(1, cssW);
const h = Math.max(1, cssH);
const dpr = Math.min(this.dprOverride ?? window.devicePixelRatio ?? 1, this.maxDpr);
if (w === this.cssW && h === this.cssH && dpr === this.dpr) return;
this.cssW = w;
this.cssH = h;
this.dpr = dpr;
this.canvas.width = Math.round(w * dpr);
this.canvas.height = Math.round(h * dpr);
this.applyTransform();
}
clear(): void {
this.ctx.clearRect(0, 0, this.cssW, this.cssH);
if (this.backgroundColor !== undefined) {
this.ctx.fillStyle = this.backgroundColor;
this.ctx.fillRect(0, 0, this.cssW, this.cssH);
}
}
drawShadow(s: ShadowDraw): void {
const alpha = s.alpha ?? 0.3;
if (alpha <= 0) return;
const ctx = this.ctx;
ctx.save();
ctx.globalAlpha = alpha;
ctx.fillStyle = s.color ?? "#000";
ctx.beginPath();
ctx.ellipse(s.cx, s.cy, s.rx, s.ry, 0, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
drawSprite(d: SpriteDraw): void {
const alpha = d.alpha ?? 1;
if (alpha <= 0) return;
const anchor = d.anchor ?? "top-left";
const { ox, oy } = anchorOffset(anchor, d.width, d.height);
const ax = this.round(d.x);
const ay = this.round(d.y);
const sx = (d.mirrored === true ? -1 : 1) * (d.scaleX ?? 1);
const sy = d.scaleY ?? 1;
const ctx = this.ctx;
ctx.save();
ctx.globalAlpha = alpha;
if (sx !== 1 || sy !== 1) {
// Scale about the anchor so squash keeps the anchor pinned.
ctx.translate(ax, ay);
ctx.scale(sx, sy);
ctx.drawImage(d.image, ox, oy, d.width, d.height);
} else {
ctx.drawImage(d.image, ax + ox, ay + oy, d.width, d.height);
}
ctx.restore();
}
drawReflection(r: ReflectionDraw): void {
const alpha = r.alpha ?? 1;
if (alpha <= 0.01) return;
const pw = Math.max(1, Math.round(r.width * this.dpr));
const ph = Math.max(1, Math.round(r.height * this.dpr));
if (this.reflW !== pw || this.reflH !== ph) {
if (this.reflCanvas === null) {
this.reflCanvas = this.createCanvas();
}
this.reflCanvas.width = pw;
this.reflCanvas.height = ph;
this.reflW = pw;
this.reflH = ph;
}
if (this.reflCtx === null) {
const c = this.reflCanvas?.getContext("2d");
if (!c) return;
this.reflCtx = c;
}
const rc = this.reflCtx;
rc.setTransform(1, 0, 0, 1, 0, 0);
rc.globalCompositeOperation = "source-over";
rc.globalAlpha = 1;
rc.clearRect(0, 0, pw, ph);
rc.imageSmoothingEnabled = !this.pixelArt;
// 1. Draw the image flipped vertically (and optionally horizontally).
rc.save();
rc.translate(r.mirrored === true ? pw : 0, ph);
rc.scale(r.mirrored === true ? -1 : 1, -1);
rc.drawImage(r.image, 0, 0, pw, ph);
rc.restore();
// 2. Tint — paints only over existing pixels.
if (r.tint !== undefined) {
rc.globalCompositeOperation = "source-atop";
rc.fillStyle = r.tint;
rc.fillRect(0, 0, pw, ph);
}
// 3. Fade toward the far edge.
const fade = Math.min(Math.max(r.fade ?? 0, 0), 1);
if (fade > 0) {
rc.globalCompositeOperation = "destination-out";
const grad = rc.createLinearGradient(0, 0, 0, ph);
const topA = r.fadeDirection === "up" ? fade : 0;
const botA = r.fadeDirection === "up" ? 0 : fade;
grad.addColorStop(0, `rgba(0,0,0,${topA})`);
grad.addColorStop(1, `rgba(0,0,0,${botA})`);
rc.fillStyle = grad;
rc.fillRect(0, 0, pw, ph);
}
rc.globalCompositeOperation = "source-over";
// 4. Composite to the main canvas.
const anchor = r.anchor ?? "top-left";
const { ox, oy } = anchorOffset(anchor, r.width, r.height);
const x = this.round(r.x) + ox;
const y = this.round(r.y) + oy;
const ctx = this.ctx;
ctx.save();
ctx.globalAlpha = alpha;
ctx.drawImage(this.reflCanvas!, x, y, r.width, r.height);
ctx.restore();
}
drawText(t: TextDraw): void {
if (t.content.length === 0) return;
const ctx = this.ctx;
const fontSize = parseFontSize(t.font);
const lineHeight = (t.lineHeight ?? 1.2) * fontSize;
const align = t.align ?? "center";
const baseline = t.baseline ?? "top";
const charsShown = t.charsShown ?? Infinity;
ctx.save();
ctx.font = t.font ?? "11px monospace";
ctx.fillStyle = t.color ?? "#000";
ctx.textBaseline = baseline === "middle" ? "middle" : baseline;
ctx.textAlign = align;
const lines = t.wrap === false ? [t.content] : wrapText(ctx, t.content, t.width);
const anchorX = align === "left" ? t.x : align === "right" ? t.x + t.width : t.x + t.width / 2;
const baseY = baseline === "top" ? t.y : baseline === "bottom" ? t.y + t.height : t.y + t.height / 2;
let cursor = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line === undefined) continue;
const visible = Math.max(0, Math.min(line.length, charsShown - cursor));
if (visible <= 0) break;
const yy =
baseline === "top"
? baseY + i * lineHeight
: baseline === "bottom"
? baseY - (lines.length - 1 - i) * lineHeight
: baseY - ((lines.length - 1) / 2 - i) * lineHeight;
ctx.fillText(line.slice(0, visible), anchorX, yy);
cursor += line.length;
if (visible < line.length) break;
}
ctx.restore();
}
/* -------------------------------------------------------------- */
private applyTransform(): void {
this.ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0);
this.ctx.imageSmoothingEnabled = !this.pixelArt;
}
private round(v: number): number {
return this.pixelArt ? Math.round(v) : v;
}
}
+27
View File
@@ -0,0 +1,27 @@
/**
* system.ts — the system interface.
*
* A system is an object with an `update` method. Systems run in ascending
* `order`. `renderOnly` systems run during render() instead of update(),
* and are skipped by pause/timescale on the update side.
*/
import type { World } from "./world.ts";
export interface System {
readonly name: string;
/** Sort key. Lower runs first. Default 0. */
readonly order?: number;
/**
* When true, this system runs during World.render() with the last
* scaled dt, instead of during World.update().
*/
readonly renderOnly?: boolean;
update(world: World, dt: number): void;
/** Called once when added to a world. */
onAdd?(world: World): void;
/** Called once when removed from a world. */
onRemove?(world: World): void;
}
+204
View File
@@ -0,0 +1,204 @@
/**
* world.ts — the top-level simulation container.
*
* Owns entities, systems, time state, and the optional camera. Provides
* safe add/remove during iteration via deferred queues flushed at the end
* of each update.
*
* The update loop:
* 1. Compute scaled dt (respects pause and timeScale).
* 2. Update camera.
* 3. Run each non-render system in order.
* 4. Flush pending adds and removes.
*
* The render loop:
* 1. Run each renderOnly system in order with the last scaled dt.
*
* Additions and removals are queued, not applied immediately. A system
* that adds an entity during update will not see it until the next frame.
*/
import { Camera, type CameraConfig } from "./camera.ts";
import { createEntity, type Entity, type EntityOptions, type SlotKey } from "./entity.ts";
import type { System } from "./system.ts";
export interface WorldConfig {
width: number;
height: number;
/** Clamp on raw frame dt, seconds. Default 1/20. */
maxDelta?: number;
camera?: CameraConfig;
}
export interface WorldStats {
frameCount: number;
lastRawDt: number;
lastScaledDt: number;
}
export class World {
width: number;
height: number;
timeScale = 1;
paused = false;
/** Scaled seconds elapsed since creation. */
time = 0;
readonly camera: Camera;
readonly maxDelta: number;
readonly stats: WorldStats = {
frameCount: 0,
lastRawDt: 0,
lastScaledDt: 0,
};
private readonly _entities: Entity[] = [];
private readonly _systems: System[] = [];
private readonly _pendingAdds: Entity[] = [];
private readonly _pendingRemoves: Entity[] = [];
private lastScaledDt = 0;
constructor(cfg: WorldConfig) {
this.width = cfg.width;
this.height = cfg.height;
this.maxDelta = cfg.maxDelta ?? 1 / 20;
this.camera = new Camera(cfg.camera);
}
/* -------------------------------------------------------------- */
/* Accessors */
/* -------------------------------------------------------------- */
get entities(): readonly Entity[] {
return this._entities;
}
get systems(): readonly System[] {
return this._systems;
}
/** Entities with no parent. Renderers iterate these and recurse. */
get roots(): readonly Entity[] {
const result: Entity[] = [];
for (const e of this._entities) {
if (!e.destroyed && e.parent === null) result.push(e);
}
return result;
}
/* -------------------------------------------------------------- */
/* Entities */
/* -------------------------------------------------------------- */
/** Create an entity and queue it for addition. */
createEntity(opts: EntityOptions = {}): Entity {
const e = createEntity(opts);
this._pendingAdds.push(e);
return e;
}
/** Queue an already-created entity for addition. */
addEntity(entity: Entity): Entity {
this._pendingAdds.push(entity);
return entity;
}
/**
* Mark an entity as destroyed and queue it for removal.
* Cascades to children. Idempotent.
*/
removeEntity(entity: Entity): void {
if (entity.destroyed) return;
entity.destroyed = true;
// Detach from parent
if (entity.parent !== null) {
const i = entity.parent.children.indexOf(entity);
if (i >= 0) entity.parent.children.splice(i, 1);
entity.parent = null;
}
// Cascade to children (copy the array first — removeEntity mutates it)
for (const child of [...entity.children]) {
this.removeEntity(child);
}
this._pendingRemoves.push(entity);
}
/** All live entities that have the given slot populated. */
entitiesWith<K extends SlotKey>(slot: K): Entity[] {
const result: Entity[] = [];
for (const e of this._entities) {
if (e.destroyed) continue;
if (e[slot] !== undefined) result.push(e);
}
return result;
}
/* -------------------------------------------------------------- */
/* Systems */
/* -------------------------------------------------------------- */
addSystem(system: System): System {
this._systems.push(system);
this._systems.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
system.onAdd?.(this);
return system;
}
removeSystem(system: System): void {
const i = this._systems.indexOf(system);
if (i < 0) return;
this._systems.splice(i, 1);
system.onRemove?.(this);
}
/* -------------------------------------------------------------- */
/* Main loop */
/* -------------------------------------------------------------- */
update(rawDt: number): void {
this.stats.frameCount++;
this.stats.lastRawDt = rawDt;
const clamped = Math.min(rawDt, this.maxDelta);
const scaledDt = this.paused ? 0 : clamped * this.timeScale;
this.stats.lastScaledDt = scaledDt;
this.lastScaledDt = scaledDt;
this.time += scaledDt;
this.camera.update(scaledDt);
for (const sys of this._systems) {
if (sys.renderOnly === true) continue;
sys.update(this, scaledDt);
}
this.flush();
}
render(): void {
for (const sys of this._systems) {
if (sys.renderOnly !== true) continue;
sys.update(this, this.lastScaledDt);
}
}
/* -------------------------------------------------------------- */
private flush(): void {
if (this._pendingAdds.length > 0) {
for (const e of this._pendingAdds) this._entities.push(e);
this._pendingAdds.length = 0;
}
if (this._pendingRemoves.length > 0) {
for (const e of this._pendingRemoves) {
const i = this._entities.indexOf(e);
if (i >= 0) this._entities.splice(i, 1);
}
this._pendingRemoves.length = 0;
}
}
}