@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/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +22 -0
- package/README.md +10 -2
- package/dist/client.d.ts +60 -0
- package/dist/client.js +248 -0
- package/dist/debug.d.ts +3 -0
- package/dist/debug.js +13 -0
- package/dist/delta.d.ts +40 -0
- package/dist/delta.js +124 -0
- package/dist/events.d.ts +17 -0
- package/dist/events.js +9 -0
- package/dist/hub.d.ts +29 -0
- package/dist/hub.js +130 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +15 -0
- package/dist/loopback.d.ts +21 -0
- package/dist/loopback.js +45 -0
- package/dist/node.server.d.ts +30 -0
- package/dist/node.server.js +146 -0
- package/dist/positions.d.ts +9 -0
- package/dist/positions.js +18 -0
- package/dist/protocol.d.ts +116 -0
- package/dist/protocol.js +6 -0
- package/dist/room-client.d.ts +60 -0
- package/dist/room-client.js +153 -0
- package/dist/room.d.ts +89 -0
- package/dist/room.js +58 -0
- package/dist/server.d.ts +52 -0
- package/dist/server.js +232 -0
- package/dist/websocket.d.ts +5 -0
- package/dist/websocket.js +27 -0
- package/package.json +48 -3
package/LICENSE-APACHE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The vibe-engine contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
package/README.md
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @vibe-engine/net
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
vibe-engine multiplayer: authoritative server, prediction and reconciliation, rooms and lobby.
|
|
4
|
+
|
|
5
|
+
Part of [vibe-engine](https://github.com/sergiobanhos/vibe-engine), a TypeScript game engine that is code-first, headless-first and made to be driven by AI agents. Start a game with:
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npx @vibe-engine/cli create my-game
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
License: MIT OR Apache-2.0.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cliente com predição e reconciliação (RFC-004). O cliente roda o mesmo jogo à
|
|
3
|
+
* frente do servidor: aplica o próprio input na hora (sem esperar a rede), manda
|
|
4
|
+
* o input marcado com o tick, e a cada snapshot volta ao estado oficial e
|
|
5
|
+
* re-simula os ticks que o servidor ainda não viu com o input que guardou. Os
|
|
6
|
+
* outros jogadores seguem o último input conhecido até o próximo snapshot.
|
|
7
|
+
*/
|
|
8
|
+
import type { InputValue, World } from '@vibe-engine/core';
|
|
9
|
+
import { type Link } from './protocol.ts';
|
|
10
|
+
export interface NetClientOptions {
|
|
11
|
+
version?: string;
|
|
12
|
+
/** Token de um welcome anterior: volta como o mesmo jogador (reconexão). */
|
|
13
|
+
token?: string;
|
|
14
|
+
/** Correção maior que isto (px no 2D, m no 3D) é teletransporte (respawn) e não desliza. Padrão 48 px / 2 m. */
|
|
15
|
+
smoothMax?: {
|
|
16
|
+
px?: number;
|
|
17
|
+
m?: number;
|
|
18
|
+
};
|
|
19
|
+
/** Ticks de input que o cliente tenta manter na fila do servidor. Padrão 2. */
|
|
20
|
+
targetBuffer?: number;
|
|
21
|
+
/** Relógio em ms para o ping e os intervalos entre snapshots (padrão `performance.now`; testes passam o relógio virtual). */
|
|
22
|
+
now?: () => number;
|
|
23
|
+
}
|
|
24
|
+
export interface NetClient {
|
|
25
|
+
/** Um passo do relógio fixo: troca mensagens, reconcilia e avança 0, 1 ou 2 ticks (ajuste fino do adiantamento). */
|
|
26
|
+
tick(): void;
|
|
27
|
+
/** Input do jogador deste cliente (teclado/gamepad/agente escrevem aqui). */
|
|
28
|
+
readonly input: {
|
|
29
|
+
set(action: string, value: InputValue): void;
|
|
30
|
+
press(action: string): void;
|
|
31
|
+
};
|
|
32
|
+
readonly player: string | null;
|
|
33
|
+
/** Para voltar como o mesmo jogador se a conexão cair. */
|
|
34
|
+
readonly token: string;
|
|
35
|
+
readonly ready: boolean;
|
|
36
|
+
readonly rejected: {
|
|
37
|
+
code: string;
|
|
38
|
+
message: string;
|
|
39
|
+
} | null;
|
|
40
|
+
/**
|
|
41
|
+
* `corrections`: quantas vezes uma entidade foi corrigida pelo servidor (com deslocamento visual). `adjustments`: quantas
|
|
42
|
+
* vezes o cliente mudou o quanto roda à frente. `rtt`/`jitter`: ping em ms (média móvel) e sua variação. `gapMs`: maior
|
|
43
|
+
* intervalo entre snapshots no último segundo; `stalls`: intervalos acima de 150 ms (a rede segurou pacotes).
|
|
44
|
+
* `lateInputs`: inputs deste jogador que chegaram tarde no servidor.
|
|
45
|
+
*/
|
|
46
|
+
readonly stats: {
|
|
47
|
+
snapshots: number;
|
|
48
|
+
resimTicks: number;
|
|
49
|
+
lead: number;
|
|
50
|
+
buffer: number;
|
|
51
|
+
corrections: number;
|
|
52
|
+
adjustments: number;
|
|
53
|
+
rtt: number;
|
|
54
|
+
jitter: number;
|
|
55
|
+
gapMs: number;
|
|
56
|
+
stalls: number;
|
|
57
|
+
lateInputs: number;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
export declare function createNetClient(world: World, link: Link, opts?: NetClientOptions): NetClient;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { positions } from './positions.js';
|
|
2
|
+
import { PROTOCOL } from './protocol.js';
|
|
3
|
+
import { applyDelta } from './delta.js';
|
|
4
|
+
/** Quanto da correção visual sobra a cada tick. */
|
|
5
|
+
const SMOOTH = 0.88;
|
|
6
|
+
export function createNetClient(world, link, opts = {}) {
|
|
7
|
+
const target = opts.targetBuffer ?? 2;
|
|
8
|
+
let player = null;
|
|
9
|
+
let ready = false;
|
|
10
|
+
let rejected = null;
|
|
11
|
+
let latest = null;
|
|
12
|
+
const states = new Map(); // snapshots inteiros recebidos: bases para as diferenças
|
|
13
|
+
let snapAck = -1;
|
|
14
|
+
const pendingEvents = [];
|
|
15
|
+
const history = new Map();
|
|
16
|
+
const pending = [];
|
|
17
|
+
const stats = { snapshots: 0, resimTicks: 0, lead: 0, buffer: 0, corrections: 0, adjustments: 0, rtt: 0, jitter: 0, gapMs: 0, stalls: 0, lateInputs: 0 };
|
|
18
|
+
const now = opts.now ?? (() => performance.now());
|
|
19
|
+
let ticks = 0;
|
|
20
|
+
let lastSnapAt = -1;
|
|
21
|
+
const gaps = []; // [quando, intervalo] no último segundo
|
|
22
|
+
const buffers = []; // fila de input no servidor nos últimos snapshots
|
|
23
|
+
let sinceAdjust = 0;
|
|
24
|
+
let waitFor = 0; // primeiro tick de input mandado depois do último ajuste
|
|
25
|
+
let debt = 0; // ticks a segurar (estava à frente demais)
|
|
26
|
+
let token = opts.token ?? '';
|
|
27
|
+
link.send({ t: 'hello', protocol: PROTOCOL, version: opts.version ?? '', ...(opts.token ? { token: opts.token } : {}) });
|
|
28
|
+
// Lag compensation: o que o jogador local acertou em cada tick (por consulta, em ordem) vai junto do input.
|
|
29
|
+
// Na re-simulação, a mesma consulta repete o que ele viu (os alvos onde estavam na tela dele).
|
|
30
|
+
const claims = new Map();
|
|
31
|
+
let resimulating = false;
|
|
32
|
+
let calls = { frame: -1, n: 0 };
|
|
33
|
+
world.hitAuthority = {
|
|
34
|
+
resolve(w, by, query) {
|
|
35
|
+
if (by !== player)
|
|
36
|
+
return query(new Map());
|
|
37
|
+
if (calls.frame !== w.frame)
|
|
38
|
+
calls = { frame: w.frame, n: 0 };
|
|
39
|
+
const i = calls.n++;
|
|
40
|
+
const list = claims.get(w.frame) ?? [];
|
|
41
|
+
if (resimulating)
|
|
42
|
+
return query(new Map((list[i] ?? []).map((c) => [c.entity, c.at])));
|
|
43
|
+
const hits = query(new Map());
|
|
44
|
+
list[i] = hits.map((h) => ({ entity: h.entity, at: { x: h.at.x, y: h.at.y, z: h.at.z } }));
|
|
45
|
+
claims.set(w.frame, list);
|
|
46
|
+
return hits;
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
const step = () => { calls = { frame: -1, n: 0 }; world.step(1); };
|
|
50
|
+
const stepOnce = () => {
|
|
51
|
+
const tick = world.frame;
|
|
52
|
+
for (const [action, value] of pending.splice(0))
|
|
53
|
+
value === 'press' ? world.input.press(action, player) : world.input.set(action, value, player);
|
|
54
|
+
step();
|
|
55
|
+
const values = world.input.sampled(player);
|
|
56
|
+
history.set(tick, values);
|
|
57
|
+
const hits = claims.get(tick);
|
|
58
|
+
link.send({ t: 'input', tick, values, snap: snapAck, ...(hits?.length ? { hits } : {}) });
|
|
59
|
+
};
|
|
60
|
+
// Posições antes e depois da reconciliação: a diferença vira deslocamento visual que some em ~0,1 s.
|
|
61
|
+
const smooth = (before) => {
|
|
62
|
+
for (const [id, now] of positions(world)) {
|
|
63
|
+
const was = before.get(id);
|
|
64
|
+
if (!was)
|
|
65
|
+
continue;
|
|
66
|
+
const d = { x: was.x - now.x, y: was.y - now.y, z: was.z - now.z };
|
|
67
|
+
const len = Math.hypot(d.x, d.y, d.z);
|
|
68
|
+
if (len < (now.m ? 0.001 : 0.05) || len > (now.m ? opts.smoothMax?.m ?? 2 : opts.smoothMax?.px ?? 48))
|
|
69
|
+
continue;
|
|
70
|
+
const o = world.visualOffsets.get(id) ?? { x: 0, y: 0, z: 0 };
|
|
71
|
+
world.visualOffsets.set(id, { x: o.x + d.x, y: o.y + d.y, z: o.z + d.z });
|
|
72
|
+
stats.corrections++;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
const reconcile = (snap) => {
|
|
76
|
+
const now = world.frame;
|
|
77
|
+
const before = positions(world);
|
|
78
|
+
const live = world.input.live(player); // teclas apertadas desde o último tick: não podem se perder na re-simulação
|
|
79
|
+
world.restoreNetState(snap.state, { keepLiveInput: [player] });
|
|
80
|
+
for (const t of [...history.keys()])
|
|
81
|
+
if (t < snap.tick - 1) {
|
|
82
|
+
history.delete(t);
|
|
83
|
+
claims.delete(t);
|
|
84
|
+
} // o servidor já tem esses
|
|
85
|
+
resimulating = true;
|
|
86
|
+
try {
|
|
87
|
+
for (let t = snap.tick; t < now; t++) {
|
|
88
|
+
// O input do tick inteiro, do zero: ação que não estava na amostra é neutra (não herda o que está apertado agora).
|
|
89
|
+
world.input.restoreLive({ values: history.get(t) ?? {}, taps: [] }, player);
|
|
90
|
+
step();
|
|
91
|
+
stats.resimTicks++;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
resimulating = false;
|
|
96
|
+
}
|
|
97
|
+
world.input.restoreLive(live, player);
|
|
98
|
+
smooth(before);
|
|
99
|
+
world.addRemoteEvents(pendingEvents.splice(0));
|
|
100
|
+
};
|
|
101
|
+
return {
|
|
102
|
+
tick() {
|
|
103
|
+
if (rejected)
|
|
104
|
+
return;
|
|
105
|
+
if (ticks++ % 60 === 0)
|
|
106
|
+
link.send({ t: 'ping', id: now() }); // ~1 por segundo
|
|
107
|
+
for (const raw of link.receive()) {
|
|
108
|
+
const m = raw;
|
|
109
|
+
if (m.t === 'pong') {
|
|
110
|
+
const rtt = now() - m.id;
|
|
111
|
+
stats.jitter = stats.rtt ? stats.jitter * 0.8 + Math.abs(rtt - stats.rtt) * 0.2 : 0;
|
|
112
|
+
stats.rtt = stats.rtt ? stats.rtt * 0.8 + rtt * 0.2 : rtt;
|
|
113
|
+
stats.lateInputs = m.late;
|
|
114
|
+
}
|
|
115
|
+
else if (m.t === 'welcome') {
|
|
116
|
+
player = m.player;
|
|
117
|
+
token = m.token;
|
|
118
|
+
world.localPlayer = m.player;
|
|
119
|
+
}
|
|
120
|
+
else if (m.t === 'reject')
|
|
121
|
+
rejected = { code: m.code, message: m.message };
|
|
122
|
+
else if (m.t === 'snapshot') {
|
|
123
|
+
const at = now();
|
|
124
|
+
if (lastSnapAt >= 0) {
|
|
125
|
+
const gap = at - lastSnapAt;
|
|
126
|
+
gaps.push([at, gap]);
|
|
127
|
+
if (gap > 150)
|
|
128
|
+
stats.stalls++;
|
|
129
|
+
}
|
|
130
|
+
lastSnapAt = at;
|
|
131
|
+
while (gaps.length && gaps[0][0] < at - 1000)
|
|
132
|
+
gaps.shift();
|
|
133
|
+
stats.gapMs = Math.round(Math.max(0, ...gaps.map(([, g]) => g)));
|
|
134
|
+
pendingEvents.push(...(m.events ?? [])); // de todo snapshot, mesmo os que vamos pular
|
|
135
|
+
// Estado inteiro: veio completo ou é a base confirmada + a diferença.
|
|
136
|
+
let state = m.state;
|
|
137
|
+
if (!state && m.delta) {
|
|
138
|
+
const base = states.get(m.delta.base);
|
|
139
|
+
if (!base) {
|
|
140
|
+
snapAck = -1;
|
|
141
|
+
continue;
|
|
142
|
+
} // sem a base: pede o completo
|
|
143
|
+
state = applyDelta(base, m.delta);
|
|
144
|
+
}
|
|
145
|
+
if (!state)
|
|
146
|
+
continue;
|
|
147
|
+
states.set(m.tick, state);
|
|
148
|
+
snapAck = Math.max(snapAck, m.tick);
|
|
149
|
+
for (const t of states.keys())
|
|
150
|
+
if (t < m.tick - 180)
|
|
151
|
+
states.delete(t);
|
|
152
|
+
if (!latest || m.tick > latest.tick) {
|
|
153
|
+
latest = { tick: m.tick, ack: m.ack, buffer: m.buffer, state };
|
|
154
|
+
stats.snapshots++;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (rejected || !player)
|
|
159
|
+
return;
|
|
160
|
+
if (!ready) {
|
|
161
|
+
if (!latest)
|
|
162
|
+
return;
|
|
163
|
+
// Primeiro estado: entra no tick do servidor e já corre à frente o bastante para o input chegar a tempo.
|
|
164
|
+
world.restoreNetState(latest.state);
|
|
165
|
+
ready = true;
|
|
166
|
+
for (let i = 0; i < target + 1; i++)
|
|
167
|
+
stepOnce();
|
|
168
|
+
stats.lead = world.frame - latest.tick;
|
|
169
|
+
latest = null;
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
let steps = 1;
|
|
173
|
+
sinceAdjust++;
|
|
174
|
+
if (debt > 0) {
|
|
175
|
+
debt--;
|
|
176
|
+
steps = 0;
|
|
177
|
+
} // à frente demais: segura a simulação até a fila do servidor voltar ao alvo
|
|
178
|
+
if (latest) {
|
|
179
|
+
stats.buffer = latest.buffer;
|
|
180
|
+
const before = world.frame;
|
|
181
|
+
reconcile(latest);
|
|
182
|
+
// Cliente parado (aba dormindo) fica atrás do snapshot: a reconciliação já o põe no tick do servidor.
|
|
183
|
+
const skipped = Math.max(0, world.frame - before);
|
|
184
|
+
// Adiantamento pela fila de input no servidor, olhando ~1 s de snapshots: o jitter da internet faz a fila
|
|
185
|
+
// oscilar, e ajustar a cada snapshot (0 ou 2 ticks num frame) aparecia como tranco ~3×/s. Só muda quando
|
|
186
|
+
// a rede mudou: muito atrás (entrada, pico) corrige de uma vez; atrasando de verdade → +1; sobrando → −1.
|
|
187
|
+
// Só vale a leitura de um snapshot em que o servidor já viu input mandado depois do último ajuste
|
|
188
|
+
// (último input recebido = tick + buffer). Os que estavam no caminho ainda dizem "atrasado": contar
|
|
189
|
+
// com eles fazia o salto se repetir e passar muito do ponto (fila de 110 ticks = 2 s à frente).
|
|
190
|
+
if (latest.tick + latest.buffer >= waitFor && debt === 0) {
|
|
191
|
+
buffers.push(latest.buffer);
|
|
192
|
+
if (buffers.length > 20)
|
|
193
|
+
buffers.shift();
|
|
194
|
+
const min = Math.min(...buffers);
|
|
195
|
+
const mean = buffers.reduce((a, b) => a + b, 0) / buffers.length;
|
|
196
|
+
let adjust = 0;
|
|
197
|
+
if (latest.buffer < -1)
|
|
198
|
+
adjust = target - latest.buffer;
|
|
199
|
+
else if (latest.buffer > target + 8)
|
|
200
|
+
adjust = target - latest.buffer;
|
|
201
|
+
else if ((min < 0 && sinceAdjust >= 30) || (mean < target - 1 && sinceAdjust >= 60))
|
|
202
|
+
adjust = 1;
|
|
203
|
+
else if (buffers.length >= 20 && min > target + 1 && sinceAdjust >= 60)
|
|
204
|
+
adjust = -1;
|
|
205
|
+
if (adjust > 0)
|
|
206
|
+
steps += Math.max(0, adjust - skipped); // o que a reconciliação já avançou não conta de novo
|
|
207
|
+
else if (adjust < 0) {
|
|
208
|
+
debt = -adjust - steps;
|
|
209
|
+
steps = 0;
|
|
210
|
+
}
|
|
211
|
+
if (adjust) {
|
|
212
|
+
sinceAdjust = 0;
|
|
213
|
+
buffers.length = 0;
|
|
214
|
+
stats.adjustments++;
|
|
215
|
+
waitFor = world.frame;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
stats.lead = world.frame - latest.tick;
|
|
219
|
+
latest = null;
|
|
220
|
+
}
|
|
221
|
+
for (let i = 0; i < steps; i++)
|
|
222
|
+
stepOnce();
|
|
223
|
+
// Correção visual some em ~0,3 s (×0,88 por tick a 60 Hz; 0,82 deixava o inimigo dando trancos ao virar), com ou sem tela: a mira (raycast com `by`) usa a posição da tela.
|
|
224
|
+
for (const [id, o] of world.visualOffsets) {
|
|
225
|
+
o.x *= SMOOTH;
|
|
226
|
+
o.y *= SMOOTH;
|
|
227
|
+
o.z *= SMOOTH;
|
|
228
|
+
if (Math.abs(o.x) + Math.abs(o.y) + Math.abs(o.z) < 0.01)
|
|
229
|
+
world.visualOffsets.delete(id);
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
input: {
|
|
233
|
+
set: (action, value) => { if (player)
|
|
234
|
+
world.input.set(action, value, player);
|
|
235
|
+
else
|
|
236
|
+
pending.push([action, value]); },
|
|
237
|
+
press: (action) => { if (player)
|
|
238
|
+
world.input.press(action, player);
|
|
239
|
+
else
|
|
240
|
+
pending.push([action, 'press']); },
|
|
241
|
+
},
|
|
242
|
+
get player() { return player; },
|
|
243
|
+
get token() { return token; },
|
|
244
|
+
get ready() { return ready; },
|
|
245
|
+
get rejected() { return rejected; },
|
|
246
|
+
stats,
|
|
247
|
+
};
|
|
248
|
+
}
|
package/dist/debug.d.ts
ADDED
package/dist/debug.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export function netDebugLines(stats, player) {
|
|
2
|
+
if (!stats)
|
|
3
|
+
return ['rede: fora de uma sala'];
|
|
4
|
+
const ms = (v) => `${Math.round(v)} ms`;
|
|
5
|
+
return [
|
|
6
|
+
`rede${player ? ` · ${player}` : ''}`,
|
|
7
|
+
`ping ${stats.rtt ? ms(stats.rtt) : '…'} ±${ms(stats.jitter)}`,
|
|
8
|
+
`snapshots: maior intervalo ${ms(stats.gapMs)} · travadas ${stats.stalls}`,
|
|
9
|
+
`inputs atrasados no servidor ${stats.lateInputs}`,
|
|
10
|
+
`à frente ${stats.lead} ticks · fila ${stats.buffer} · ajustes ${stats.adjustments}`,
|
|
11
|
+
`correções ${stats.corrections}`,
|
|
12
|
+
];
|
|
13
|
+
}
|
package/dist/delta.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Snapshot por diferença (RFC-004): só o que mudou desde um snapshot que o
|
|
3
|
+
* cliente confirmou. Granularidade de componente: entidade nova vai inteira,
|
|
4
|
+
* entidade que mudou leva só os componentes alterados, a que sumiu vai pelo id.
|
|
5
|
+
* O resto (inputs, estados, frame) é pequeno e vai sempre. A ordem das
|
|
6
|
+
* entidades importa (hash, determinismo): só vai junto quando não dá para
|
|
7
|
+
* deduzir (base − removidas + novas no fim).
|
|
8
|
+
* Campo que é lista (os tiles de um Tilemap) vai como as folhas que mudaram
|
|
9
|
+
* (`deep`: caminho → valor) quando isso sai menor que a lista inteira: uma
|
|
10
|
+
* explosão no cenário manda as células removidas, não o mapa (#121).
|
|
11
|
+
*/
|
|
12
|
+
import type { NetState } from '@vibe-engine/core';
|
|
13
|
+
type Entity = NetState['entities'][number][1];
|
|
14
|
+
export interface NetDelta {
|
|
15
|
+
base: number;
|
|
16
|
+
frame: number;
|
|
17
|
+
scene: string | null;
|
|
18
|
+
states: string[];
|
|
19
|
+
inputs: NetState['inputs'];
|
|
20
|
+
frozenUntil: number;
|
|
21
|
+
paused: boolean;
|
|
22
|
+
removed: string[];
|
|
23
|
+
added: Array<[string, Entity]>;
|
|
24
|
+
/** `set`: componente novo (inteiro). `patch`: só os campos de primeiro nível que mudaram num componente que já existia. */
|
|
25
|
+
/** `deep`: folhas que mudaram dentro de campos lista, `[[campo, índice, ...], valor]`. */
|
|
26
|
+
changed: Array<[string, {
|
|
27
|
+
hidden?: boolean;
|
|
28
|
+
scope?: string | null;
|
|
29
|
+
set?: Record<string, unknown>;
|
|
30
|
+
patch?: Record<string, Record<string, unknown>>;
|
|
31
|
+
deep?: Record<string, Leaf[]>;
|
|
32
|
+
del?: string[];
|
|
33
|
+
}]>;
|
|
34
|
+
/** Só quando a ordem não é a deduzida. */
|
|
35
|
+
order?: string[];
|
|
36
|
+
}
|
|
37
|
+
type Leaf = [Array<string | number>, unknown];
|
|
38
|
+
export declare function diffState(baseTick: number, base: NetState, next: NetState): NetDelta;
|
|
39
|
+
export declare function applyDelta(base: NetState, d: NetDelta): NetState;
|
|
40
|
+
export {};
|