@vibe-engine/web 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Runtime de browser: loop com tick fixo (acumulador), teclado → ações e
3
+ * render por frame. O world só avança por `step`, como no headless; o browser
4
+ * só decide quando chamar.
5
+ */
6
+ import type { World } from '@vibe-engine/core';
7
+ export { actionsFromKeys, isTyping, pointerAim } from './keyboard.ts';
8
+ export { createAudioPlayer } from './audio.ts';
9
+ export { distanceGain, spatial2D, toWebAudio, SPATIAL_DEFAULTS } from './spatial.ts';
10
+ export type { AudioListenerState, SpatialOptions } from './spatial.ts';
11
+ export { createUiOverlay } from './ui.ts';
12
+ export type { UiOverlayOptions } from './ui.ts';
13
+ export { themeCss, mergeTheme, DEFAULT_THEME } from './ui-theme.ts';
14
+ export { indexedDbSaveStore } from './save-store.ts';
15
+ export { bootGame, type BootOptions } from './boot.ts';
16
+ export type { UiOverlay } from './ui.ts';
17
+ export type { AudioPlayer } from './audio.ts';
18
+ import type { AudioPlayer } from './audio.ts';
19
+ import type { AudioListenerState } from './spatial.ts';
20
+ export interface WebRenderer {
21
+ /** `alpha`: fração do próximo tick já decorrida (0..1), para interpolar. */
22
+ render(world: World, alpha?: number): void;
23
+ /** Chamado antes de cada tick (o renderer guarda o estado anterior para interpolar). */
24
+ beforeTick?(world: World): void;
25
+ /** Coordenadas da janela (`clientX/Y`) → mundo. Necessário para bindings `pointer`. */
26
+ screenToWorld?(clientX: number, clientY: number): {
27
+ x: number;
28
+ y: number;
29
+ };
30
+ /** Ouvinte do áudio posicional: a câmera do último frame desenhado (null = sem câmera). */
31
+ listener?(): AudioListenerState | null;
32
+ }
33
+ export interface RunningGame {
34
+ stop(): void;
35
+ }
36
+ export declare function startGame(world: World, opts?: {
37
+ renderer?: WebRenderer;
38
+ audio?: AudioPlayer;
39
+ keyboard?: boolean;
40
+ onError?: (err: Error) => void;
41
+ expose?: boolean;
42
+ /** Um tick do relógio fixo. Padrão `world.step(1)`; o cliente de rede passa `() => client.tick()`. */
43
+ step?: () => void;
44
+ }): RunningGame;
45
+ export { createDebugPanel } from './debug.ts';
46
+ export { fitScale, fitToWindow } from './fit.ts';
package/dist/index.js ADDED
@@ -0,0 +1,148 @@
1
+ import { actionsFromKeys, isTyping, pointerAim } from './keyboard.js';
2
+ export { actionsFromKeys, isTyping, pointerAim } from './keyboard.js';
3
+ export { createAudioPlayer } from './audio.js';
4
+ export { distanceGain, spatial2D, toWebAudio, SPATIAL_DEFAULTS } from './spatial.js';
5
+ export { createUiOverlay } from './ui.js';
6
+ export { themeCss, mergeTheme, DEFAULT_THEME } from './ui-theme.js';
7
+ export { indexedDbSaveStore } from './save-store.js';
8
+ export { bootGame } from './boot.js';
9
+ /** Ticks no máximo por frame: depois de uma aba em segundo plano, não tenta "recuperar" segundos de uma vez. */
10
+ const MAX_CATCH_UP = 5;
11
+ export function startGame(world, opts = {}) {
12
+ const keys = new Set();
13
+ const last = new Map();
14
+ const downAt = new Map(); // tick em que cada botão foi apertado
15
+ const syncKeys = () => {
16
+ const map = world.inputMap;
17
+ if (!map)
18
+ return;
19
+ for (const [action, value] of Object.entries(actionsFromKeys(map, keys))) {
20
+ const key = JSON.stringify(value);
21
+ if (last.get(action) === key)
22
+ continue;
23
+ last.set(action, key);
24
+ // Toque mais rápido que um tick (clique, tecla batida): vira `press`, que garante um tick apertado.
25
+ if (value === false && downAt.get(action) === world.frame)
26
+ world.input.press(action, world.localPlayer);
27
+ else
28
+ world.input.set(action, value, world.localPlayer);
29
+ if (value === true)
30
+ downAt.set(action, world.frame);
31
+ }
32
+ };
33
+ const down = (e) => {
34
+ if (isTyping(e.target)) {
35
+ if (keys.size) {
36
+ keys.clear();
37
+ syncKeys();
38
+ }
39
+ return;
40
+ } // digitando num campo: nada vira ação (e solta o que estava apertado)
41
+ if (!e.repeat) {
42
+ keys.add(e.code);
43
+ syncKeys();
44
+ }
45
+ };
46
+ const unlock = () => opts.audio?.unlock(); // na captura: vale até para teclas e cliques que a UI consome
47
+ const up = (e) => { keys.delete(e.code); syncKeys(); };
48
+ const blur = () => { keys.clear(); syncKeys(); }; // trocar de aba solta tudo
49
+ const BUTTONS = ['left', 'middle', 'right'];
50
+ const mouseDown = (e) => { keys.add(`Mouse:${BUTTONS[e.button]}`); syncKeys(); };
51
+ const mouseUp = (e) => { keys.delete(`Mouse:${BUTTONS[e.button]}`); syncKeys(); };
52
+ // Botão direito ligado a uma ação (ex.: faca): sem o menu do browser por cima do jogo.
53
+ const usesRight = Object.values(world.inputMap?.actions ?? {}).some((s) => s.mouse?.includes('right'));
54
+ const noMenu = (e) => e.preventDefault();
55
+ let pointer = null;
56
+ const move = (e) => { pointer = { x: e.clientX, y: e.clientY }; };
57
+ // `pointer: { from: 'player' }` num vector2: direção da entidade até o mouse, recalculada todo frame.
58
+ const aims = Object.entries(world.inputMap?.actions ?? {}).filter(([, s]) => s.type === 'vector2' && s.pointer?.from)
59
+ .map(([action, s]) => ({ action, from: s.pointer.from }));
60
+ const syncPointer = () => {
61
+ if (!pointer || !opts.renderer?.screenToWorld)
62
+ return;
63
+ const target = opts.renderer.screenToWorld(pointer.x, pointer.y);
64
+ for (const { action, from } of aims) {
65
+ const id = from.replaceAll('{local}', world.localPlayer); // `pointer: { from: 'avatar-{local}' }` em multiplayer
66
+ const at = world.exists(id) ? world.observe({ entityIds: [id] }).entities[id]?.Transform2D : undefined;
67
+ if (!at)
68
+ continue;
69
+ const value = pointerAim(at, target);
70
+ const key = JSON.stringify(value);
71
+ if (last.get(action) === key)
72
+ continue;
73
+ last.set(action, key);
74
+ world.input.set(action, value, world.localPlayer);
75
+ }
76
+ };
77
+ if (opts.keyboard !== false) {
78
+ addEventListener('keydown', down);
79
+ addEventListener('keyup', up);
80
+ addEventListener('blur', blur);
81
+ addEventListener('mousedown', mouseDown);
82
+ addEventListener('mouseup', mouseUp);
83
+ if (usesRight)
84
+ addEventListener('contextmenu', noMenu);
85
+ addEventListener('pointermove', move);
86
+ addEventListener('pointerdown', unlock, { capture: true });
87
+ addEventListener('keydown', unlock, { capture: true });
88
+ }
89
+ // Para agentes e debug no console: window.__vibe.world.observe()
90
+ if (opts.expose)
91
+ globalThis.__vibe = { world };
92
+ let raf = 0;
93
+ let acc = 0;
94
+ let prev = performance.now();
95
+ let running = true;
96
+ const frame = (now) => {
97
+ if (!running)
98
+ return;
99
+ acc = Math.min(acc + (now - prev) / 1000, MAX_CATCH_UP * world.dt);
100
+ prev = now;
101
+ try {
102
+ syncPointer();
103
+ while (acc >= world.dt) {
104
+ opts.renderer?.beforeTick?.(world);
105
+ if (opts.step)
106
+ opts.step();
107
+ else
108
+ world.step(1);
109
+ acc -= world.dt;
110
+ }
111
+ opts.renderer?.render(world, acc / world.dt);
112
+ opts.audio?.update(world, opts.renderer?.listener?.());
113
+ }
114
+ catch (err) {
115
+ running = false;
116
+ (opts.onError ?? showError)(err);
117
+ return;
118
+ }
119
+ raf = requestAnimationFrame(frame);
120
+ };
121
+ raf = requestAnimationFrame(frame);
122
+ return {
123
+ stop() {
124
+ running = false;
125
+ cancelAnimationFrame(raf);
126
+ removeEventListener('keydown', down);
127
+ removeEventListener('keyup', up);
128
+ removeEventListener('blur', blur);
129
+ removeEventListener('mousedown', mouseDown);
130
+ removeEventListener('mouseup', mouseUp);
131
+ removeEventListener('contextmenu', noMenu);
132
+ removeEventListener('pointermove', move);
133
+ removeEventListener('pointerdown', unlock, { capture: true });
134
+ removeEventListener('keydown', unlock, { capture: true });
135
+ },
136
+ };
137
+ }
138
+ /** Erro visível na página, sóbrio, com a mensagem completa (o world está envenenado: parar é o certo). */
139
+ function showError(err) {
140
+ console.error(err);
141
+ const box = document.createElement('pre');
142
+ box.textContent = `vibe-engine: o jogo parou.\n\n${err instanceof Error ? err.message : String(err)}`;
143
+ box.setAttribute('role', 'alert');
144
+ box.style.cssText = 'position:fixed;inset:auto 12px 12px 12px;margin:0;padding:12px;background:#fff;color:#1a1a1a;border:1px solid #1a1a1a;font:12px ui-monospace,monospace;white-space:pre-wrap;z-index:9999';
145
+ document.body.appendChild(box);
146
+ }
147
+ export { createDebugPanel } from './debug.js';
148
+ export { fitScale, fitToWindow } from './fit.js';
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Teclado e mouse → ações do mapa de input (RFC-001 §12). Pura: testável sem DOM.
3
+ * Botões do mouse entram no conjunto como `Mouse:left`, `Mouse:right`, `Mouse:middle`.
4
+ */
5
+ import type { InputDef, InputValue } from '@vibe-engine/core';
6
+ /** Valor de cada ação com binding de teclado, dado o conjunto de teclas apertadas (`KeyboardEvent.code`). */
7
+ export declare function actionsFromKeys(def: InputDef, keys: ReadonlySet<string>): Record<string, InputValue>;
8
+ /** O evento de teclado é de alguém digitando (campo de texto): o jogo não trata a tecla como ação. */
9
+ export declare function isTyping(target: unknown): boolean;
10
+ /**
11
+ * Direção normalizada de `from` até o ponteiro, arredondada em 2 casas (a gravação
12
+ * fica pequena e o jogo não depende de ruído do mouse). Ponteiro em cima de `from`: [0, 0].
13
+ */
14
+ export declare function pointerAim(from: {
15
+ x: number;
16
+ y: number;
17
+ }, to: {
18
+ x: number;
19
+ y: number;
20
+ }): [number, number];
@@ -0,0 +1,54 @@
1
+ const list = (v) => (Array.isArray(v) ? v.map(String) : typeof v === 'string' ? [v] : []);
2
+ /** Valor de cada ação com binding de teclado, dado o conjunto de teclas apertadas (`KeyboardEvent.code`). */
3
+ export function actionsFromKeys(def, keys) {
4
+ const out = {};
5
+ const any = (codes) => list(codes).some((c) => keys.has(c));
6
+ for (const [name, spec] of Object.entries(def.actions)) {
7
+ const kb = spec.keyboard;
8
+ const mouse = list(spec.mouse).map((b) => `Mouse:${b}`);
9
+ if (kb === undefined && mouse.length === 0)
10
+ continue;
11
+ switch (spec.type) {
12
+ case 'button':
13
+ out[name] = any(kb) || mouse.some((m) => keys.has(m));
14
+ break;
15
+ case 'axis':
16
+ if (kb === undefined)
17
+ break;
18
+ out[name] = (any(kb.positive) ? 1 : 0) - (any(kb.negative) ? 1 : 0);
19
+ break;
20
+ case 'vector2':
21
+ if (kb === undefined)
22
+ break;
23
+ out[name] = [(any(kb.right) ? 1 : 0) - (any(kb.left) ? 1 : 0), (any(kb.down) ? 1 : 0) - (any(kb.up) ? 1 : 0)];
24
+ break;
25
+ case 'number': {
26
+ if (kb === undefined)
27
+ break;
28
+ // { Digit1: 0, Digit2: 1 }: a última tecla da lista que estiver apertada vence.
29
+ const hit = Object.entries(kb).filter(([code]) => keys.has(code)).pop();
30
+ if (hit)
31
+ out[name] = hit[1];
32
+ break;
33
+ }
34
+ }
35
+ }
36
+ return out;
37
+ }
38
+ /** O evento de teclado é de alguém digitando (campo de texto): o jogo não trata a tecla como ação. */
39
+ export function isTyping(target) {
40
+ const t = target;
41
+ return !!t && (t.isContentEditable === true || t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT');
42
+ }
43
+ /**
44
+ * Direção normalizada de `from` até o ponteiro, arredondada em 2 casas (a gravação
45
+ * fica pequena e o jogo não depende de ruído do mouse). Ponteiro em cima de `from`: [0, 0].
46
+ */
47
+ export function pointerAim(from, to) {
48
+ const dx = to.x - from.x;
49
+ const dy = to.y - from.y;
50
+ const len = Math.hypot(dx, dy);
51
+ if (len < 1e-6)
52
+ return [0, 0];
53
+ return [Math.round((dx / len) * 100) / 100, Math.round((dy / len) * 100) / 100];
54
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Saves no browser (IndexedDB). Carrega tudo antes do jogo começar (a API de
3
+ * save é síncrona no tick) e grava em segundo plano.
4
+ */
5
+ import type { SaveStore } from '@vibe-engine/core';
6
+ export declare function indexedDbSaveStore(name: string): Promise<SaveStore>;
@@ -0,0 +1,28 @@
1
+ export async function indexedDbSaveStore(name) {
2
+ const db = await new Promise((resolve, reject) => {
3
+ const req = indexedDB.open(`vibe-saves:${name}`, 1);
4
+ req.onupgradeneeded = () => req.result.createObjectStore('saves');
5
+ req.onsuccess = () => resolve(req.result);
6
+ req.onerror = () => reject(req.error);
7
+ });
8
+ const cache = new Map();
9
+ await new Promise((resolve, reject) => {
10
+ const tx = db.transaction('saves', 'readonly');
11
+ const cursor = tx.objectStore('saves').openCursor();
12
+ cursor.onsuccess = () => {
13
+ const c = cursor.result;
14
+ if (!c)
15
+ return resolve();
16
+ cache.set(String(c.key), String(c.value));
17
+ c.continue();
18
+ };
19
+ cursor.onerror = () => reject(cursor.error);
20
+ });
21
+ const run = (fn) => { const tx = db.transaction('saves', 'readwrite'); fn(tx.objectStore('saves')); };
22
+ return {
23
+ read: (k) => cache.get(k),
24
+ write: (k, v) => { cache.set(k, v); run((s) => s.put(v, k)); },
25
+ remove: (k) => { cache.delete(k); run((s) => s.delete(k)); },
26
+ keys: () => [...cache.keys()].sort(),
27
+ };
28
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Matemática do áudio posicional (#119), sem Web Audio (testável no node).
3
+ * A curva de distância é a do modelo `inverse` do PannerNode, a mesma no 2D e no 3D.
4
+ */
5
+ export interface Vec3 {
6
+ x: number;
7
+ y: number;
8
+ z: number;
9
+ }
10
+ /** Ouvinte: o que o renderer mostra. 2D: centro da vista e meia largura visível (px). 3D: câmera. */
11
+ export type AudioListenerState = {
12
+ kind: '2d';
13
+ x: number;
14
+ y: number;
15
+ halfWidth: number;
16
+ } | {
17
+ kind: '3d';
18
+ position: Vec3;
19
+ forward: Vec3;
20
+ };
21
+ export interface SpatialOptions {
22
+ /** Até esta distância o som toca com volume cheio (px em 2D, metros em 3D). */
23
+ refDistance: number;
24
+ /** Depois disto o volume para de cair. */
25
+ maxDistance: number;
26
+ /** Rapidez da queda (1 = inverso da distância). */
27
+ rolloff: number;
28
+ }
29
+ export declare const SPATIAL_DEFAULTS: Record<'2d' | '3d', SpatialOptions>;
30
+ /** Ganho (0..1) pela distância: `ref / (ref + rolloff · (d − ref))`, com d preso em [ref, max]. */
31
+ export declare function distanceGain(distance: number, o: SpatialOptions): number;
32
+ /** 2D: pan estéreo (−1 esquerda … 1 direita; borda da tela = lado cheio) e ganho pela distância ao centro da vista. */
33
+ export declare function spatial2D(src: {
34
+ x: number;
35
+ y: number;
36
+ }, l: {
37
+ x: number;
38
+ y: number;
39
+ halfWidth: number;
40
+ }, o: SpatialOptions): {
41
+ pan: number;
42
+ gain: number;
43
+ };
44
+ /** O renderer 3D (Babylon) é mão esquerda, com +z para dentro da tela; o Web Audio é mão direita (−z à frente). */
45
+ export declare const toWebAudio: (p: {
46
+ x: number;
47
+ y: number;
48
+ z?: number;
49
+ }) => Vec3;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Matemática do áudio posicional (#119), sem Web Audio (testável no node).
3
+ * A curva de distância é a do modelo `inverse` do PannerNode, a mesma no 2D e no 3D.
4
+ */
5
+ export const SPATIAL_DEFAULTS = {
6
+ '2d': { refDistance: 300, maxDistance: 2000, rolloff: 1 },
7
+ // Câmera em terceira pessoa fica ~8 m do jogador: os sons dele ainda saem a ~60%.
8
+ '3d': { refDistance: 5, maxDistance: 60, rolloff: 1 },
9
+ };
10
+ /** Ganho (0..1) pela distância: `ref / (ref + rolloff · (d − ref))`, com d preso em [ref, max]. */
11
+ export function distanceGain(distance, o) {
12
+ const d = Math.min(Math.max(distance, o.refDistance), o.maxDistance);
13
+ return o.refDistance / (o.refDistance + o.rolloff * (d - o.refDistance));
14
+ }
15
+ /** 2D: pan estéreo (−1 esquerda … 1 direita; borda da tela = lado cheio) e ganho pela distância ao centro da vista. */
16
+ export function spatial2D(src, l, o) {
17
+ const dx = src.x - l.x;
18
+ return { pan: Math.max(-1, Math.min(1, dx / Math.max(1e-6, l.halfWidth))), gain: distanceGain(Math.hypot(dx, src.y - l.y), o) };
19
+ }
20
+ /** O renderer 3D (Babylon) é mão esquerda, com +z para dentro da tela; o Web Audio é mão direita (−z à frente). */
21
+ export const toWebAudio = (p) => ({ x: p.x, y: p.y, z: -(p.z ?? 0) });
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Tema da UI → CSS (#134). Puro (sem DOM): o overlay põe o resultado num <style>.
3
+ * Cada estilo vira uma classe `.vibe-s-<nome>`; estados viram seletores com a
4
+ * mesma especificidade (`:where`), então vale a ordem: base, hover, focused,
5
+ * pressed, disabled.
6
+ */
7
+ import { type SpriteSheetMeta, type UiStyleSpec, type UiTheme } from '@vibe-engine/core';
8
+ /** O visual padrão da engine: monocromático e sóbrio. O tema do jogo mescla por cima. */
9
+ export declare const DEFAULT_THEME: Required<Pick<UiTheme, 'font' | 'color'>> & {
10
+ styles: Record<string, UiStyleSpec>;
11
+ };
12
+ export interface ThemeAssets {
13
+ fonts?: Record<string, string>;
14
+ images?: Record<string, string>;
15
+ meta?: Record<string, SpriteSheetMeta>;
16
+ }
17
+ /** Família CSS registrada para a fonte-asset `id`. */
18
+ export declare const fontFamily: (id: string) => string;
19
+ /** Tema do jogo mesclado no padrão: estilos de mesmo nome somam propriedades (e estados). */
20
+ export declare function mergeTheme(theme?: UiTheme): typeof DEFAULT_THEME;
21
+ /** CSS do tema inteiro (já mesclado com o padrão). */
22
+ export declare function themeCss(theme: UiTheme, assets?: ThemeAssets): string;
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Tema da UI → CSS (#134). Puro (sem DOM): o overlay põe o resultado num <style>.
3
+ * Cada estilo vira uma classe `.vibe-s-<nome>`; estados viram seletores com a
4
+ * mesma especificidade (`:where`), então vale a ordem: base, hover, focused,
5
+ * pressed, disabled.
6
+ */
7
+ import { UI_STATES } from '@vibe-engine/core';
8
+ /** O visual padrão da engine: monocromático e sóbrio. O tema do jogo mescla por cima. */
9
+ export const DEFAULT_THEME = {
10
+ font: 'ui-monospace, SFMono-Regular, Menlo, monospace',
11
+ color: '#1a1a1a',
12
+ styles: {
13
+ text: { size: 16 },
14
+ button: {
15
+ size: 16, padding: '6px 18px', minWidth: 180, background: '#f4f4f2', color: '#1a1a1a', border: '1px solid #1a1a1a', transition: 90,
16
+ hover: { background: '#e4e4e0' }, focused: { background: '#1a1a1a', color: '#f4f4f2' }, pressed: { scale: 0.97 }, disabled: { opacity: 0.4 },
17
+ },
18
+ input: {
19
+ size: 16, padding: '6px 10px', minWidth: 180, background: '#ffffff', color: '#1a1a1a', border: '1px solid #1a1a1a', transition: 90,
20
+ focused: { shadow: 'inset 0 0 0 1px #1a1a1a' }, disabled: { opacity: 0.4 },
21
+ },
22
+ panel: { background: '#f4f4f2e6', padding: 18 },
23
+ },
24
+ };
25
+ /** Família CSS registrada para a fonte-asset `id`. */
26
+ export const fontFamily = (id) => `vibe-font-${id.replace(/[^a-z0-9]/gi, '-')}`;
27
+ /** Tema do jogo mesclado no padrão: estilos de mesmo nome somam propriedades (e estados). */
28
+ export function mergeTheme(theme = {}) {
29
+ const styles = { ...DEFAULT_THEME.styles };
30
+ for (const [name, spec] of Object.entries(theme.styles ?? {})) {
31
+ // Skin no lugar do fundo e da borda padrão, em todos os estados (senão a cor aparece nos cantos da imagem).
32
+ const base = spec.skin ? withoutFill(styles[name] ?? {}) : (styles[name] ?? {});
33
+ const merged = { ...base, ...spec };
34
+ for (const s of UI_STATES)
35
+ if (base[s] || spec[s])
36
+ merged[s] = { ...base[s], ...spec[s] };
37
+ styles[name] = merged;
38
+ }
39
+ return { font: theme.font ?? DEFAULT_THEME.font, color: theme.color ?? DEFAULT_THEME.color, styles };
40
+ }
41
+ function withoutFill(spec) {
42
+ const strip = ({ background: _b, border: _r, ...rest }) => rest;
43
+ const out = strip(spec);
44
+ for (const s of UI_STATES)
45
+ if (spec[s])
46
+ out[s] = strip(spec[s]);
47
+ return out;
48
+ }
49
+ const resolveFont = (font, a) => (a.fonts?.[font] ? `"${fontFamily(font)}", ${DEFAULT_THEME.font}` : font);
50
+ function declarations(p, a) {
51
+ const d = [];
52
+ const px = (n) => `${n}px`;
53
+ if (p.font)
54
+ d.push(`font-family:${resolveFont(p.font, a)}`);
55
+ if (p.size !== undefined)
56
+ d.push(`font-size:${px(p.size)}`);
57
+ if (p.weight !== undefined)
58
+ d.push(`font-weight:${p.weight}`);
59
+ if (p.color !== undefined)
60
+ d.push(`color:${p.color}`);
61
+ if (p.background !== undefined)
62
+ d.push(`background:${p.background}`);
63
+ if (p.border !== undefined)
64
+ d.push(`border:${p.border}`);
65
+ if (p.radius !== undefined)
66
+ d.push(`border-radius:${px(p.radius)}`);
67
+ if (p.padding !== undefined)
68
+ d.push(`padding:${typeof p.padding === 'number' ? px(p.padding) : p.padding}`);
69
+ if (p.shadow !== undefined)
70
+ d.push(`box-shadow:${p.shadow}`);
71
+ if (p.opacity !== undefined)
72
+ d.push(`opacity:${p.opacity}`);
73
+ if (p.minWidth !== undefined)
74
+ d.push(`min-width:${px(p.minWidth)}`);
75
+ if (p.letterSpacing !== undefined)
76
+ d.push(`letter-spacing:${px(p.letterSpacing)}`);
77
+ if (p.uppercase !== undefined)
78
+ d.push(`text-transform:${p.uppercase ? 'uppercase' : 'none'}`);
79
+ if (p.textAlign !== undefined)
80
+ d.push(`text-align:${p.textAlign}`);
81
+ if (p.scale !== undefined)
82
+ d.push(`scale:${p.scale}`);
83
+ if (p.transition !== undefined)
84
+ d.push(`transition:${['background-color', 'color', 'border-color', 'box-shadow', 'opacity', 'scale'].map((x) => `${x} ${p.transition}ms ease-out`).join(',')}`);
85
+ if (p.enter)
86
+ d.push(`animation:vibe-${p.enter} 180ms ease-out`);
87
+ if (p.skin) {
88
+ const url = a.images?.[p.skin];
89
+ const slice = a.meta?.[p.skin]?.slice;
90
+ if (url && slice !== undefined) {
91
+ const [t, r, b, l] = typeof slice === 'number' ? [slice, slice, slice, slice] : slice;
92
+ const s = p.skinScale ?? 1;
93
+ const w = [t, r, b, l].map((n) => px(n * s)).join(' ');
94
+ d.push('border-style:solid', 'border-color:transparent', `border-width:${w}`, `border-image:url("${url}") ${t} ${r} ${b} ${l} fill / ${w} stretch`);
95
+ if (Number.isInteger(s) && s >= 2)
96
+ d.push('image-rendering:pixelated'); // pixel art ampliada; arte lisa (escala 1 ou fracionária) fica suave
97
+ if (p.background === undefined)
98
+ d.push('background:transparent');
99
+ }
100
+ }
101
+ return d.join(';');
102
+ }
103
+ const STATE_SELECTOR = {
104
+ hover: ':where(:hover:not(:disabled,[data-disabled]))',
105
+ focused: ':where([data-focused])',
106
+ pressed: ':where(:active:not(:disabled,[data-disabled]))',
107
+ disabled: ':where(:disabled,[data-disabled])',
108
+ };
109
+ /** CSS do tema inteiro (já mesclado com o padrão). */
110
+ export function themeCss(theme, assets = {}) {
111
+ const th = mergeTheme(theme);
112
+ const out = [
113
+ `.vibe-ui{font-family:${resolveFont(th.font, assets)};color:${th.color}}`,
114
+ '.vibe-ui button{pointer-events:auto;font:inherit;color:inherit;cursor:pointer;white-space:pre}',
115
+ '.vibe-ui button:disabled{cursor:default}',
116
+ '.vibe-ui input{pointer-events:auto;font:inherit;color:inherit;outline:none;box-sizing:border-box}',
117
+ '.vibe-ui input::placeholder{color:inherit;opacity:.45}',
118
+ '.vibe-ui div:empty:not([data-image]){display:none}', // texto vazio não mostra o fundo/skin do estilo
119
+ '@keyframes vibe-fade{from{opacity:0}}',
120
+ '@keyframes vibe-pop{from{opacity:0;scale:.92}}',
121
+ '@keyframes vibe-rise{from{opacity:0;translate:0 10px}}',
122
+ ];
123
+ for (const [name, spec] of Object.entries(th.styles)) {
124
+ const sel = `.vibe-ui .vibe-s-${name}`;
125
+ out.push(`${sel}{${declarations(spec, assets)}}`);
126
+ for (const s of ['hover', 'focused', 'pressed', 'disabled']) {
127
+ const d = spec[s] && declarations({ ...(spec.skinScale ? { skinScale: spec.skinScale } : {}), ...spec[s] }, assets); // skin do estado herda a escala
128
+ if (d)
129
+ out.push(`${sel}${STATE_SELECTOR[s]}{${d}}`);
130
+ }
131
+ }
132
+ return out.join('\n');
133
+ }
package/dist/ui.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Overlay DOM da UI do jogo: desenha as entidades `Ui*` por cima do canvas.
3
+ * Só lê o estado; clique e teclado viram `world.ui.click/navigate/confirm`
4
+ * (o mesmo caminho de testes e agentes). Botões são <button> de verdade; campos
5
+ * (`UiInput`) são <input>, e o texto digitado vai para o estado por `world.ui.type`.
6
+ */
7
+ import { type SpriteSheetMeta, type UiTheme, type World } from '@vibe-engine/core';
8
+ export interface UiOverlay {
9
+ render(world: World): void;
10
+ destroy(): void;
11
+ }
12
+ export interface UiOverlayOptions {
13
+ parent: HTMLElement;
14
+ world: World;
15
+ /** Imagens: id → URL (UiImage e skins). */
16
+ assets?: Record<string, string>;
17
+ meta?: Record<string, SpriteSheetMeta>;
18
+ /** Fontes: id → URL (`assets/fonts/*.woff2|ttf`). */
19
+ fonts?: Record<string, string>;
20
+ /** `ui` do `vibe.config.ts`. */
21
+ theme?: UiTheme;
22
+ }
23
+ export declare function createUiOverlay(opts: UiOverlayOptions): UiOverlay;