import type { Facing } from './types'; export type { Facing }; const files = import.meta.glob('$lib/assets/character/states/**/*.png', { eager: true, query: '?url', import: 'default' }) as Record; const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); /** Matches states//.png OR states///.png */ const STATE_RE = /\/states\/([^/]+)\/(?:(left|right)\/)?[^/]+\.png$/i; export interface StateSide { frames: string[]; /** True if these frames must be drawn flipped. */ mirrored: boolean; } export interface StatePack { name: string; fps: number; left: StateSide; right: StateSide; /** Reference speed in px/s. When set, playback scales with |vx| / speed. */ speed?: number; /** If true, loops. If false, holds on the last frame after one pass. */ loop: boolean; } export interface StateConfig { fps?: number; speed?: number; loop?: boolean; } export type StateConfigMap = Record; export const STATE_CONFIG: StateConfigMap = { idle: { fps: 6 }, walk: { fps: 8, speed: 120 }, run: { fps: 12, speed: 280 }, jump: { fps: 8, loop: false }, held: { fps: 8 }, falling: { fps: 8 }, landing: { fps: 8, loop: false }, love: { fps: 8 }, drink: { fps: 8, loop: false }, play: { fps: 8, loop: false }, sleep: { fps: 8, loop: false } }; export function loadStates(config: StateConfigMap = {}): Record { const merged: StateConfigMap = { ...STATE_CONFIG, ...config }; const grouped = new Map< string, { left: Array<[string, string]>; right: Array<[string, string]>; flat: Array<[string, string]>; } >(); for (const [path, url] of Object.entries(files)) { const m = STATE_RE.exec(path); if (!m) continue; const name = m[1].toLowerCase(); const side = m[2]?.toLowerCase(); let bucket = grouped.get(name); if (!bucket) { bucket = { left: [], right: [], flat: [] }; grouped.set(name, bucket); } if (side === 'left') bucket.left.push([path, url]); else if (side === 'right') bucket.right.push([path, url]); else bucket.flat.push([path, url]); } const out: Record = {}; for (const [name, buckets] of grouped) { const sortUrls = (arr: Array<[string, string]>) => arr.sort(([a], [b]) => collator.compare(a, b)).map(([, url]) => url); const leftUrls = sortUrls(buckets.left); const rightUrls = sortUrls(buckets.right); const flatUrls = sortUrls(buckets.flat); const cfg = merged[name] ?? {}; let left: StateSide; let right: StateSide; if (leftUrls.length || rightUrls.length) { if (leftUrls.length && rightUrls.length) { left = { frames: leftUrls, mirrored: false }; right = { frames: rightUrls, mirrored: false }; } else if (leftUrls.length) { left = { frames: leftUrls, mirrored: false }; right = { frames: leftUrls, mirrored: true }; } else { right = { frames: rightUrls, mirrored: false }; left = { frames: rightUrls, mirrored: true }; } } else if (flatUrls.length) { left = { frames: flatUrls, mirrored: true }; right = { frames: flatUrls, mirrored: false }; } else { continue; } out[name] = { name, fps: cfg.fps ?? 8, left, right, speed: cfg.speed, loop: cfg.loop ?? true }; } return out; } export function collectStateUrls(packs: Record): string[] { const out = new Set(); for (const pack of Object.values(packs)) { for (const url of pack.left.frames) out.add(url); for (const url of pack.right.frames) out.add(url); } return [...out]; } /* ------------------------------------------------------------------ */ /* State resolution */ /* ------------------------------------------------------------------ */ export type InteractionState = 'free' | 'held' | 'falling' | 'landing' | 'petted'; export interface StateContext { interaction: InteractionState; grounded: boolean; speed: number; /** Active need-action state name (e.g. 'drink'), or null. */ needAction: string | null; } export interface ResolverConfig { idleThreshold: number; runThreshold: number; } /** Interaction-state → state-pack-name overrides, in priority order. */ const INTERACTION_MAP: Array<[InteractionState, string]> = [ ['held', 'held'], ['falling', 'falling'], ['landing', 'landing'], ['petted', 'love'] ]; export function resolveStateName( ctx: StateContext, cfg: ResolverConfig, packs: Record ): string { for (const [interactionState, packName] of INTERACTION_MAP) { if (ctx.interaction === interactionState && packs[packName]) return packName; } if (ctx.needAction && packs[ctx.needAction]) return ctx.needAction; if (!ctx.grounded && packs.jump) return 'jump'; if (ctx.speed >= cfg.runThreshold && packs.run) return 'run'; if (ctx.speed >= cfg.idleThreshold && packs.walk) return 'walk'; return 'idle'; } /* ------------------------------------------------------------------ */ /* Animation clock */ /* ------------------------------------------------------------------ */ export class StateClock { private lastName = ''; private elapsed = 0; update(dt: number, name: string, pack: StatePack | undefined, speed: number): void { if (name !== this.lastName) { this.lastName = name; this.elapsed = 0; return; } if (!pack) return; const rate = pack.speed && pack.speed > 0 ? Math.min(Math.max(speed / pack.speed, 0.25), 3) : 1; this.elapsed += dt * rate; } get time(): number { return this.elapsed; } frameIndex(pack: StatePack, side: StateSide): number { const count = side.frames.length; if (!count) return 0; const raw = Math.floor(this.elapsed * pack.fps); return pack.loop ? raw % count : Math.min(raw, count - 1); } }