@vibe-engine/cli 0.1.0 → 0.1.2

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.
Files changed (33) hide show
  1. package/dist/assets.d.ts +1 -0
  2. package/dist/assets.js +13 -7
  3. package/dist/create.js +3 -0
  4. package/dist/main.js +11 -4
  5. package/dist/run.d.ts +2 -0
  6. package/dist/run.js +1 -1
  7. package/dist/session-daemon.d.ts +1 -0
  8. package/dist/session-daemon.js +103 -0
  9. package/dist/session-host.d.ts +29 -0
  10. package/dist/session-host.js +226 -0
  11. package/dist/session.d.ts +6 -0
  12. package/dist/session.js +256 -0
  13. package/dist/typecheck.d.ts +15 -0
  14. package/dist/typecheck.js +68 -0
  15. package/package.json +4 -4
  16. package/templates/arena-3d/AGENTS.md +4 -4
  17. package/templates/arena-3d/tests/arena.test.ts +1 -1
  18. package/templates/platformer-2d/AGENTS.md +4 -4
  19. package/templates/platformer-2d/tests/gameplay.test.ts +1 -1
  20. package/templates/shooter-2d-pvp/AGENTS.md +12 -11
  21. package/templates/shooter-2d-pvp/README.md +1 -1
  22. package/templates/shooter-2d-pvp/src/components/gun.component.ts +2 -13
  23. package/templates/shooter-2d-pvp/src/events/combat.events.ts +0 -2
  24. package/templates/shooter-2d-pvp/src/level/build.ts +2 -2
  25. package/templates/shooter-2d-pvp/src/listeners/effects.listener.ts +2 -22
  26. package/templates/shooter-2d-pvp/src/listeners/players.listener.ts +3 -2
  27. package/templates/shooter-2d-pvp/src/maps/arena.map.ts +1 -1
  28. package/templates/shooter-2d-pvp/src/rules/damage.ts +4 -19
  29. package/templates/shooter-2d-pvp/src/scenes/arena.scene.ts +2 -2
  30. package/templates/shooter-2d-pvp/src/systems/combat.system.ts +3 -13
  31. package/templates/shooter-2d-pvp/src/systems/gun.system.ts +9 -30
  32. package/templates/shooter-2d-pvp/src/systems/view.system.ts +1 -1
  33. package/templates/shooter-2d-pvp/tests/pvp.test.ts +26 -38
