@vibe-engine/net 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.
package/dist/delta.js ADDED
@@ -0,0 +1,124 @@
1
+ const same = (a, b) => a === b || JSON.stringify(a) === JSON.stringify(b);
2
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
3
+ /** Junta em `out` as folhas diferentes entre `a` e `b` (mesma forma: desce; forma diferente: a folha é o valor novo inteiro). */
4
+ function leaves(a, b, path, out) {
5
+ if (a === b)
6
+ return;
7
+ if (Array.isArray(a) && Array.isArray(b) && a.length === b.length) {
8
+ for (let i = 0; i < a.length; i++) {
9
+ path.push(i);
10
+ leaves(a[i], b[i], path, out);
11
+ path.pop();
12
+ }
13
+ return;
14
+ }
15
+ if (isRecord(a) && isRecord(b) && Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((k) => k in b)) {
16
+ for (const k of Object.keys(b)) {
17
+ path.push(k);
18
+ leaves(a[k], b[k], path, out);
19
+ path.pop();
20
+ }
21
+ return;
22
+ }
23
+ if (!same(a, b))
24
+ out.push([[...path], b]);
25
+ }
26
+ export function diffState(baseTick, base, next) {
27
+ const before = new Map(base.entities);
28
+ const nowIds = new Set(next.entities.map(([id]) => id));
29
+ const removed = base.entities.filter(([id]) => !nowIds.has(id)).map(([id]) => id);
30
+ const added = [];
31
+ const changed = [];
32
+ for (const [id, e] of next.entities) {
33
+ const b = before.get(id);
34
+ if (!b) {
35
+ added.push([id, e]);
36
+ continue;
37
+ }
38
+ const c = {};
39
+ if (b.hidden !== e.hidden)
40
+ c.hidden = e.hidden;
41
+ if (b.scope !== e.scope)
42
+ c.scope = e.scope;
43
+ for (const [name, value] of Object.entries(e.components)) {
44
+ if (!(name in b.components)) {
45
+ (c.set ??= {})[name] = value;
46
+ continue;
47
+ }
48
+ const old = b.components[name];
49
+ if (same(old, value))
50
+ continue;
51
+ if (!isRecord(old) || !isRecord(value)) {
52
+ (c.set ??= {})[name] = value;
53
+ continue;
54
+ }
55
+ const patch = {};
56
+ if (Object.keys(old).some((k) => !(k in value))) {
57
+ (c.set ??= {})[name] = value;
58
+ continue;
59
+ } // campo sumiu: vai inteiro
60
+ const deep = [];
61
+ for (const [k, v] of Object.entries(value)) {
62
+ if (k in old && same(old[k], v))
63
+ continue;
64
+ if (k in old && Array.isArray(v) && Array.isArray(old[k])) {
65
+ const found = [];
66
+ leaves(old[k], v, [k], found);
67
+ if (JSON.stringify(found).length < JSON.stringify(v).length) {
68
+ deep.push(...found);
69
+ continue;
70
+ }
71
+ }
72
+ patch[k] = v;
73
+ }
74
+ if (Object.keys(patch).length)
75
+ (c.patch ??= {})[name] = patch;
76
+ if (deep.length)
77
+ (c.deep ??= {})[name] = deep;
78
+ }
79
+ for (const name of Object.keys(b.components))
80
+ if (!(name in e.components))
81
+ (c.del ??= []).push(name);
82
+ if (Object.keys(c).length)
83
+ changed.push([id, c]);
84
+ }
85
+ const deduced = [...base.entities.map(([id]) => id).filter((id) => nowIds.has(id)), ...added.map(([id]) => id)];
86
+ const order = next.entities.map(([id]) => id);
87
+ const delta = { base: baseTick, frame: next.frame, scene: next.scene, states: next.states, inputs: next.inputs, frozenUntil: next.frozenUntil, paused: next.paused, removed, added, changed };
88
+ if (deduced.some((id, i) => id !== order[i]))
89
+ delta.order = order;
90
+ return delta;
91
+ }
92
+ export function applyDelta(base, d) {
93
+ const gone = new Set(d.removed);
94
+ const map = new Map(base.entities.filter(([id]) => !gone.has(id)).map(([id, e]) => [id, { hidden: e.hidden, scope: e.scope, components: { ...e.components } }]));
95
+ for (const [id, e] of d.added)
96
+ map.set(id, e);
97
+ for (const [id, c] of d.changed) {
98
+ const e = map.get(id);
99
+ if (!e)
100
+ throw new Error(`net delta: changed entity '${id}' is not in the base snapshot ${d.base}`);
101
+ if (c.hidden !== undefined)
102
+ e.hidden = c.hidden;
103
+ if (c.scope !== undefined)
104
+ e.scope = c.scope;
105
+ for (const [name, value] of Object.entries(c.set ?? {}))
106
+ e.components[name] = value;
107
+ for (const [name, patch] of Object.entries(c.patch ?? {}))
108
+ e.components[name] = { ...e.components[name], ...patch };
109
+ for (const [name, list] of Object.entries(c.deep ?? {})) {
110
+ const comp = structuredClone(e.components[name]); // a base fica intacta (outros deltas partem dela)
111
+ for (const [path, value] of list) {
112
+ let at = comp;
113
+ for (let i = 0; i < path.length - 1; i++)
114
+ at = at[path[i]];
115
+ at[path[path.length - 1]] = value;
116
+ }
117
+ e.components[name] = comp;
118
+ }
119
+ for (const name of c.del ?? [])
120
+ delete e.components[name];
121
+ }
122
+ const order = d.order ?? [...base.entities.map(([id]) => id).filter((id) => !gone.has(id) && !d.added.some(([a]) => a === id)), ...d.added.map(([id]) => id)];
123
+ return { frame: d.frame, scene: d.scene, states: d.states, inputs: d.inputs, frozenUntil: d.frozenUntil, paused: d.paused, entities: order.map((id) => [id, map.get(id)]) };
124
+ }
@@ -0,0 +1,17 @@
1
+ /** `profile`: o que o cliente mandou ao entrar, já validado pelo `profile` da sala (sempre presente quando vem do servidor). */
2
+ export declare const NetPlayerJoined: import("@vibe-engine/core").EventDef<{
3
+ player: string;
4
+ profile?: Record<string, unknown>;
5
+ }>;
6
+ export declare const NetPlayerLeft: import("@vibe-engine/core").EventDef<{
7
+ player: string;
8
+ }>;
9
+ /** Caiu: o jogador fica na sala por um tempo (lutador parado), esperando voltar. */
10
+ export declare const NetPlayerAway: import("@vibe-engine/core").EventDef<{
11
+ player: string;
12
+ }>;
13
+ /** Voltou a tempo, como o mesmo jogador. */
14
+ export declare const NetPlayerBack: import("@vibe-engine/core").EventDef<{
15
+ player: string;
16
+ profile?: Record<string, unknown>;
17
+ }>;
package/dist/events.js ADDED
@@ -0,0 +1,9 @@
1
+ /** Eventos de rede que o jogo escuta (código shared: roda no servidor; o cliente recebe o resultado no snapshot). */
2
+ import { defineEvent } from '@vibe-engine/core';
3
+ /** `profile`: o que o cliente mandou ao entrar, já validado pelo `profile` da sala (sempre presente quando vem do servidor). */
4
+ export const NetPlayerJoined = defineEvent('net.player-joined');
5
+ export const NetPlayerLeft = defineEvent('net.player-left');
6
+ /** Caiu: o jogador fica na sala por um tempo (lutador parado), esperando voltar. */
7
+ export const NetPlayerAway = defineEvent('net.player-away');
8
+ /** Voltou a tempo, como o mesmo jogador. */
9
+ export const NetPlayerBack = defineEvent('net.player-back');
package/dist/hub.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Várias salas num processo (RFC-004). Conexões começam no lobby (listar, entrar,
3
+ * criar); ao entrar, o link passa para o `NetServer` da sala. Cada sala tem o
4
+ * próprio World, criado com `{ room, rules }` nos params da cena. Sala vazia
5
+ * fecha depois de um tempo, menos as `open` de cada tipo. Sem Node: testável com loopback.
6
+ */
7
+ import type { World } from '@vibe-engine/core';
8
+ import { type Link } from './protocol.ts';
9
+ import { type NetServerOptions } from './server.ts';
10
+ import type { RoomDef, RoomInfo, RoomParams } from './room.ts';
11
+ export interface RoomHubOptions {
12
+ rooms: RoomDef<any>[];
13
+ createWorld: (def: RoomDef<any>, params: RoomParams) => Promise<World>;
14
+ version?: string;
15
+ snapshotEvery?: number;
16
+ lagCompensation?: NetServerOptions['lagCompensation'];
17
+ /** Ticks vazia até fechar (salas além das `open`). Padrão 30 s a 60 Hz. */
18
+ emptyTicks?: number;
19
+ }
20
+ export interface RoomHub {
21
+ connect(link: Link): void;
22
+ tick(): void;
23
+ rooms(): RoomInfo[];
24
+ /** Espera as salas fixas (`open`) estarem prontas. */
25
+ ready(): Promise<void>;
26
+ /** World de uma sala (testes e agentes). */
27
+ world(roomId: string): World | null;
28
+ }
29
+ export declare function createRoomHub(opts: RoomHubOptions): RoomHub;
package/dist/hub.js ADDED
@@ -0,0 +1,130 @@
1
+ import { PROTOCOL, prefixed } from './protocol.js';
2
+ import { createNetServer } from './server.js';
3
+ export function createRoomHub(opts) {
4
+ const instances = [];
5
+ const worlds = new Map();
6
+ const lobby = [];
7
+ const counters = new Map();
8
+ const creating = [];
9
+ const send = (link, m) => link.send(m);
10
+ const info = (r) => ({ id: r.id, type: r.def.id, name: r.name, players: (r.net?.players.length ?? 0) + r.pending.length, maxPlayers: r.def.maxPlayers, rules: r.rules });
11
+ const params = (r) => ({ room: { id: r.id, type: r.def.id, name: r.name }, rules: r.rules });
12
+ function create(def, name, rules, fixed = false) {
13
+ const n = (counters.get(def.id) ?? 0) + 1;
14
+ counters.set(def.id, n);
15
+ const r = { id: `${def.id}-${n}`, def, name: name || `${def.name} ${n}`, rules: def.resolveRules(rules), net: null, pending: [], empty: 0, failed: null, fixed };
16
+ instances.push(r);
17
+ creating.push(opts.createWorld(def, params(r)).then((world) => {
18
+ worlds.set(r.id, world);
19
+ r.net = createNetServer(world, { maxPlayers: def.maxPlayers, onRelease: (link) => lobby.push(link), ...(opts.version !== undefined ? { version: opts.version } : {}), ...(opts.snapshotEvery ? { snapshotEvery: opts.snapshotEvery } : {}), ...(opts.lagCompensation !== undefined ? { lagCompensation: opts.lagCompensation } : {}) });
20
+ }, (err) => { r.failed = err.message; }));
21
+ return r;
22
+ }
23
+ for (const def of opts.rooms)
24
+ for (let i = 0; i < def.open; i++)
25
+ create(def, undefined, undefined, true);
26
+ function admit(r, link, rest, rejoin = false, profile) {
27
+ if (!rejoin && info(r).players >= r.def.maxPlayers)
28
+ return send(link, { t: 'reject', code: 'room-full', message: `room '${r.name}' is full (${r.def.maxPlayers} players)` });
29
+ lobby.splice(lobby.indexOf(link), 1);
30
+ r.pending.push({ link, rest, ...(profile ? { profile } : {}) });
31
+ }
32
+ function lobbyMessage(link, m, rest) {
33
+ if (m.t === 'rooms') {
34
+ send(link, { t: 'rooms', rooms: instances.filter((r) => !r.failed).map(info), types: opts.rooms.map((d) => ({ type: d.id, maxPlayers: d.maxPlayers, rules: d.resolveRules() })) });
35
+ }
36
+ else if (m.t === 'join') {
37
+ if (m.protocol !== PROTOCOL || (opts.version && m.version !== opts.version))
38
+ return send(link, { t: 'reject', code: 'version-mismatch', message: `server runs version ${opts.version ?? '?'} (protocol ${PROTOCOL}), client sent ${m.version} (protocol ${m.protocol}); reload the page to update` });
39
+ if (m.rejoin) {
40
+ // Volta depois de cair (ou de um F5): a vaga ainda é dele; quem confere o token é a sala (hello).
41
+ const r = instances.find((x) => x.id === m.rejoin.room && !x.failed);
42
+ if (!r)
43
+ return send(link, { t: 'reject', code: 'room-not-found', message: `room '${m.rejoin.room}' is closed` });
44
+ return admit(r, link, rest, true);
45
+ }
46
+ // Perfil do jogador: validado na fronteira, antes de criar ou ocupar a sala.
47
+ const profileFor = (def) => {
48
+ try {
49
+ return def.resolveProfile(m.profile);
50
+ }
51
+ catch (err) {
52
+ send(link, { t: 'reject', code: 'profile-invalid', message: err.message });
53
+ return null;
54
+ }
55
+ };
56
+ if (m.create) {
57
+ const def = opts.rooms.find((d) => d.id === m.create.type);
58
+ if (!def)
59
+ return send(link, { t: 'reject', code: 'room-not-found', message: `no room type '${m.create.type}' (types: ${opts.rooms.map((d) => d.id).join(', ')})` });
60
+ const profile = profileFor(def);
61
+ if (!profile)
62
+ return;
63
+ let r;
64
+ try {
65
+ r = create(def, m.create.name, m.create.rules);
66
+ }
67
+ catch (err) {
68
+ return send(link, { t: 'reject', code: 'rules-invalid', message: err.message });
69
+ }
70
+ return admit(r, link, rest, false, profile);
71
+ }
72
+ if (m.room) {
73
+ const r = instances.find((x) => x.id === m.room && !x.failed);
74
+ if (!r)
75
+ return send(link, { t: 'reject', code: 'room-not-found', message: `no open room '${m.room}'` });
76
+ const profile = profileFor(r.def);
77
+ return profile ? admit(r, link, rest, false, profile) : undefined;
78
+ }
79
+ // Entrada rápida: a sala do tipo com mais gente que ainda tem vaga; senão, uma nova.
80
+ const def = opts.rooms.find((d) => d.id === (m.type ?? opts.rooms[0]?.id));
81
+ if (!def)
82
+ return send(link, { t: 'reject', code: 'room-not-found', message: `no room type '${m.type}'` });
83
+ const profile = profileFor(def);
84
+ if (!profile)
85
+ return;
86
+ const open = instances.filter((x) => x.def === def && !x.failed && info(x).players < def.maxPlayers).sort((a, b) => info(b).players - info(a).players);
87
+ admit(open[0] ?? create(def), link, rest, false, profile);
88
+ }
89
+ }
90
+ return {
91
+ connect(link) { lobby.push(link); },
92
+ tick() {
93
+ for (const link of [...lobby]) {
94
+ if (link.closed) {
95
+ lobby.splice(lobby.indexOf(link), 1);
96
+ continue;
97
+ }
98
+ const msgs = link.receive();
99
+ for (let i = 0; i < msgs.length; i++) {
100
+ if (!lobby.includes(link))
101
+ break;
102
+ lobbyMessage(link, msgs[i], msgs.slice(i + 1));
103
+ }
104
+ }
105
+ for (const r of [...instances]) {
106
+ if (r.failed) {
107
+ for (const p of r.pending.splice(0))
108
+ send(p.link, { t: 'reject', code: 'room-failed', message: `room '${r.name}' failed to start: ${r.failed}` });
109
+ instances.splice(instances.indexOf(r), 1);
110
+ continue;
111
+ }
112
+ if (!r.net)
113
+ continue;
114
+ for (const p of r.pending.splice(0)) {
115
+ send(p.link, { t: 'joined', room: info(r), scene: r.def.scene, params: params(r) });
116
+ r.net.connect(prefixed(p.link, p.rest), p.profile); // o hello chega pelo mesmo link
117
+ }
118
+ r.net.tick();
119
+ r.empty = r.net.players.length === 0 && r.pending.length === 0 ? r.empty + 1 : 0;
120
+ if (!r.fixed && r.empty > (opts.emptyTicks ?? 60 * 30)) {
121
+ instances.splice(instances.indexOf(r), 1);
122
+ worlds.delete(r.id);
123
+ }
124
+ }
125
+ },
126
+ rooms: () => instances.filter((r) => !r.failed).map(info),
127
+ ready: async () => { await Promise.all(creating); },
128
+ world: (id) => worlds.get(id) ?? null,
129
+ };
130
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Multiplayer (RFC-004, perfil realtime-authoritative): servidor autoritativo,
3
+ * cliente com predição e reconciliação, transporte trocável e rede emulada.
4
+ * Código shared: sem DOM e sem Node (o WebSocket do servidor fica em outro entry).
5
+ */
6
+ export { PROTOCOL, prefixed, type ClientMessage, type ServerMessage, type Link } from './protocol.ts';
7
+ export { NetPlayerJoined, NetPlayerLeft, NetPlayerAway, NetPlayerBack } from './events.ts';
8
+ export { createNetServer, type NetServer, type NetServerOptions } from './server.ts';
9
+ export { createNetClient, type NetClient, type NetClientOptions } from './client.ts';
10
+ export { createClock, createLoopback, type NetClock, type LinkConditions } from './loopback.ts';
11
+ export { connectWebSocket } from './websocket.ts';
12
+ export { defineRoom, MAX_PROFILE_BYTES, NetListRooms, NetJoinRoom, NetRoomsListed, NetJoined, NetFailed, NetLeaveRoom, NetConnection, type RoomDef, type RoomInfo, type RoomParams } from './room.ts';
13
+ export { createRoomHub, type RoomHub, type RoomHubOptions } from './hub.ts';
14
+ export { createRoomClient, type RoomClient, type RoomClientOptions, type RoomSession } from './room-client.ts';
15
+ export { netDebugLines } from './debug.ts';
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Multiplayer (RFC-004, perfil realtime-authoritative): servidor autoritativo,
3
+ * cliente com predição e reconciliação, transporte trocável e rede emulada.
4
+ * Código shared: sem DOM e sem Node (o WebSocket do servidor fica em outro entry).
5
+ */
6
+ export { PROTOCOL, prefixed } from './protocol.js';
7
+ export { NetPlayerJoined, NetPlayerLeft, NetPlayerAway, NetPlayerBack } from './events.js';
8
+ export { createNetServer } from './server.js';
9
+ export { createNetClient } from './client.js';
10
+ export { createClock, createLoopback } from './loopback.js';
11
+ export { connectWebSocket } from './websocket.js';
12
+ export { defineRoom, MAX_PROFILE_BYTES, NetListRooms, NetJoinRoom, NetRoomsListed, NetJoined, NetFailed, NetLeaveRoom, NetConnection } from './room.js';
13
+ export { createRoomHub } from './hub.js';
14
+ export { createRoomClient } from './room-client.js';
15
+ export { netDebugLines } from './debug.js';
@@ -0,0 +1,21 @@
1
+ import type { Link } from './protocol.ts';
2
+ export interface NetClock {
3
+ readonly now: number;
4
+ advance(ms: number): void;
5
+ }
6
+ export declare function createClock(): NetClock;
7
+ export interface LinkConditions {
8
+ /** Ida, em ms (RTT = 2 × latency). */
9
+ latencyMs?: number;
10
+ /** Variação extra de 0 a jitterMs por mensagem. */
11
+ jitterMs?: number;
12
+ seed?: number;
13
+ }
14
+ export declare function createLoopback(clock: NetClock, conditions?: LinkConditions): {
15
+ client: Link;
16
+ server: Link;
17
+ stats: {
18
+ messages: number;
19
+ bytes: number;
20
+ };
21
+ };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Rede em memória para testes e agentes: latência e jitter com seed, num relógio
3
+ * virtual (o teste avança o tempo). Confiável e em ordem, como WebSocket: perda
4
+ * de pacote aparece como atraso, não como mensagem sumida.
5
+ */
6
+ import { createRandom } from '@vibe-engine/core';
7
+ export function createClock() {
8
+ let now = 0;
9
+ return { get now() { return now; }, advance(ms) { now += ms; } };
10
+ }
11
+ export function createLoopback(clock, conditions = {}) {
12
+ const random = createRandom(conditions.seed ?? 1);
13
+ const stats = { messages: 0, bytes: 0 };
14
+ let closed = false;
15
+ const pipe = () => {
16
+ const queue = [];
17
+ let last = 0;
18
+ return {
19
+ push(message) {
20
+ if (closed)
21
+ return;
22
+ const data = JSON.stringify(message); // passa pelo fio: nada de referência compartilhada
23
+ stats.messages++;
24
+ stats.bytes += data.length;
25
+ last = Math.max(last, clock.now + (conditions.latencyMs ?? 0) + random.float() * (conditions.jitterMs ?? 0));
26
+ queue.push({ at: last, data });
27
+ },
28
+ pull() {
29
+ const out = [];
30
+ while (queue.length && queue[0].at <= clock.now)
31
+ out.push(JSON.parse(queue.shift().data));
32
+ return out;
33
+ },
34
+ };
35
+ };
36
+ const up = pipe();
37
+ const down = pipe();
38
+ const side = (send, recv) => ({
39
+ send: (m) => send.push(m),
40
+ receive: () => recv.pull(),
41
+ close: () => { closed = true; },
42
+ get closed() { return closed; },
43
+ });
44
+ return { client: side(up, down), server: side(down, up), stats };
45
+ }
@@ -0,0 +1,30 @@
1
+ import { type WebSocket } from 'ws';
2
+ import type { World } from '@vibe-engine/core';
3
+ import { type NetServer, type NetServerOptions } from './server.ts';
4
+ import { type RoomHub, type RoomHubOptions } from './hub.ts';
5
+ import type { Link } from './protocol.ts';
6
+ export interface GameServer {
7
+ readonly port: number;
8
+ readonly net: NetServer;
9
+ readonly world: World;
10
+ close(): Promise<void>;
11
+ }
12
+ export declare function linkFromSocket(ws: WebSocket): Link;
13
+ export declare function startGameServer(world: World, opts?: NetServerOptions & {
14
+ port?: number;
15
+ host?: string;
16
+ onError?: (err: Error) => void;
17
+ }): Promise<GameServer>;
18
+ export interface RoomServer {
19
+ readonly port: number;
20
+ readonly hub: RoomHub;
21
+ close(): Promise<void>;
22
+ }
23
+ /** Várias salas num processo: WebSocket + um loop de tick fixo que avança o lobby e todas as salas. */
24
+ export declare function startRoomServer(opts: RoomHubOptions & {
25
+ port?: number;
26
+ host?: string;
27
+ tickRate?: number;
28
+ onError?: (err: Error) => void;
29
+ staticDir?: string;
30
+ }): Promise<RoomServer>;
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Servidor de jogo em Node (server-only): WebSocket (`ws`) + loop de tick fixo
3
+ * em volta de um `NetServer`. Não entra no bundle do browser.
4
+ */
5
+ import { createServer } from 'node:http';
6
+ import { readFile, stat } from 'node:fs/promises';
7
+ import { extname, join, resolve, sep } from 'node:path';
8
+ import { WebSocketServer } from 'ws';
9
+ import { createNetServer } from './server.js';
10
+ import { createRoomHub } from './hub.js';
11
+ /** Compressão do WebSocket (os browsers negociam sozinhos): o JSON dos snapshots repete chaves e cai ~2x. Mensagens pequenas (input) não comprimem. */
12
+ const DEFLATE = { threshold: 256 };
13
+ /** Mensagem maior que isso fecha a conexão (input é pequeno; isso barra abuso). */
14
+ const MAX_MESSAGE = 16 * 1024;
15
+ export function linkFromSocket(ws) {
16
+ const inbox = [];
17
+ let closed = false;
18
+ ws.on('message', (data, binary) => {
19
+ if (binary || data.length > MAX_MESSAGE)
20
+ return void ws.close(1009, 'message too big');
21
+ try {
22
+ inbox.push(JSON.parse(String(data)));
23
+ }
24
+ catch {
25
+ ws.close(1007, 'invalid JSON');
26
+ }
27
+ });
28
+ ws.on('close', () => { closed = true; });
29
+ return {
30
+ send: (m) => { if (ws.readyState === ws.OPEN)
31
+ ws.send(JSON.stringify(m)); },
32
+ receive: () => inbox.splice(0),
33
+ close: () => { closed = true; ws.close(); },
34
+ get closed() { return closed; },
35
+ };
36
+ }
37
+ export async function startGameServer(world, opts = {}) {
38
+ const net = createNetServer(world, opts);
39
+ const wss = new WebSocketServer({ port: opts.port ?? 0, host: opts.host ?? '127.0.0.1', maxPayload: MAX_MESSAGE, perMessageDeflate: DEFLATE });
40
+ await new Promise((resolve, reject) => { wss.once('listening', resolve); wss.once('error', reject); });
41
+ wss.on('connection', (ws) => net.connect(linkFromSocket(ws)));
42
+ // Tick fixo com acumulador (como no browser): o relógio do servidor é a referência dos clientes.
43
+ let last = performance.now();
44
+ let acc = 0;
45
+ let failed = false;
46
+ const timer = setInterval(() => {
47
+ if (failed)
48
+ return;
49
+ const now = performance.now();
50
+ acc = Math.min(acc + (now - last) / 1000, 5 * world.dt);
51
+ last = now;
52
+ try {
53
+ while (acc >= world.dt) {
54
+ net.tick();
55
+ acc -= world.dt;
56
+ }
57
+ }
58
+ catch (err) {
59
+ failed = true; // world envenenado: parar é o certo; quem chamou decide (log, reiniciar a sala)
60
+ (opts.onError ?? ((e) => console.error(e)))(err);
61
+ }
62
+ }, Math.max(1, Math.floor(1000 / world.tickRate / 2)));
63
+ const address = wss.address();
64
+ return {
65
+ port: typeof address === 'object' && address ? address.port : opts.port ?? 0,
66
+ net,
67
+ world,
68
+ close: () => new Promise((resolve) => { clearInterval(timer); for (const c of wss.clients)
69
+ c.terminate(); wss.close(() => resolve()); }),
70
+ };
71
+ }
72
+ /** Várias salas num processo: WebSocket + um loop de tick fixo que avança o lobby e todas as salas. */
73
+ export async function startRoomServer(opts) {
74
+ const hub = createRoomHub(opts);
75
+ await hub.ready();
76
+ // Uma porta só: HTTP (cliente estático do `vibe build` e /health) + WebSocket no mesmo servidor (qualquer caminho, ex.: /ws).
77
+ const http = createServer((req, res) => { void serveHttp(req, res, opts.staticDir, () => hub.rooms()); });
78
+ const wss = new WebSocketServer({ server: http, maxPayload: MAX_MESSAGE, perMessageDeflate: DEFLATE });
79
+ await new Promise((ok, fail) => { http.once('error', fail); http.listen(opts.port ?? 0, opts.host ?? '127.0.0.1', () => ok()); });
80
+ wss.on('connection', (ws) => hub.connect(linkFromSocket(ws)));
81
+ const dt = 1 / (opts.tickRate ?? 60);
82
+ let last = performance.now();
83
+ let acc = 0;
84
+ let failed = false;
85
+ const timer = setInterval(() => {
86
+ if (failed)
87
+ return;
88
+ const now = performance.now();
89
+ acc = Math.min(acc + (now - last) / 1000, 5 * dt);
90
+ last = now;
91
+ try {
92
+ while (acc >= dt) {
93
+ hub.tick();
94
+ acc -= dt;
95
+ }
96
+ }
97
+ catch (err) {
98
+ failed = true;
99
+ (opts.onError ?? ((e) => console.error(e)))(err);
100
+ }
101
+ }, Math.max(1, Math.floor(1000 * dt / 2)));
102
+ const address = http.address();
103
+ return {
104
+ port: typeof address === 'object' && address ? address.port : opts.port ?? 0,
105
+ hub,
106
+ close: () => new Promise((done) => { clearInterval(timer); for (const c of wss.clients)
107
+ c.terminate(); wss.close(() => http.close(() => done())); }),
108
+ };
109
+ }
110
+ const TYPES = {
111
+ '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json',
112
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.svg': 'image/svg+xml',
113
+ '.wav': 'audio/wav', '.ogg': 'audio/ogg', '.mp3': 'audio/mpeg', '.glb': 'model/gltf-binary', '.gltf': 'model/gltf+json',
114
+ '.wasm': 'application/wasm', '.woff2': 'font/woff2', '.ttf': 'font/ttf',
115
+ };
116
+ /** Arquivos estáticos (só dentro de `dir`), `/health` para o provedor, 404 no resto. */
117
+ async function serveHttp(req, res, dir, rooms) {
118
+ const path = decodeURIComponent((req.url ?? '/').split('?')[0]);
119
+ if (path === '/health') {
120
+ res.writeHead(200, { 'content-type': 'application/json' });
121
+ return void res.end(JSON.stringify({ ok: true, rooms: rooms() }));
122
+ }
123
+ if (!dir || (req.method !== 'GET' && req.method !== 'HEAD')) {
124
+ res.writeHead(404);
125
+ return void res.end();
126
+ }
127
+ const root = resolve(dir);
128
+ let file = resolve(join(root, path));
129
+ if (file !== root && !file.startsWith(root + sep)) {
130
+ res.writeHead(403);
131
+ return void res.end();
132
+ } // ../ fora da pasta
133
+ try {
134
+ if ((await stat(file)).isDirectory())
135
+ file = join(file, 'index.html');
136
+ const body = await readFile(file);
137
+ // Assets do build têm hash no nome: cache longo. index.html sempre fresco (versão nova do jogo).
138
+ const cache = file.includes(`${sep}assets${sep}`) ? 'public, max-age=31536000, immutable' : 'no-cache';
139
+ res.writeHead(200, { 'content-type': TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream', 'cache-control': cache });
140
+ res.end(req.method === 'HEAD' ? undefined : body);
141
+ }
142
+ catch {
143
+ res.writeHead(404);
144
+ res.end();
145
+ }
146
+ }
@@ -0,0 +1,9 @@
1
+ /** Posição de cada entidade com Transform2D/3D (o net não depende do 2d/3d: acha os componentes pelo id). */
2
+ import { type World } from '@vibe-engine/core';
3
+ export interface Position {
4
+ x: number;
5
+ y: number;
6
+ z: number; /** metros (3D) ou px (2D) */
7
+ m: boolean;
8
+ }
9
+ export declare function positions(world: World): Map<string, Position>;
@@ -0,0 +1,18 @@
1
+ /** Posição de cada entidade com Transform2D/3D (o net não depende do 2d/3d: acha os componentes pelo id). */
2
+ import { componentById } from '@vibe-engine/core';
3
+ export function positions(world) {
4
+ const T2 = componentById('Transform2D');
5
+ const T3 = componentById('Transform3D');
6
+ const out = new Map();
7
+ for (const e of world.query()) {
8
+ if (T2 && e.has(T2)) {
9
+ const t = e.read(T2);
10
+ out.set(e.id, { x: t.x, y: t.y, z: 0, m: false });
11
+ }
12
+ else if (T3 && e.has(T3)) {
13
+ const p = e.read(T3).position;
14
+ out.set(e.id, { ...p, m: true });
15
+ }
16
+ }
17
+ return out;
18
+ }