@@ -0,0 +1,256 @@
1
+ /**
2
+ * `vibe session ...` (ADR-0009, RFC-003): comandos curtos que falam com uma
3
+ * sessão viva. `start` sobe o processo da sessão; o resto acha a sessão em
4
+ * `.vibe/sessions/` (a única aberta, ou `--session <id>`) e chama um método.
5
+ */
6
+ import { spawn } from 'node:child_process';
7
+ import { existsSync, mkdirSync, openSync, readFileSync, readdirSync, rmSync } from 'node:fs';
8
+ import { extname, join, relative, resolve } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { randomUUID } from 'node:crypto';
11
+ import { CliError, defineCommand } from './registry.js';
12
+ import { CONFIG_FILE, PROJECT_ERRORS } from './project.js';
13
+ import { PROTOCOL_VERSION, sessionsDir } from './session-host.js';
14
+ const SESSION_ERRORS = {
15
+ 'session-not-found': 'no open session with that id (or several are open and --session is missing)',
16
+ 'session-unreachable': 'the session process is gone or does not answer',
17
+ 'session-unauthorized': 'the session token in .vibe/sessions/ does not match',
18
+ 'protocol-mismatch': 'the CLI and the session process come from different engine versions',
19
+ };
20
+ const sessionFlag = { session: { type: 'string', doc: 'session id (default: the only open session in this project)' } };
21
+ const revisionFlag = { revision: { type: 'number', doc: 'fail with session-revision-stale if the session changed since this revision' } };
22
+ const HEAD = { session: 'session id', frame: 'current tick', revision: 'state revision: goes up on every change' };
23
+ const STATUS = { ...HEAD, scene: 'active scene', seed: 'session seed', running: 'true while resumed (real time)', simTimeMs: 'simulated time in ms', tickRate: 'ticks per second', hash: 'state hash (same seed + same inputs = same hash)', entities: 'entity count', error: 'last world error ({ frame, message, source }) or null' };
24
+ /** Sessões abertas no projeto; arquivos de processos mortos são apagados. */
25
+ export function listSessions(root) {
26
+ const dir = sessionsDir(root);
27
+ if (!existsSync(dir))
28
+ return [];
29
+ const out = [];
30
+ for (const name of readdirSync(dir).filter((n) => n.endsWith('.json'))) {
31
+ const path = join(dir, name);
32
+ try {
33
+ const s = JSON.parse(readFileSync(path, 'utf8'));
34
+ process.kill(s.pid, 0);
35
+ out.push(s);
36
+ }
37
+ catch {
38
+ rmSync(path, { force: true });
39
+ }
40
+ }
41
+ return out.sort((a, b) => a.startedAt.localeCompare(b.startedAt));
42
+ }
43
+ function findSession(root, id) {
44
+ const open = listSessions(root);
45
+ const ids = open.map((s) => s.id);
46
+ if (id !== undefined) {
47
+ const s = open.find((x) => x.id === id);
48
+ if (!s)
49
+ throw new CliError('session-not-found', `session '${id}' is not open`, { detail: { open: ids }, hint: ids.length ? `open: ${ids.join(', ')}` : 'vibe session start' });
50
+ return s;
51
+ }
52
+ if (open.length === 1)
53
+ return open[0];
54
+ throw new CliError('session-not-found', open.length ? `${open.length} sessions are open: pass --session` : 'no session is open in this project', { detail: { open: ids }, hint: open.length ? `--session ${ids[0]}` : 'vibe session start [--scene <id>] [--seed <n>]' });
55
+ }
56
+ export async function callSession(s, method, payload = {}) {
57
+ let res;
58
+ try {
59
+ res = await fetch(`http://127.0.0.1:${s.port}/rpc`, {
60
+ method: 'POST',
61
+ headers: { authorization: `Bearer ${s.token}`, 'content-type': 'application/json' },
62
+ body: JSON.stringify({ protocolVersion: PROTOCOL_VERSION, requestId: randomUUID(), method, payload }),
63
+ signal: AbortSignal.timeout(60_000),
64
+ });
65
+ }
66
+ catch (err) {
67
+ throw new CliError('session-unreachable', `session '${s.id}' does not answer: ${err.message}`, { hint: 'vibe session list (removes dead sessions), then vibe session start' });
68
+ }
69
+ const body = (await res.json().catch(() => ({})));
70
+ if (body.ok)
71
+ return body.result;
72
+ const { code = 'internal', message = `session answered HTTP ${res.status}`, ...fields } = body.error ?? {};
73
+ throw new CliError(code, message, fields);
74
+ }
75
+ const toPayload = (flags, names) => Object.fromEntries(names.filter((n) => flags[n] !== undefined).map((n) => [n, flags[n]]));
76
+ const head = (o) => `${o.session} · tick ${o.frame} · revision ${o.revision}`;
77
+ const statusLine = (o) => `${head(o)} · ${o.scene} · seed ${o.seed} · ${o.running ? 'running' : 'paused'} · hash ${o.hash} · ${o.entities} entities${o.error ? `\nlast error at tick ${o.error.frame}: ${o.error.message}` : ''}`;
78
+ function sessionCommand(c) {
79
+ return defineCommand({
80
+ name: `session ${c.verb}`,
81
+ summary: c.summary,
82
+ ...(c.positionals && { positionals: c.positionals }),
83
+ flags: { ...sessionFlag, ...(c.mutating ? revisionFlag : {}), ...c.flags },
84
+ output: c.output,
85
+ errors: { ...SESSION_ERRORS, ...c.errors },
86
+ async run({ flags, positionals, io }) {
87
+ const s = findSession(io.cwd, flags.session);
88
+ const payload = { ...(c.payload?.(flags, positionals, io.cwd) ?? {}), ...(flags.revision !== undefined && { revision: flags.revision }) };
89
+ return callSession(s, c.verb, payload);
90
+ },
91
+ human: c.human ?? statusLine,
92
+ });
93
+ }
94
+ const start = defineCommand({
95
+ name: 'session start',
96
+ summary: 'Open a live session: the scene loads paused at tick 0 in a background process; other session commands drive it',
97
+ flags: {
98
+ scene: { type: 'string', doc: 'scene id; default: startScene in vibe.config.ts, or the only scene' },
99
+ seed: { type: 'number', default: 1, doc: 'session seed' },
100
+ 'save-dir': { type: 'string', doc: 'read and write saves as files in this folder (default: in memory)' },
101
+ idle: { type: 'number', default: 30, doc: 'minutes without commands before the session closes itself' },
102
+ },
103
+ output: { ...STATUS, log: 'file with the session process output (console.log of the game)' },
104
+ errors: { ...PROJECT_ERRORS, ...SESSION_ERRORS, 'scene-not-found': 'the scene id is not registered', 'world-error': 'the scene setup threw; source points at the game file' },
105
+ async run({ flags, io }) {
106
+ if (!existsSync(join(io.cwd, CONFIG_FILE)))
107
+ throw new CliError('config-missing', `no ${CONFIG_FILE} in ${io.cwd}`, { hint: 'run vibe session start in the project folder' });
108
+ const seed = flags.seed;
109
+ const idle = flags.idle;
110
+ if (!Number.isInteger(seed))
111
+ throw new CliError('usage', `--seed must be an integer, got ${seed}`, { expected: 'integer' });
112
+ if (!(idle > 0))
113
+ throw new CliError('usage', `--idle must be a positive number of minutes, got ${idle}`);
114
+ const id = `s_${randomUUID().slice(0, 6)}`;
115
+ const dir = sessionsDir(io.cwd);
116
+ mkdirSync(dir, { recursive: true });
117
+ const logFile = join(dir, `${id}.log`);
118
+ const log = openSync(logFile, 'w');
119
+ const here = fileURLToPath(import.meta.url);
120
+ const daemon = resolve(here, '..', `session-daemon${extname(here)}`);
121
+ const opts = { id, root: io.cwd, seed, idleMinutes: idle, ...(flags.scene !== undefined && { scene: flags.scene }), ...(flags['save-dir'] !== undefined && { saveDir: flags['save-dir'] }) };
122
+ const child = spawn(process.execPath, [daemon, JSON.stringify(opts)], { cwd: io.cwd, detached: true, stdio: ['ignore', log, log, 'ipc'] });
123
+ const msg = await new Promise((ok) => {
124
+ const timer = setTimeout(() => ok({ error: { code: 'session-unreachable', message: 'the session did not start in 60 s' } }), 60_000);
125
+ child.once('message', (m) => { clearTimeout(timer); ok(m); });
126
+ child.once('exit', (code) => { clearTimeout(timer); ok({ error: { code: 'session-unreachable', message: `the session process exited (code ${code}); see ${relative(io.cwd, logFile)}` } }); });
127
+ });
128
+ child.removeAllListeners();
129
+ if (child.connected)
130
+ child.disconnect();
131
+ child.unref();
132
+ if (msg.error) {
133
+ if (child.exitCode === null)
134
+ child.kill();
135
+ const { code, message, ...fields } = msg.error;
136
+ throw new CliError(code, message, fields);
137
+ }
138
+ return { ...(await callSession(msg.ready, 'status')), log: relative(io.cwd, logFile) };
139
+ },
140
+ human: (o) => `${statusLine(o)}\nnext: vibe session step 60 · vibe session inspect <entity> · vibe session stop`,
141
+ });
142
+ const listCmd = defineCommand({
143
+ name: 'session list',
144
+ summary: 'List the open sessions of this project (and forget dead ones)',
145
+ flags: {},
146
+ output: { sessions: 'open sessions: id, pid, scene, seed, startedAt' },
147
+ errors: {},
148
+ async run({ io }) {
149
+ return { sessions: listSessions(io.cwd).map(({ token: _t, port: _p, ...s }) => s) };
150
+ },
151
+ human: ({ sessions }) => (sessions.length ? sessions.map((s) => `${s.id} ${s.scene} seed ${s.seed} pid ${s.pid} since ${s.startedAt}`).join('\n') : 'no open sessions (vibe session start)'),
152
+ });
153
+ const parseValue = (raw) => {
154
+ try {
155
+ return JSON.parse(raw);
156
+ }
157
+ catch {
158
+ throw new CliError('usage', `value '${raw}' is not JSON`, { expected: 'true | false | a number | [x,y]' });
159
+ }
160
+ };
161
+ const readChanges = (file, cwd) => {
162
+ try {
163
+ return JSON.parse(readFileSync(resolve(cwd, file), 'utf8'));
164
+ }
165
+ catch (err) {
166
+ throw new CliError('input-invalid', `cannot read '${file}': ${err.message}`, { expected: 'a JSON array of { frame, action, value, player? }' });
167
+ }
168
+ };
169
+ export const SESSION_COMMANDS = [
170
+ start,
171
+ listCmd,
172
+ sessionCommand({ verb: 'status', summary: 'Show tick, revision, scene, seed, running/paused, state hash and the last world error', output: STATUS }),
173
+ sessionCommand({
174
+ verb: 'step',
175
+ summary: 'Advance a paused session by exactly N fixed ticks and count the events emitted',
176
+ positionals: [{ name: 'frames', doc: 'ticks to advance (default 1)' }],
177
+ mutating: true,
178
+ output: { ...STATUS, stepped: 'ticks advanced', events: 'count of each event name emitted in these ticks' },
179
+ errors: { 'session-running': 'the session is resumed; pause it first', 'session-revision-stale': 'the session changed since --revision', 'world-error': 'a system threw; source points at the game file' },
180
+ payload: (_f, [frames]) => ({ frames: frames === undefined ? 1 : Number(frames) }),
181
+ human: (o) => `${statusLine(o)}\nevents: ${Object.entries(o.events).map(([n, c]) => `${n} ${c}`).join(', ') || 'none'}`,
182
+ }),
183
+ sessionCommand({ verb: 'pause', summary: 'Stop real-time ticking (sessions start paused)', output: STATUS }),
184
+ sessionCommand({ verb: 'resume', summary: 'Tick in real time (tickRate per second) until pause; an error pauses it', mutating: true, output: STATUS, errors: { 'session-revision-stale': 'the session changed since --revision' } }),
185
+ sessionCommand({
186
+ verb: 'reset',
187
+ summary: 'Start the scene again at tick 0 (same seed and scene unless given)',
188
+ flags: { seed: { type: 'number', doc: 'new seed' }, scene: { type: 'string', doc: 'another scene' } },
189
+ mutating: true,
190
+ output: STATUS,
191
+ errors: { 'scene-not-found': 'the scene id is not registered', 'session-revision-stale': 'the session changed since --revision', 'world-error': 'the scene setup threw' },
192
+ payload: (f) => toPayload(f, ['seed', 'scene']),
193
+ }),
194
+ sessionCommand({
195
+ verb: 'input',
196
+ summary: 'Schedule input by tick: a value now (or --at), --press for one tick, --frames to hold then release, or --file with a recorded sequence',
197
+ positionals: [{ name: 'action', doc: 'action from defineInput (not with --file)' }, { name: 'value', doc: 'JSON value: true, 0.5, [1,0] (not with --press)' }],
198
+ flags: {
199
+ press: { type: 'boolean', default: false, doc: 'press a button for exactly one tick' },
200
+ frames: { type: 'number', doc: 'hold the value for N ticks, then release (false / 0 / [0,0])' },
201
+ at: { type: 'number', doc: 'tick to apply at (default: the next tick)' },
202
+ player: { type: 'string', doc: "player id (default 'local')" },
203
+ file: { type: 'string', doc: 'JSON file with [{ frame, action, value, player? }] (world.input.recorded() format)' },
204
+ },
205
+ mutating: true,
206
+ output: { ...HEAD, scheduled: 'changes scheduled: { frame, player, action, value }' },
207
+ errors: { 'input-invalid': 'unknown action, value of the wrong type, tick in the past or bad file', 'session-revision-stale': 'the session changed since --revision' },
208
+ payload(f, [action, value], cwd) {
209
+ if (f.file !== undefined)
210
+ return { changes: readChanges(f.file, cwd) };
211
+ if (action === undefined)
212
+ throw new CliError('usage', 'input needs an action (or --file)', { hint: 'vibe session input jump --press' });
213
+ return { action, ...(value !== undefined && { value: parseValue(value) }), ...(f.press ? { press: true } : {}), ...toPayload(f, ['frames', 'at', 'player']) };
214
+ },
215
+ human: (o) => `${head(o)}\n${o.scheduled.map((c) => `tick ${c.frame}: ${c.player} ${c.action} = ${JSON.stringify(c.value)}`).join('\n')}`,
216
+ }),
217
+ sessionCommand({
218
+ verb: 'query',
219
+ summary: 'List entity ids (spawn order) that have every given component, a page at a time',
220
+ flags: { with: { type: 'string', doc: 'comma-separated component ids (default: every entity)' }, limit: { type: 'number', default: 50, doc: 'page size' }, cursor: { type: 'string', doc: 'the next value of the previous page' } },
221
+ output: { ...HEAD, total: 'matching entities', entities: 'this page: { id, components }', next: 'cursor for the next page, or null' },
222
+ payload: (f) => toPayload(f, ['with', 'limit', 'cursor']),
223
+ human: (o) => `${head(o)} · ${o.total} entities\n${o.entities.map((e) => `${e.id} ${e.components.join(', ')}`).join('\n')}${o.next ? `\nmore: --cursor ${o.next}` : ''}`,
224
+ }),
225
+ sessionCommand({
226
+ verb: 'inspect',
227
+ summary: 'Show the component values of one entity',
228
+ positionals: [{ name: 'entity', doc: 'entity id', required: true }],
229
+ flags: { components: { type: 'string', doc: 'comma-separated component ids (default: all)' } },
230
+ output: { ...HEAD, entity: 'entity id', hidden: 'hidden by its scene/state', components: 'component id → value' },
231
+ errors: { 'entity-not-found': 'no entity with that id at this tick' },
232
+ payload(f, [entity]) {
233
+ if (entity === undefined)
234
+ throw new CliError('usage', 'inspect needs an entity id', { hint: 'vibe session query lists ids' });
235
+ return { entity, ...toPayload(f, ['components']) };
236
+ },
237
+ human: (o) => `${head(o)} · ${o.entity}${o.hidden ? ' (hidden)' : ''}\n${Object.entries(o.components).map(([c, v]) => `${c} ${JSON.stringify(v)}`).join('\n')}`,
238
+ }),
239
+ sessionCommand({
240
+ verb: 'events',
241
+ summary: 'Events emitted since a tick (physics contacts, input, game events), newest last',
242
+ flags: { since: { type: 'number', doc: 'from this tick (default 0)' }, filter: { type: 'string', doc: "comma-separated names; a trailing * matches a prefix ('physics.*')" }, limit: { type: 'number', default: 100, doc: 'at most this many (the newest)' } },
243
+ output: { ...HEAD, total: 'matching events in the session log', oldest: 'oldest tick still in the log (it keeps the last 5000 events)', events: '{ frame, name, payload }' },
244
+ payload: (f) => toPayload(f, ['since', 'filter', 'limit']),
245
+ human: (o) => `${head(o)} · ${o.total} events\n${o.events.map((e) => `@${e.frame} ${e.name} ${JSON.stringify(e.payload)}`).join('\n')}`,
246
+ }),
247
+ sessionCommand({
248
+ verb: 'state',
249
+ summary: 'Scene, active states, resources and the last recorded input changes',
250
+ flags: { inputs: { type: 'number', default: 20, doc: 'how many recorded input changes' } },
251
+ output: { ...HEAD, scene: 'active scene', states: 'active states', resources: 'resource id → inspect()', inputs: 'last recorded input changes (replayable with vibe run --inputs)' },
252
+ payload: (f) => toPayload(f, ['inputs']),
253
+ human: (o) => `${head(o)} · ${o.scene} · states ${o.states.join(', ') || 'none'}\nresources ${JSON.stringify(o.resources)}\ninputs ${JSON.stringify(o.inputs)}`,
254
+ }),
255
+ sessionCommand({ verb: 'stop', summary: 'Close the session and its process', output: { session: 'session id', stopped: 'true' }, human: (o) => `${o.session} stopped` }),
256
+ ];
@@ -0,0 +1,15 @@
1
+ export interface TsError {
2
+ file: string;
3
+ line: number;
4
+ column: number;
5
+ code: string;
6
+ message: string;
7
+ }
8
+ export type TypecheckResult = {
9
+ ran: true;
10
+ errors: TsError[];
11
+ } | {
12
+ ran: false;
13
+ reason: string;
14
+ };
15
+ export declare function typecheck(root: string): Promise<TypecheckResult>;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Typecheck do projeto para o `vibe check` (#42): roda o `tsc` do próprio
3
+ * projeto e devolve cada erro com arquivo, linha e coluna. Sem `tsconfig.json`,
4
+ * usa um gerado em `.vibe/` com as regras da engine (as mesmas que o Node
5
+ * aceita ao rodar `.ts` direto). Sem `typescript` instalado, não roda e diz por quê.
6
+ */
7
+ import { execFile } from 'node:child_process';
8
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
9
+ import { createRequire } from 'node:module';
10
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
11
+ export async function typecheck(root) {
12
+ const req = createRequire(join(root, 'package.json'));
13
+ let tsc;
14
+ try {
15
+ tsc = join(dirname(req.resolve('typescript/package.json')), 'bin', 'tsc');
16
+ }
17
+ catch {
18
+ return { ran: false, reason: 'typescript is not installed in this project (add typescript and @types/node to devDependencies)' };
19
+ }
20
+ const project = existsSync(join(root, 'tsconfig.json')) ? join(root, 'tsconfig.json') : generated(root, req);
21
+ const out = await new Promise((ok) => {
22
+ execFile(process.execPath, [tsc, '--noEmit', '--pretty', 'false', '-p', project], { cwd: root, timeout: 120_000, maxBuffer: 16 << 20 }, (_err, stdout) => ok(String(stdout)));
23
+ });
24
+ const cfgDir = dirname(project);
25
+ const errors = [];
26
+ for (const line of out.split('\n')) {
27
+ const global = /^error (TS\d+): (.*)$/.exec(line.trim()); // erro sem posição (tsconfig inválido, opção desconhecida)
28
+ if (global)
29
+ errors.push({ file: relative(root, project), line: 1, column: 1, code: global[1], message: global[2] });
30
+ const m = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/.exec(line.trim());
31
+ if (!m)
32
+ continue;
33
+ const abs = isAbsolute(m[1]) ? m[1] : resolve(root, m[1]);
34
+ const file = relative(root, existsSync(abs) ? abs : resolve(cfgDir, m[1]));
35
+ if (file.startsWith('..') || file.includes('node_modules'))
36
+ continue; // só o código do jogo: a engine (link no monorepo) tem o próprio typecheck
37
+ errors.push({ file, line: Number(m[2]), column: Number(m[3]), code: m[4], message: m[5] });
38
+ }
39
+ return { ran: true, errors };
40
+ }
41
+ function generated(root, req) {
42
+ const dir = join(root, '.vibe');
43
+ mkdirSync(dir, { recursive: true });
44
+ let node = true;
45
+ try {
46
+ req.resolve('@types/node/package.json');
47
+ }
48
+ catch {
49
+ node = false;
50
+ }
51
+ const file = join(dir, 'tsconfig.check.json');
52
+ writeFileSync(file, JSON.stringify({
53
+ compilerOptions: {
54
+ target: 'es2024',
55
+ module: 'nodenext',
56
+ moduleResolution: 'nodenext',
57
+ strict: true,
58
+ verbatimModuleSyntax: true,
59
+ erasableSyntaxOnly: true, // o Node roda .ts só apagando tipos: enum/namespace quebrariam lá
60
+ allowImportingTsExtensions: true,
61
+ noEmit: true,
62
+ skipLibCheck: true,
63
+ types: node ? ['node'] : [],
64
+ },
65
+ include: ['../src', '../tests', '../*.ts'],
66
+ }, null, 2));
67
+ return file;
68
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibe-engine/cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "vibe CLI: create, dev, run --headless, test, check, build and serve vibe-engine games",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "repository": {
@@ -35,12 +35,12 @@
35
35
  }
36
36
  },
37
37
  "dependencies": {
38
- "@vibe-engine/core": "0.1.0",
38
+ "@vibe-engine/core": "0.1.2",
39
39
  "vite": "8.4.0"
40
40
  },
41
41
  "devDependencies": {
42
- "@vibe-engine/2d": "0.1.0",
43
- "@vibe-engine/net": "0.1.0"
42
+ "@vibe-engine/2d": "0.1.2",
43
+ "@vibe-engine/net": "0.1.2"
44
44
  },
45
45
  "files": [
46
46
  "dist",
@@ -86,6 +86,7 @@ Build levels as text maps (`*.map.ts` with `defineMap`): one character per cell,
86
86
  - UI look lives in `vibe.config.ts` → `ui: { font, color, styles }`: named styles with `hover`/`pressed`/`focused`/`disabled` variants. Buttons use `button` and texts use `text` automatically; apply others with `UiStyle({ use: 'panel title' })`. For 9-slice skins, set `skin: 'ui/button'` and put `{ "slice": 3 }` in `assets/ui/button.meta.json`. Fonts go in `assets/fonts/*.woff2|ttf`, referenced by id (`font: 'fonts/pixel'`). The style is visual only; test the state, not the look.
87
87
  - **Text fields and world labels:** `UiInput({ value, placeholder, maxLength })` is a text field whose text is state; read `UiInput.value`, react to `UiChanged` / `UiSubmitted` (Enter), and test with `world.ui.type('menu/name', 'Ana')` + `world.ui.submit('menu/name')` (typed keys never reach game input). `Label2D({ text, offset, owner })` / `Label3D` draws text that follows the entity (names, tags); it's state, so assert the text. In multiplayer, pass a small `profile` with the join (`NetJoinRoom({ type, profile: { name } })`), declare `profile: { name: t.string({ maxLength: 16 }) }` in the room, and read it in `NetPlayerJoined { player, profile }` (the server cleans and validates it).
88
88
  - **Showing a value** (HUD, labels): derive it from state every tick (a system in `update`, or `bindText`). It can never go stale, whatever changed the state.
89
+ - **Multiplayer entities owned by a player** (fighter, gun, their bullets): add `NetOwner({ player })` from `@vibe-engine/net`. The owner's client predicts them; every other client draws them ~100 ms in the past, sliding between real server positions (interpolation), so remote players never jitter.
89
90
  - **Instant hits** (hitscan gun, knife, punch, explosion, line of sight): `raycast(world, { from, dir, range, by, ignore, filter })` and `overlap(world, { at, radius, dir?, angle?, by })` from `@vibe-engine/2d` (`raycast3D`/`overlap3D` in 3D). They read components, so call them inside a system. Pass `by: playerId` when a player's action does it: in multiplayer the server then accepts what that player saw on screen, within limits (lag compensation; `net.lagCompensation` in `vibe.config.ts`, `false` turns it off). Leave `by` out for things nobody aims (explosions, AI sight).
90
91
  - **Shaders** (GLSL ES 3.0): `SpriteShader({ shader: 'flash' })` on a sprite, `PostEffect({ shader: 'vignette' })` on any entity for a full-screen pass, `Mesh({ material: 'toon' })` / `MeshShader` in 3D. Presets: `flash`, `outline`, `dissolve`, `palette`, `crt`, `bloom`, `shockwave`, `vignette`, `toon`; your own go in `*.shader.ts` (`defineShader('id', { fragment, uniforms: { amount: t.number() } })`). Systems write `uniforms` (state, testable headless); `time` comes for free. `vibe check` reports unknown shader ids and bad uniforms; compile errors point at file and line.
91
92
  - **Destructible scenery** (2D): `destroyTiles(mapEntity, { x, y, radius }, emit)` from `@vibe-engine/2d` removes the tiles in a circle, emits `TilesDestroyed` with the cells, and only the touched chunks are rebuilt. Layers named in `Tilemap.indestructible` (`indestructible: true` in `tilemapFromGrid`) are kept.
@@ -129,12 +130,11 @@ Use the `vibe` CLI (`pnpm exec vibe ...`). Add `--json` for structured output: e
129
130
  | understand the project | `vibe info [--component Player]` |
130
131
  | read engine docs for **this** version | `vibe docs search "<term>"`, `vibe docs show <topic>` |
131
132
  | run once without a screen | `vibe run --headless --scene <id> --frames N [--inputs file]` |
132
- | drive a live session | `vibe session start --scene <id> --seed 1 --headless` → `step <s> N`, `input <s> jump --press`, `pause`, `stop` |
133
- | inspect state | `vibe session inspect <s> <entity> [--components A,B]`, `vibe session query <s> ...`, `vibe session events <s> --since N` |
133
+ | drive a live session (paused at tick 0, background process) | `vibe session start [--scene <id>] [--seed 1]` → `vibe session step 60`, `vibe session input jump --press` (or `move 1 --frames 30`, `--at <tick>`, `--file inputs.json`), `reset`, `resume`/`pause`, `stop`. With several sessions open, add `--session <id>`; `--revision <n>` refuses to act on a state you have not seen |
134
+ | inspect a live session | `vibe session status`, `vibe session inspect <entity> [--components A,B]`, `vibe session query --with A,B`, `vibe session events --since N --filter 'physics.*'`, `vibe session state` |
134
135
  | test | `vibe test [filter] [--name <regex>]` |
135
- | see the screen | `vibe session screenshot <s>` (needs a renderer) |
136
136
  | replay a run | `vibe replay <runId>` |
137
- | check scenes, ids and asset references | `vibe check` |
137
+ | check TypeScript errors (file:line:column), scenes, ids and asset references | `vibe check` (`--no-types` skips the typecheck) |
138
138
  | list assets (id = path under `assets/` without extension) | `vibe assets` |
139
139
  | see a level with coordinates / validate all levels | `vibe map show <id>`, `vibe map check` |
140
140
  | open in the browser (localhost; editing `src/` restarts the session) | `vibe dev [--port 5173]` |
@@ -96,7 +96,7 @@ test('3D: same seed and inputs give the same hash (deterministic Rapier 3D)', as
96
96
  });
97
97
 
98
98
  test('vibe run --headless --json on the 3D template', () => {
99
- const bin = fileURLToPath(import.meta.resolve('@vibe-engine/cli').replace(/index\.ts$/, 'bin.ts'));
99
+ const bin = fileURLToPath(import.meta.resolve('@vibe-engine/cli').replace(/index\.(ts|js)$/, 'bin.$1')); // src no checkout da engine, dist instalado do npm
100
100
  const out = JSON.parse(execFileSync(process.execPath, [bin, 'run', '--headless', '--frames', '60', '--entities', 'player', '--json'], { cwd: root, encoding: 'utf8' }));
101
101
  assert.equal(out.scene, 'arena');
102
102
  assert.ok('Grounded3D' in out.entities.player && 'Transform3D' in out.entities.player);
@@ -86,6 +86,7 @@ Build levels as text maps (`*.map.ts` with `defineMap`): one character per cell,
86
86
  - UI look lives in `vibe.config.ts` → `ui: { font, color, styles }`: named styles with `hover`/`pressed`/`focused`/`disabled` variants. Buttons use `button` and texts use `text` automatically; apply others with `UiStyle({ use: 'panel title' })`. For 9-slice skins, set `skin: 'ui/button'` and put `{ "slice": 3 }` in `assets/ui/button.meta.json`. Fonts go in `assets/fonts/*.woff2|ttf`, referenced by id (`font: 'fonts/pixel'`). The style is visual only; test the state, not the look.
87
87
  - **Text fields and world labels:** `UiInput({ value, placeholder, maxLength })` is a text field whose text is state; read `UiInput.value`, react to `UiChanged` / `UiSubmitted` (Enter), and test with `world.ui.type('menu/name', 'Ana')` + `world.ui.submit('menu/name')` (typed keys never reach game input). `Label2D({ text, offset, owner })` / `Label3D` draws text that follows the entity (names, tags); it's state, so assert the text. In multiplayer, pass a small `profile` with the join (`NetJoinRoom({ type, profile: { name } })`), declare `profile: { name: t.string({ maxLength: 16 }) }` in the room, and read it in `NetPlayerJoined { player, profile }` (the server cleans and validates it).
88
88
  - **Showing a value** (HUD, labels): derive it from state every tick (a system in `update`, or `bindText`). It can never go stale, whatever changed the state.
89
+ - **Multiplayer entities owned by a player** (fighter, gun, their bullets): add `NetOwner({ player })` from `@vibe-engine/net`. The owner's client predicts them; every other client draws them ~100 ms in the past, sliding between real server positions (interpolation), so remote players never jitter.
89
90
  - **Instant hits** (hitscan gun, knife, punch, explosion, line of sight): `raycast(world, { from, dir, range, by, ignore, filter })` and `overlap(world, { at, radius, dir?, angle?, by })` from `@vibe-engine/2d` (`raycast3D`/`overlap3D` in 3D). They read components, so call them inside a system. Pass `by: playerId` when a player's action does it: in multiplayer the server then accepts what that player saw on screen, within limits (lag compensation; `net.lagCompensation` in `vibe.config.ts`, `false` turns it off). Leave `by` out for things nobody aims (explosions, AI sight).
90
91
  - **Shaders** (GLSL ES 3.0): `SpriteShader({ shader: 'flash' })` on a sprite, `PostEffect({ shader: 'vignette' })` on any entity for a full-screen pass, `Mesh({ material: 'toon' })` / `MeshShader` in 3D. Presets: `flash`, `outline`, `dissolve`, `palette`, `crt`, `bloom`, `shockwave`, `vignette`, `toon`; your own go in `*.shader.ts` (`defineShader('id', { fragment, uniforms: { amount: t.number() } })`). Systems write `uniforms` (state, testable headless); `time` comes for free. `vibe check` reports unknown shader ids and bad uniforms; compile errors point at file and line.
91
92
  - **Destructible scenery** (2D): `destroyTiles(mapEntity, { x, y, radius }, emit)` from `@vibe-engine/2d` removes the tiles in a circle, emits `TilesDestroyed` with the cells, and only the touched chunks are rebuilt. Layers named in `Tilemap.indestructible` (`indestructible: true` in `tilemapFromGrid`) are kept.
@@ -129,12 +130,11 @@ Use the `vibe` CLI (`pnpm exec vibe ...`). Add `--json` for structured output: e
129
130
  | understand the project | `vibe info [--component Player]` |
130
131
  | read engine docs for **this** version | `vibe docs search "<term>"`, `vibe docs show <topic>` |
131
132
  | run once without a screen | `vibe run --headless --scene <id> --frames N [--inputs file]` |
132
- | drive a live session | `vibe session start --scene <id> --seed 1 --headless` → `step <s> N`, `input <s> jump --press`, `pause`, `stop` |
133
- | inspect state | `vibe session inspect <s> <entity> [--components A,B]`, `vibe session query <s> ...`, `vibe session events <s> --since N` |
133
+ | drive a live session (paused at tick 0, background process) | `vibe session start [--scene <id>] [--seed 1]` → `vibe session step 60`, `vibe session input jump --press` (or `move 1 --frames 30`, `--at <tick>`, `--file inputs.json`), `reset`, `resume`/`pause`, `stop`. With several sessions open, add `--session <id>`; `--revision <n>` refuses to act on a state you have not seen |
134
+ | inspect a live session | `vibe session status`, `vibe session inspect <entity> [--components A,B]`, `vibe session query --with A,B`, `vibe session events --since N --filter 'physics.*'`, `vibe session state` |
134
135
  | test | `vibe test [filter] [--name <regex>]` |
135
- | see the screen | `vibe session screenshot <s>` (needs a renderer) |
136
136
  | replay a run | `vibe replay <runId>` |
137
- | check scenes, ids and asset references | `vibe check` |
137
+ | check TypeScript errors (file:line:column), scenes, ids and asset references | `vibe check` (`--no-types` skips the typecheck) |
138
138
  | list assets (id = path under `assets/` without extension) | `vibe assets` |
139
139
  | see a level with coordinates / validate all levels | `vibe map show <id>`, `vibe map check` |
140
140
  | open in the browser (localhost; editing `src/` restarts the session) | `vibe dev [--port 5173]` |
@@ -485,7 +485,7 @@ test('same seed and inputs give equal snapshots (replay of a recording)', async
485
485
  });
486
486
 
487
487
  test('vibe run --headless --json works on the template', () => {
488
- const bin = fileURLToPath(import.meta.resolve('@vibe-engine/cli').replace(/index\.ts$/, 'bin.ts'));
488
+ const bin = fileURLToPath(import.meta.resolve('@vibe-engine/cli').replace(/index\.(ts|js)$/, 'bin.$1')); // src no checkout da engine, dist instalado do npm
489
489
  const out = JSON.parse(execFileSync(process.execPath, [bin, 'run', '--headless', '--scene', 'level-1', '--frames', '60', '--entities', 'player', '--json'], { cwd: root, encoding: 'utf8' }));
490
490
  assert.equal(out.scene, 'level-1');
491
491
  assert.ok('Grounded' in out.entities.player && 'Transform2D' in out.entities.player);
@@ -86,6 +86,7 @@ Build levels as text maps (`*.map.ts` with `defineMap`): one character per cell,
86
86
  - UI look lives in `vibe.config.ts` → `ui: { font, color, styles }`: named styles with `hover`/`pressed`/`focused`/`disabled` variants. Buttons use `button` and texts use `text` automatically; apply others with `UiStyle({ use: 'panel title' })`. For 9-slice skins, set `skin: 'ui/button'` and put `{ "slice": 3 }` in `assets/ui/button.meta.json`. Fonts go in `assets/fonts/*.woff2|ttf`, referenced by id (`font: 'fonts/pixel'`). The style is visual only; test the state, not the look.
87
87
  - **Text fields and world labels:** `UiInput({ value, placeholder, maxLength })` is a text field whose text is state; read `UiInput.value`, react to `UiChanged` / `UiSubmitted` (Enter), and test with `world.ui.type('menu/name', 'Ana')` + `world.ui.submit('menu/name')` (typed keys never reach game input). `Label2D({ text, offset, owner })` / `Label3D` draws text that follows the entity (names, tags); it's state, so assert the text. In multiplayer, pass a small `profile` with the join (`NetJoinRoom({ type, profile: { name } })`), declare `profile: { name: t.string({ maxLength: 16 }) }` in the room, and read it in `NetPlayerJoined { player, profile }` (the server cleans and validates it).
88
88
  - **Showing a value** (HUD, labels): derive it from state every tick (a system in `update`, or `bindText`). It can never go stale, whatever changed the state.
89
+ - **Multiplayer entities owned by a player** (fighter, gun, their bullets): add `NetOwner({ player })` from `@vibe-engine/net`. The owner's client predicts them; every other client draws them ~100 ms in the past, sliding between real server positions (interpolation), so remote players never jitter.
89
90
  - **Instant hits** (hitscan gun, knife, punch, explosion, line of sight): `raycast(world, { from, dir, range, by, ignore, filter })` and `overlap(world, { at, radius, dir?, angle?, by })` from `@vibe-engine/2d` (`raycast3D`/`overlap3D` in 3D). They read components, so call them inside a system. Pass `by: playerId` when a player's action does it: in multiplayer the server then accepts what that player saw on screen, within limits (lag compensation; `net.lagCompensation` in `vibe.config.ts`, `false` turns it off). Leave `by` out for things nobody aims (explosions, AI sight).
90
91
  - **Shaders** (GLSL ES 3.0): `SpriteShader({ shader: 'flash' })` on a sprite, `PostEffect({ shader: 'vignette' })` on any entity for a full-screen pass, `Mesh({ material: 'toon' })` / `MeshShader` in 3D. Presets: `flash`, `outline`, `dissolve`, `palette`, `crt`, `bloom`, `shockwave`, `vignette`, `toon`; your own go in `*.shader.ts` (`defineShader('id', { fragment, uniforms: { amount: t.number() } })`). Systems write `uniforms` (state, testable headless); `time` comes for free. `vibe check` reports unknown shader ids and bad uniforms; compile errors point at file and line.
91
92
  - **Destructible scenery** (2D): `destroyTiles(mapEntity, { x, y, radius }, emit)` from `@vibe-engine/2d` removes the tiles in a circle, emits `TilesDestroyed` with the cells, and only the touched chunks are rebuilt. Layers named in `Tilemap.indestructible` (`indestructible: true` in `tilemapFromGrid`) are kept.
@@ -129,12 +130,11 @@ Use the `vibe` CLI (`pnpm exec vibe ...`). Add `--json` for structured output: e
129
130
  | understand the project | `vibe info [--component Player]` |
130
131
  | read engine docs for **this** version | `vibe docs search "<term>"`, `vibe docs show <topic>` |
131
132
  | run once without a screen | `vibe run --headless --scene <id> --frames N [--inputs file]` |
132
- | drive a live session | `vibe session start --scene <id> --seed 1 --headless` → `step <s> N`, `input <s> jump --press`, `pause`, `stop` |
133
- | inspect state | `vibe session inspect <s> <entity> [--components A,B]`, `vibe session query <s> ...`, `vibe session events <s> --since N` |
133
+ | drive a live session (paused at tick 0, background process) | `vibe session start [--scene <id>] [--seed 1]` → `vibe session step 60`, `vibe session input jump --press` (or `move 1 --frames 30`, `--at <tick>`, `--file inputs.json`), `reset`, `resume`/`pause`, `stop`. With several sessions open, add `--session <id>`; `--revision <n>` refuses to act on a state you have not seen |
134
+ | inspect a live session | `vibe session status`, `vibe session inspect <entity> [--components A,B]`, `vibe session query --with A,B`, `vibe session events --since N --filter 'physics.*'`, `vibe session state` |
134
135
  | test | `vibe test [filter] [--name <regex>]` |
135
- | see the screen | `vibe session screenshot <s>` (needs a renderer) |
136
136
  | replay a run | `vibe replay <runId>` |
137
- | check scenes, ids and asset references | `vibe check` |
137
+ | check TypeScript errors (file:line:column), scenes, ids and asset references | `vibe check` (`--no-types` skips the typecheck) |
138
138
  | list assets (id = path under `assets/` without extension) | `vibe assets` |
139
139
  | see a level with coordinates / validate all levels | `vibe map show <id>`, `vibe map check` |
140
140
  | open in the browser (localhost; editing `src/` restarts the session) | `vibe dev [--port 5173]` |
@@ -156,15 +156,16 @@ The full reference ships **with the installed engine version**, in `node_modules
156
156
  <!-- vibe-engine:end -->
157
157
  ## This project
158
158
 
159
- Online PvP in arenas of up to 6 players (three are always open in the lobby; more can be created there): players run, jump and shoot where the mouse points. Q cycles pistol (bullets) → rifle (instant shot, 2 damage, slower) → bazooka (a rocket that explodes on walls and fighters: it blows a hole in the ground and takes 3 hp in a 30 px radius), and K or the right mouse button swings a knife (short arc, 2 damage). A bullet takes 1 of 5 hp; every hit knocks back; at 0 the player dies, the shooter scores a kill, and the dead player respawns after 2 s with a short shield. Falling off the map also kills (credit to the last hitter).
159
+ Online PvP in arenas of up to 6 players (three are always open in the lobby; more can be created there): players run, jump and shoot where the mouse points. Q swaps pistol (bullets) ↔ rifle (instant shot, 2 damage, slower), and K or the right mouse button swings a knife (short arc, 2 damage). A bullet takes 1 of 5 hp; every hit knocks back; at 0 the player dies, the shooter scores a kill, and the dead player respawns after 2 s with a short shield. Falling off the map also kills (credit to the last hitter).
160
160
 
161
161
  **How multiplayer works here.** The server is authoritative: it runs this same game headless (`vibe serve`; `vibe dev` starts it next to the browser preview and restarts it when code changes). Each browser tab is a client: it sends only input, predicts its own moves on the same tick, and reconciles with the server snapshot (restore + re-simulate). So:
162
162
 
163
163
  - Game rules are **shared** code and run on both sides. Read input with `inputOf(owner)`, never `input`: every fighter belongs to a player id (`p1`, `p2`...).
164
164
  - Players appear through the `NetPlayerJoined` event (`src/listeners/players.listener.ts`), which spawns `fighter-<player>` and `gun-<player>`; `NetPlayerLeft` removes them. The event carries the player's `profile` (the name typed in the lobby, already cleaned by the server): it becomes `Fighter.name` (no name: the color) and a `Label2D` above the fighter (the local player's own label is drawn with swapped colors).
165
165
  - Camera and UI are local to each client (`net: 'local'` components are not replicated). `view.local` points the camera at `fighter-<localPlayer>` and writes the small top-right HUD (`hud/hp`: health + weapon, `hud/board`: kill limit and scoreboard). Controls are listed in the lobby. `localPlayer` is in the system context.
166
- - Ids created during play must be the same on client and server: bullets are `bullet-<player>-<n>`, rockets `rocket-<player>-<n>` and rifle tracers `tracer-<player>-<n>`, from a counter in `Gun`.
167
- - Rifle and knife use `raycast`/`overlap` with `by: gun.owner`: the server accepts what that player saw (lag compensation), so a hit on a target that just turned around still counts, within limits. Bullets and rockets are simulated on the server and need nothing extra; the explosion uses `overlap` without `by` (nobody aims it).
166
+ - Ids created during play must be the same on client and server: bullets are `bullet-<player>-<n>` and rifle tracers `tracer-<player>-<n>`, from a counter in `Gun`.
167
+ - Rifle and knife use `raycast`/`overlap` with `by: gun.owner`: the server accepts what that player saw (lag compensation), so a hit on a target that just turned around still counts, within limits. Bullets are simulated on the server and need nothing extra.
168
+ - Fighters, guns, bullets and tracers carry `NetOwner({ player })`: your own are predicted; other players' are drawn ~100 ms in the past, interpolated between server snapshots (smooth, never corrected).
168
169
  - Health, kills and deaths are decided by the server; a client that edits them locally is overwritten by the next snapshot.
169
170
 
170
171
  Files:
@@ -173,9 +174,9 @@ Files:
173
174
  - `src/scenes/lobby.scene.ts` + `src/systems/lobby.system.ts` + `src/ui/lobby.ui.ts`: the lobby is game code. A name field (`lobby/name`, a `UiInput`) is prefilled from `src/saves/player.save.ts` and saved on every change; Enter joins quickly; every join sends `profile: { name }`. It asks with events (`emit(NetListRooms, {})` every 2 s, `emit(NetJoinRoom, { room } | { type } | { create: { type, name, rules } }, with profile)`) and gets answers as events (`NetRoomsListed`, `NetJoined`, `NetFailed` with the reason, such as a full room or invalid rules). Buttons are `lobby/rooms/<room-id>`; update existing entities instead of despawning and spawning the same id in one step.
174
175
  - Connection: a dropped player keeps their seat for 10 s and comes back as the same player (`NetPlayerAway` / `NetPlayerBack` on the server, `NetConnection` on the client, shown in the HUD from the local `connection` entity). Esc (`leave`, a `local` action) emits `NetLeaveRoom`: the seat is freed and the client goes back to the lobby. The session is kept in the tab, so a reload returns to the same room.
175
176
  - `match.rules`: reaching `killLimit` sets `Arena.status = 'over'` with the winner, and a new match starts 4 s later.
176
- - `src/maps/arena.map.ts`: the arena as text; `S` cells are spawn points (player `pN` uses the (N-1)th); `%` is bedrock, a layer marked `indestructible` in `src/level/build.ts`, so explosions never open the border or the floor. `src/level/build.ts` builds the `Tilemap`, camera and HUD.
177
- - `src/systems/`: `fighter.controller` (platformer movement with game feel, squash & stretch), `gun.control` (aim, weapon swap, fire rate, recoil, bullets, rockets, rifle raycast, knife arc), `gun.tracer-fade`, `gun.bullet-lifetime`, `gun.rocket-lifetime` (a rocket explodes at the end of its range), `combat.hits` (bullet × fighter, bullet × walls, rocket × either; damage, knockback, death, score and `explode` live in `src/rules/damage.ts`, shared by bullet, rifle, knife and bazooka; `explode` calls `destroyTiles` and the destroyed cells reach the clients in the snapshot), `fighter.respawn` (falling off, respawn, shield blink), `view.local` (camera, HUD, scoreboard and win banner with player names).
178
- - `src/listeners/effects.listener.ts`: sound, particles, camera shake and hit-stop for jumps, shots, rockets, explosions (dirt from each destroyed tile via `TilesDestroyed`), hits, deaths and respawns (shake only when the local player is involved). Sounds are positioned (`at:`), so an enemy shot off to the left is heard on the left.
177
+ - `src/maps/arena.map.ts`: the arena as text; `S` cells are spawn points (player `pN` uses the (N-1)th); `%` is the rock border and floor (its own tile layer). `src/level/build.ts` builds the `Tilemap`, camera and HUD.
178
+ - `src/systems/`: `fighter.controller` (platformer movement with game feel, squash & stretch), `gun.control` (aim, weapon swap, fire rate, recoil, bullets, rifle raycast, knife arc), `gun.tracer-fade`, `gun.bullet-lifetime`, `combat.hits` (bullet × fighter, bullet × walls; damage, knockback, death and score live in `src/rules/damage.ts`, shared by bullet, rifle and knife), `fighter.respawn` (falling off, respawn, shield blink), `view.local` (camera, HUD, scoreboard and win banner with player names).
179
+ - `src/listeners/effects.listener.ts`: sound, particles, camera shake and hit-stop for jumps, shots, knife swings, hits, deaths and respawns (shake only when the local player is involved). Sounds are positioned (`at:`), so an enemy shot off to the left is heard on the left.
179
180
  - `assets/`: Kenney Pixel Platformer sheets (CC0) with one animation set per color (`green-walk`, `blue-idle`...); sounds generated by code (CC0).
180
- - `tests/pvp.test.ts`: 1 server + 2 clients over an emulated network (100 ms RTT), headless: join and spawn, shooting until a kill, score, respawn, authority, rifle and knife hits, bazooka (hole in the ground, bedrock kept, the target falls in, both clients see the hole, blast damage), player names (typed in the lobby, saved, sent as profile, on the fighters and both scoreboards; no name falls back to the color). Run `pnpm test` after every change.
181
+ - `tests/pvp.test.ts`: 1 server + 2 clients over an emulated network (100 ms RTT), headless: join and spawn, shooting until a kill, score, respawn, authority, rifle and knife hits, player names (typed in the lobby, saved, sent as profile, on the fighters and both scoreboards; no name falls back to the color). Run `pnpm test` after every change.
181
182
  - Play: `pnpm dev`, open the URL in two tabs (or two machines with `vibe serve --host 0.0.0.0` and `net.url`).
@@ -1,6 +1,6 @@
1
1
  # shooter-2d-pvp
2
2
 
3
- Template multiplayer da vibe-engine: arena 2D de plataforma com tiro, até 4 jogadores por sala, com lobby e salas com regras próprias (abates para vencer, tempo de respawn, gravidade). O servidor é autoritativo, o cliente prediz e reconcilia, e o game feel vem do platformer (coyote time, jump buffer, recoil, knockback, shake, hit-stop, partículas e sons).
3
+ Template multiplayer da vibe-engine: arena 2D de plataforma com tiro, até 6 jogadores por sala, com lobby e salas com regras próprias (abates para vencer, tempo de respawn, gravidade). O servidor é autoritativo, o cliente prediz e reconcilia, e o game feel vem do platformer (coyote time, jump buffer, recoil, knockback, shake, hit-stop, partículas e sons).
4
4
 
5
5
  ```sh
6
6
  pnpm dev # vibe dev: browser + servidor do jogo; abra em duas abas para jogar contra você mesmo
@@ -3,18 +3,15 @@ import { defineComponent, t } from '@vibe-engine/core';
3
3
  /**
4
4
  * A arma de um lutador (`gun-<player>`). Segurar o tiro dispara a cada `rate` ticks.
5
5
  * `pistol` atira balas (simuladas no servidor); `rifle` é tiro instantâneo (raycast com
6
- * lag compensation: vale o que o atirador viu); `bazooka` atira foguetes (simulados no servidor)
7
- * que explodem no cenário: abrem buraco no chão (`destroyTiles`) e ferem em área. A faca é de todo lutador (`knifeCooldown`).
6
+ * lag compensation: vale o que o atirador viu). A faca é de todo lutador (`knifeCooldown`).
8
7
  */
9
8
  export const Gun = defineComponent('Gun', {
10
9
  owner: t.string({ doc: 'id do jogador' }),
11
- weapon: t.enum(['pistol', 'rifle', 'bazooka'] as const, { default: 'pistol' }),
10
+ weapon: t.enum(['pistol', 'rifle'] as const, { default: 'pistol' }),
12
11
  rate: t.int({ default: 12, min: 1, doc: 'pistola' }),
13
12
  rifleRate: t.int({ default: 45, min: 1 }),
14
13
  rifleRange: t.number({ default: 420, unit: 'px' }),
15
14
  rifleDamage: t.int({ default: 2, min: 1 }),
16
- bazookaRate: t.int({ default: 70, min: 1 }),
17
- rocketSpeed: t.number({ default: 240, unit: 'px/s' }),
18
15
  knifeCooldown: t.int({ min: 0 }),
19
16
  cooldown: t.int({ min: 0 }),
20
17
  bulletSpeed: t.number({ default: 340, unit: 'px/s' }),
@@ -33,14 +30,6 @@ export const Bullet = defineComponent('Bullet', {
33
30
  damage: t.int({ default: 1, min: 1 }),
34
31
  });
35
32
 
36
- /** Foguete da bazuca (`rocket-<player>-<n>`): explode ao tocar cenário ou lutador, ou quando `ttl` acaba. */
37
- export const Rocket = defineComponent('Rocket', {
38
- owner: t.string(),
39
- ttl: t.int({ default: 90, min: 0 }),
40
- radius: t.number({ default: 30, unit: 'px', doc: 'raio da explosão (tiles e dano)' }),
41
- damage: t.int({ default: 3, min: 1 }),
42
- });
43
-
44
33
  /** A partida (entidade `arena`): tamanho, regras da sala e estado. */
45
34
  export const Arena = defineComponent('Arena', {
46
35
  width: t.number({ unit: 'px' }),
@@ -11,5 +11,3 @@ export const RifleFired = defineEvent<{ gun: string; from: { x: number; y: numbe
11
11
  export const KnifeSwung = defineEvent<{ fighter: string; x: number; y: number; dir: { x: number; y: number }; hits: number }>('knife.swung');
12
12
  export const WeaponSwapped = defineEvent<{ gun: string; weapon: string }>('gun.swapped');
13
13
  export const BulletImpact = defineEvent<{ x: number; y: number }>('bullet.impact');
14
- export const RocketFired = defineEvent<{ gun: string; rocket: string; dir: { x: number; y: number } }>('gun.rocket-fired');
15
- export const RocketExploded = defineEvent<{ rocket: string; owner: string; x: number; y: number; radius: number; tiles: number; hits: number }>('rocket.exploded');
@@ -32,8 +32,8 @@ export function buildArena({ spawn, params }: SceneSetupContext, map: GridMap):
32
32
  }),
33
33
  },
34
34
  planks: { match: 'plank', collides: true, tiles: edges({ single: 47, left: 48, mid: 49, right: 50 }) },
35
- // Borda e fundo: `destroyTiles` (bazuca) não remove esta camada.
36
- bedrock: { match: 'bedrock', collides: true, indestructible: true, tiles: 29 },
35
+ // Borda e fundo.
36
+ bedrock: { match: 'bedrock', collides: true, tiles: 29 },
37
37
  },
38
38
  }))]);
39
39
  const size = { width: map.width * TILE, height: map.height * TILE };