@korial29/tiny-fps 0.1.0 → 0.3.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/server.js CHANGED
@@ -3,8 +3,26 @@ import { WebSocketServer } from "ws";
3
3
  /** Player cylinder. */
4
4
  var PLAYER_R = .4;
5
5
  var PLAYER_H = 1.8;
6
+ /** Camera height above the feet. */
7
+ var EYE = 1.6;
6
8
  /** Pitch is clamped to ±MAX_PITCH radians, just short of straight up or down. */
7
9
  var MAX_PITCH = 1.55;
10
+ /** A floor at most this much higher is walked onto; a higher one needs a jump. */
11
+ var STEP_H = .5;
12
+ /** Speed factor while the trigger is held. */
13
+ var FIRE_SLOW = .5;
14
+ /** Largest angle, in radians, between a shot and the view direction. */
15
+ var SPREAD = .02;
16
+ var WALKER_R = .4;
17
+ var WALKER_H = 1.8;
18
+ var WALKER_SPEED = 2.5;
19
+ var FLYER_R = .45;
20
+ var FLYER_H = .9;
21
+ /** A flyer's underside floats this high above the floor below it, ceilings allowing. */
22
+ var FLYER_HOVER = 1.2;
23
+ var FLYER_SPEED = 3.5;
24
+ var SIGHT_COS = Math.cos(Math.PI / 6);
25
+ var BULLET_R = .15;
8
26
  var RULES = { maxPlayers: 16 };
9
27
  // src/shared/level.ts
10
28
  /** Joins every edge a→b with the sector that has b→a, if any: that edge is a portal. */
@@ -34,6 +52,26 @@ var inside = ({ pts }, x, z) => pts.every(([ax, az], i) => {
34
52
  });
35
53
  /** Index of the first sector holding (x, z), -1 outside the map. */
36
54
  var sectorAt = ({ map }, x, z) => map.sectors.findIndex((s) => inside(s, x, z));
55
+ /**
56
+ * Whether a wall, a step or a ceiling hides b from a (both inside the map). Between two edge
57
+ * crossings the segment stays in one sector, and each crossing is checked against the opening of
58
+ * its portal, so floors and ceilings need no test of their own.
59
+ */
60
+ var blocked = ({ map, edges }, [ax, ay, az], [bx, by, bz]) => {
61
+ const [dx, dz] = [bx - ax, bz - az];
62
+ return edges.some((e) => {
63
+ const [ex, ez] = [e.bx - e.ax, e.bz - e.az];
64
+ const den = dx * ez - dz * ex;
65
+ if (!den) return false;
66
+ const t = ((e.ax - ax) * ez - (e.az - az) * ex) / den;
67
+ const u = ((e.ax - ax) * dz - (e.az - az) * dx) / den;
68
+ if (t <= 0 || t >= 1 || u < 0 || u > 1) return false;
69
+ if (e.back < 0) return true;
70
+ const [f, k] = [map.sectors[e.front], map.sectors[e.back]];
71
+ const y = ay + t * (by - ay);
72
+ return y < Math.max(f.floor, k.floor) || y > Math.min(f.ceil, k.ceil);
73
+ });
74
+ };
37
75
  // src/shared/types.ts
38
76
  /** Bits of Input.keys. Keys are read by KeyboardEvent.code, so WASD is ZQSD on AZERTY. */
39
77
  var KEY = {
@@ -41,7 +79,27 @@ var KEY = {
41
79
  BACK: 2,
42
80
  LEFT: 4,
43
81
  RIGHT: 8,
44
- JUMP: 16
82
+ JUMP: 16,
83
+ /** Left mouse button: the chaingun fires every FIRE_EVERY steps while held. */
84
+ FIRE: 32
85
+ };
86
+ /** Monster kinds. */
87
+ var MONSTER = {
88
+ /** Walks the floors like a player, shoots bullets from afar and hits up close. */
89
+ WALKER: 0,
90
+ /** Hovers above the floor, flies over steps and pits, hits up close. */
91
+ FLYER: 1
92
+ };
93
+ /** What a GameEvent reports. */
94
+ var EVENT = {
95
+ /** Monster `id` died, (x, y, z) the middle of its body: gibs and an explosion. */
96
+ DIE: 0,
97
+ /** Player `id` was hit by a bullet or a blow at (x, y, z). Harmless until health (step 4). */
98
+ HURT: 1,
99
+ /** A bullet burst on the level at (x, y, z); `id` is the bullet. */
100
+ BOOM: 2,
101
+ /** Monster `id` swung at its target from (x, y, z), hit or miss. */
102
+ SWING: 3
45
103
  };
46
104
  /** Procedural textures, generated by the client. A sector names one per surface. */
47
105
  var TEX = {
@@ -184,10 +242,60 @@ var HALL = {
184
242
  14,
185
243
  Math.PI * 1.5
186
244
  ]
245
+ ],
246
+ monsters: [
247
+ [
248
+ 24,
249
+ 2,
250
+ Math.PI * 1.2,
251
+ MONSTER.WALKER
252
+ ],
253
+ [
254
+ 33,
255
+ 3,
256
+ Math.PI * .75,
257
+ MONSTER.WALKER
258
+ ],
259
+ [
260
+ 33,
261
+ 8,
262
+ Math.PI * .5,
263
+ MONSTER.WALKER
264
+ ],
265
+ [
266
+ 24,
267
+ 14,
268
+ Math.PI * 1.8,
269
+ MONSTER.WALKER
270
+ ],
271
+ [
272
+ 30,
273
+ 23,
274
+ 0,
275
+ MONSTER.WALKER
276
+ ],
277
+ [
278
+ 28,
279
+ 8,
280
+ 0,
281
+ MONSTER.FLYER
282
+ ],
283
+ [
284
+ 34,
285
+ 13,
286
+ Math.PI * .3,
287
+ MONSTER.FLYER
288
+ ],
289
+ [
290
+ 34,
291
+ 22,
292
+ Math.PI * .5,
293
+ MONSTER.FLYER
294
+ ]
187
295
  ]
188
296
  };
189
297
  // src/shared/physics.ts
190
- var DT = 1 / 60;
298
+ var DT$1 = 1 / 60;
191
299
  var TAU = Math.PI * 2;
192
300
  /** Overlaps smaller than this are rounding noise, not contact. */
193
301
  var EPS = 1e-6;
@@ -204,17 +312,17 @@ var forward = (yaw) => [-Math.sin(yaw), -Math.cos(yaw)];
204
312
  var f32 = Math.fround;
205
313
  var clamp = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
206
314
  /**
207
- * Whether the edge stops a player whose feet are at y: a solid wall, a floor on the far side more
208
- * than STEP_H above the feet, or an opening (the lower ceiling minus the higher floor) too short
209
- * for the body or under the head. SKIN keeps rounding from flipping the answer
315
+ * Whether the edge stops a body of height h whose feet are at y: a solid wall, a floor on the far
316
+ * side more than `step` above the feet, or an opening (the lower ceiling minus the higher floor)
317
+ * too short for the body or under the head. SKIN keeps rounding from flipping the answer
210
318
  * for a player resting on a step or against a ceiling.
211
319
  */
212
- var shut = ({ map }, e, y) => {
320
+ var shut = ({ map }, e, y, h, step) => {
213
321
  if (e.back < 0) return true;
214
322
  const f = map.sectors[e.front];
215
323
  const k = map.sectors[e.back];
216
324
  const top = Math.min(f.ceil, k.ceil);
217
- return k.floor > y + .5 + SKIN || top - Math.max(f.floor, k.floor) < 1.8 - SKIN || top < y + 1.8 - SKIN;
325
+ return k.floor > y + step + SKIN || top - Math.max(f.floor, k.floor) < h - SKIN || top < y + h - SKIN;
218
326
  };
219
327
  /**
220
328
  * Pushes the player out of every shut edge it overlaps, deepest first (up to 4 passes: two walls
@@ -228,8 +336,8 @@ var shut = ({ map }, e, y) => {
228
336
  * Tunnelling is impossible: a step is RUN_SPEED / TICK_HZ = 0.1 m and the axis ends each step at
229
337
  * least PLAYER_R = 0.4 m from every shut edge it started beside, so it cannot cross one in 0.1 m.
230
338
  */
231
- var push = (p, lvl) => {
232
- const reach = (PLAYER_R - EPS) ** 2;
339
+ var push = (p, lvl, r, h, step) => {
340
+ const reach = (r - EPS) ** 2;
233
341
  for (let pass = 0; pass < 4; pass++) {
234
342
  let best = 0;
235
343
  let px = 0;
@@ -246,8 +354,8 @@ var push = (p, lvl) => {
246
354
  const d2 = dx * dx + dz * dz;
247
355
  if (d2 >= reach) continue;
248
356
  const d = Math.sqrt(d2);
249
- if (.4 - d <= best || !shut(lvl, e, p.y)) continue;
250
- best = PLAYER_R - d;
357
+ if (r - d <= best || !shut(lvl, e, p.y, h, step)) continue;
358
+ best = r - d;
251
359
  const n = d || Math.hypot(ex, ez);
252
360
  px = (d ? dx : -ez) / n * best;
253
361
  pz = (d ? dz : ex) / n * best;
@@ -262,11 +370,11 @@ var push = (p, lvl) => {
262
370
  * sector holding the axis and of every sector across a portal the circle overlaps and could walk
263
371
  * through (a shut edge is a wall: the circle never counts what lies behind it).
264
372
  */
265
- var span = (lvl, x, z, y) => {
373
+ var span = (lvl, x, z, y, r, h, step) => {
266
374
  const { map, edges } = lvl;
267
375
  const s = Math.max(sectorAt(lvl, x, z), 0);
268
376
  let { floor, ceil } = map.sectors[s];
269
- const reach = (PLAYER_R - EPS) ** 2;
377
+ const reach = (r - EPS) ** 2;
270
378
  for (const e of edges) {
271
379
  if (e.front !== s || e.back < 0) continue;
272
380
  const ex = e.bx - e.ax;
@@ -274,7 +382,7 @@ var span = (lvl, x, z, y) => {
274
382
  const rx = x - e.ax;
275
383
  const rz = z - e.az;
276
384
  const t = clamp((rx * ex + rz * ez) / (ex * ex + ez * ez), 0, 1);
277
- if ((rx - t * ex) ** 2 + (rz - t * ez) ** 2 < reach && !shut(lvl, e, y)) {
385
+ if ((rx - t * ex) ** 2 + (rz - t * ez) ** 2 < reach && !shut(lvl, e, y, h, step)) {
278
386
  const k = map.sectors[e.back];
279
387
  floor = Math.max(floor, k.floor);
280
388
  ceil = Math.min(ceil, k.ceil);
@@ -283,27 +391,20 @@ var span = (lvl, x, z, y) => {
283
391
  return [floor, ceil];
284
392
  };
285
393
  /**
286
- * Applies one input for 1 / TICK_HZ s, in place: yaw and pitch from the input (pitch clamped to
287
- * MAX_PITCH), RUN_SPEED along the held keys (diagonals not faster), a jump from the ground,
288
- * GRAVITY, then collisions of the cylinder (PLAYER_R, PLAYER_H) with the sectors of the level:
289
- * it slides along shut edges (see shut and push), stands on the highest floor under the circle
290
- * (a step up to STEP_H is climbed at once, a higher one needs a jump, a ledge is a fall), and
291
- * bumps its head on the lowest ceiling.
394
+ * Moves the feet by (dx, dz) for 1 / TICK_HZ s, then a jump from the ground, GRAVITY and the
395
+ * collisions of the cylinder (PLAYER_R, PLAYER_H) with the sectors of the level: it slides along
396
+ * shut edges (see shut and push), stands on the highest floor under the circle (a step up to
397
+ * STEP_H is climbed at once, a higher one needs a jump, a ledge is a fall), and bumps its head on
398
+ * the lowest ceiling. Players and walkers share it, in place.
292
399
  */
293
- var move = (p, i, lvl) => {
294
- p.yaw = norm(i.yaw);
295
- p.pitch = Math.max(-MAX_PITCH, Math.min(MAX_PITCH, i.pitch));
296
- const f = (i.keys & KEY.FORWARD ? 1 : 0) - (i.keys & KEY.BACK ? 1 : 0);
297
- const s = (i.keys & KEY.RIGHT ? 1 : 0) - (i.keys & KEY.LEFT ? 1 : 0);
298
- const d = 6 * DT / (Math.hypot(f, s) || 1);
299
- const [fx, fz] = forward(p.yaw);
300
- p.x += (fx * f - fz * s) * d;
301
- p.z += (fz * f + fx * s) * d;
302
- push(p, lvl);
303
- const [floor, ceil] = span(lvl, p.x, p.z, p.y);
304
- if (p.ground && i.keys & KEY.JUMP) p.vy = 7;
305
- const vy = p.vy - 20 * DT;
306
- p.y += (p.vy + vy) / 2 * DT;
400
+ var walk = (p, dx, dz, jump, lvl) => {
401
+ p.x += dx;
402
+ p.z += dz;
403
+ push(p, lvl, PLAYER_R, PLAYER_H, STEP_H);
404
+ const [floor, ceil] = span(lvl, p.x, p.z, p.y, PLAYER_R, PLAYER_H, STEP_H);
405
+ if (p.ground && jump) p.vy = 7;
406
+ const vy = p.vy - 20 * DT$1;
407
+ p.y += (p.vy + vy) / 2 * DT$1;
307
408
  p.vy = vy;
308
409
  p.ground = false;
309
410
  if (p.y + 1.8 > ceil) {
@@ -322,6 +423,49 @@ var move = (p, i, lvl) => {
322
423
  p.z = f32(p.z);
323
424
  p.vy = f32(p.vy);
324
425
  };
426
+ /**
427
+ * Moves a flyer (underside at p.y, radius FLYER_R, height FLYER_H) by (dx, dy, dz): sideways it is
428
+ * stopped by solid walls and by openings too small for it, and it never steps (it flies over
429
+ * steps and pits); then y is held between FLYER_HOVER above the highest floor under it and the
430
+ * lowest ceiling minus FLYER_H, the ceiling winning in a low room. Below the hover height it
431
+ * rises at FLYER_SPEED, so crossing from a pit to a ledge is not a jump; the floor itself is
432
+ * never entered.
433
+ */
434
+ var fly = (p, dx, dy, dz, lvl) => {
435
+ p.x += dx;
436
+ p.z += dz;
437
+ push(p, lvl, FLYER_R, FLYER_H, 0);
438
+ const [floor, ceil] = span(lvl, p.x, p.z, p.y, FLYER_R, FLYER_H, 0);
439
+ const hover = Math.min(floor + FLYER_HOVER, ceil - FLYER_H);
440
+ const low = Math.max(floor, Math.min(hover, p.y + FLYER_SPEED * DT$1));
441
+ p.y = Math.min(Math.max(p.y + dy, low), ceil - FLYER_H);
442
+ p.x = f32(p.x);
443
+ p.y = f32(p.y);
444
+ p.z = f32(p.z);
445
+ };
446
+ /**
447
+ * Applies one input for 1 / TICK_HZ s, in place: yaw and pitch from the input (pitch clamped to
448
+ * MAX_PITCH), RUN_SPEED along the held keys (diagonals not faster), then walk().
449
+ * The chaingun: `cool` counts down one per step, RUN_SPEED is scaled by FIRE_SLOW while KEY.FIRE
450
+ * is held, and the step that finds it held with `cool` at 0 re-arms it to FIRE_EVERY and returns
451
+ * true: the caller resolves a shot (one every FIRE_EVERY steps, the first at once).
452
+ */
453
+ var move = (p, i, lvl) => {
454
+ const fire = (i.keys & KEY.FIRE) !== 0;
455
+ p.cool = Math.max(0, p.cool - 1);
456
+ p.yaw = norm(i.yaw);
457
+ p.pitch = Math.max(-MAX_PITCH, Math.min(MAX_PITCH, i.pitch));
458
+ const f = (i.keys & KEY.FORWARD ? 1 : 0) - (i.keys & KEY.BACK ? 1 : 0);
459
+ const s = (i.keys & KEY.RIGHT ? 1 : 0) - (i.keys & KEY.LEFT ? 1 : 0);
460
+ const d = 6 * DT$1 * (fire ? FIRE_SLOW : 1) / (Math.hypot(f, s) || 1);
461
+ const [fx, fz] = forward(p.yaw);
462
+ walk(p, (fx * f - fz * s) * d, (fz * f + fx * s) * d, (i.keys & KEY.JUMP) !== 0, lvl);
463
+ if (fire && !p.cool) {
464
+ p.cool = 5;
465
+ return true;
466
+ }
467
+ return false;
468
+ };
325
469
  /** A player standing on the floor at spawn point n of the map (modulo the count). */
326
470
  var spawn = (id, lvl, n) => {
327
471
  const { spawns, sectors } = lvl.map;
@@ -335,7 +479,423 @@ var spawn = (id, lvl, n) => {
335
479
  vy: 0,
336
480
  yaw: norm(yaw),
337
481
  pitch: 0,
338
- ground: true
482
+ ground: true,
483
+ cool: 0
484
+ };
485
+ };
486
+ // src/shared/shoot.ts
487
+ /** 32-bit integer hash (a xorshift-multiply round, twice). */
488
+ var hash = (n) => {
489
+ for (let k = 0; k < 2; k++) n = Math.imul(n ^ n >>> 16, 73244475);
490
+ return (n ^ n >>> 16) >>> 0;
491
+ };
492
+ /**
493
+ * Unit direction of a shot: the view direction at yaw and pitch (yaw 0, pitch 0 is -z; pitch > 0
494
+ * looks up), turned by at most SPREAD in a direction hashed from seq, so the host and the
495
+ * shooter's client agree on it.
496
+ */
497
+ var aim = (yaw, pitch, seq) => {
498
+ const [sy, cy, sp, cp] = [
499
+ Math.sin(yaw),
500
+ Math.cos(yaw),
501
+ Math.sin(pitch),
502
+ Math.cos(pitch)
503
+ ];
504
+ const h = hash(seq + 1);
505
+ const a = (h & 65535) / 65536 * TAU;
506
+ const r = (h >>> 16) / 65535;
507
+ const [x, y] = [Math.cos(a) * r * SPREAD, Math.sin(a) * r * SPREAD];
508
+ const d = [
509
+ -sy * cp + cy * x + sy * sp * y,
510
+ sp + cp * y,
511
+ -cy * cp - sy * x + cy * sp * y
512
+ ];
513
+ const n = Math.hypot(...d);
514
+ return [
515
+ d[0] / n,
516
+ d[1] / n,
517
+ d[2] / n
518
+ ];
519
+ };
520
+ /**
521
+ * Distance along the ray from o (inside the map) in the unit direction d to the first wall, step
522
+ * face, floor or ceiling, at most max.
523
+ *
524
+ * Walks the sectors: in the current convex one the ray leaves through the edge with the least
525
+ * crossing distance among the edges it goes outward through, or ends earlier on the floor or the
526
+ * ceiling. A solid edge, or a portal whose opening does not hold the crossing height, ends it.
527
+ */
528
+ var trace = (lvl, o, d, max) => {
529
+ const { map, edges } = lvl;
530
+ let s = Math.max(sectorAt(lvl, o[0], o[2]), 0);
531
+ let t = 0;
532
+ for (let hop = 0; hop <= map.sectors.length; hop++) {
533
+ const { floor, ceil } = map.sectors[s];
534
+ let exit = Infinity;
535
+ let through;
536
+ for (const e of edges) {
537
+ if (e.front !== s) continue;
538
+ const [ex, ez] = [e.bx - e.ax, e.bz - e.az];
539
+ const out = d[2] * ex - d[0] * ez;
540
+ if (out >= 0) continue;
541
+ const x = Math.max(((o[2] - e.az) * ex - (o[0] - e.ax) * ez) / -out, t);
542
+ const u = ((o[0] + x * d[0] - e.ax) * ex + (o[2] + x * d[2] - e.az) * ez) / (ex * ex + ez * ez);
543
+ if (u > -1e-9 && u < 1 + 1e-9 && (x < exit - 1e-9 || x < exit + 1e-9 && e.back < 0)) [exit, through] = [x, e];
544
+ }
545
+ const flat = d[1] < 0 ? (floor - o[1]) / d[1] : d[1] > 0 ? (ceil - o[1]) / d[1] : Infinity;
546
+ if (flat <= exit || !through) return Math.min(Math.max(flat, t), max);
547
+ if (exit >= max) return max;
548
+ const y = o[1] + exit * d[1];
549
+ const k = through.back < 0 ? void 0 : map.sectors[through.back];
550
+ if (!k || y < Math.max(floor, k.floor) || y > Math.min(ceil, k.ceil)) return exit;
551
+ [s, t] = [through.back, exit];
552
+ }
553
+ return t;
554
+ };
555
+ /**
556
+ * Distance at which the ray enters the upright cylinder of t (sides and caps), Infinity on a miss:
557
+ * the span of the ray inside the infinite cylinder, cut to the span between the cap planes.
558
+ */
559
+ var hit = (o, d, t) => {
560
+ const [px, pz] = [o[0] - t.x, o[2] - t.z];
561
+ const a = d[0] * d[0] + d[2] * d[2];
562
+ const b = px * d[0] + pz * d[2];
563
+ const c = px * px + pz * pz - t.r * t.r;
564
+ let [lo, hi] = [0, Infinity];
565
+ if (a > 1e-12) {
566
+ const q = b * b - a * c;
567
+ if (q < 0) return Infinity;
568
+ [lo, hi] = [Math.max(0, (-b - Math.sqrt(q)) / a), (-b + Math.sqrt(q)) / a];
569
+ } else if (c > 0) return Infinity;
570
+ const [y0, y1] = [t.y - o[1], t.y + t.h - o[1]];
571
+ if (d[1]) {
572
+ const [u, v] = [y0 / d[1], y1 / d[1]];
573
+ lo = Math.max(lo, Math.min(u, v));
574
+ hi = Math.min(hi, Math.max(u, v));
575
+ } else if (y0 > 0 || y1 < 0) return Infinity;
576
+ return lo <= hi ? lo : Infinity;
577
+ };
578
+ /** The body a shot sees of a player. */
579
+ var body = ({ id, x, y, z }) => ({
580
+ id,
581
+ x,
582
+ y,
583
+ z,
584
+ r: PLAYER_R,
585
+ h: PLAYER_H
586
+ });
587
+ /** The body a shot sees of a monster. */
588
+ var monsterBody = ({ id, kind, x, y, z }) => {
589
+ const walker = kind === MONSTER.WALKER;
590
+ return {
591
+ id,
592
+ x,
593
+ y,
594
+ z,
595
+ r: walker ? WALKER_R : FLYER_R,
596
+ h: walker ? WALKER_H : FLYER_H
597
+ };
598
+ };
599
+ /**
600
+ * Resolves one shot of `shooter` (state after the step that fired) from its eye (feet + EYE)
601
+ * along aim(yaw, pitch, seq): the nearest of the level (trace) and the upright cylinders
602
+ * of `targets` (bodies: players, monsters) other than the shooter, within RANGE.
603
+ */
604
+ var fire = (lvl, shooter, seq, targets) => {
605
+ const o = [
606
+ shooter.x,
607
+ shooter.y + EYE,
608
+ shooter.z
609
+ ];
610
+ const d = aim(shooter.yaw, shooter.pitch, seq);
611
+ let t = trace(lvl, o, d, 100);
612
+ let id = -1;
613
+ for (const p of targets) {
614
+ const u = p.id === shooter.id ? Infinity : hit(o, d, p);
615
+ if (u < t) [t, id] = [u, p.id];
616
+ }
617
+ return {
618
+ id: shooter.id,
619
+ x: o[0] + d[0] * t,
620
+ y: o[1] + d[1] * t,
621
+ z: o[2] + d[2] * t,
622
+ hit: id
623
+ };
624
+ };
625
+ // src/shared/monsters.ts
626
+ var DT = 1 / 60;
627
+ /** Radians a monster turns per tick toward its target. */
628
+ var TURN$1 = .05;
629
+ /** A patrolling monster moves at this share of its speed. */
630
+ var PATROL = .4;
631
+ /** A chasing monster stops this close (metres): inside MELEE_R, short of standing in the player. */
632
+ var STOP = 1;
633
+ /** Ticks between the start of a swing and its blow. */
634
+ var SWING_DELAY = 15;
635
+ /** Height of a player's chest above the feet: where monsters aim. */
636
+ var CHEST = 1.2;
637
+ /** The snapshot counts bullets with a u8. */
638
+ var MAX_BULLETS = 255;
639
+ /** Mulberry32: a small seeded generator, uniform in [0, 1). */
640
+ var mulberry32 = (seed) => {
641
+ let a = seed | 0;
642
+ return () => {
643
+ a = a + 1831565813 | 0;
644
+ let t = Math.imul(a ^ a >>> 15, 1 | a);
645
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
646
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
647
+ };
648
+ };
649
+ /** The monsters of the level's map, from the first spawn. */
650
+ var createHorde = (lvl, rand) => {
651
+ const def = (lvl.map.monsters ?? []).slice(0, 64);
652
+ let mobs = [];
653
+ let shells = [];
654
+ const events = [];
655
+ let tick = 0;
656
+ let nextBullet = 0;
657
+ let wait = 0;
658
+ const spawnAll = () => {
659
+ mobs = def.map(([x, z, yaw, kind], i) => {
660
+ const { floor, ceil } = lvl.map.sectors[Math.max(sectorAt(lvl, x, z), 0)];
661
+ const flyer = kind === MONSTER.FLYER;
662
+ return {
663
+ id: 16 + i,
664
+ kind,
665
+ x: Math.fround(x),
666
+ y: Math.fround(flyer ? Math.min(floor + FLYER_HOVER, ceil - FLYER_H) : floor),
667
+ z: Math.fround(z),
668
+ yaw: norm(yaw),
669
+ chase: false,
670
+ vy: 0,
671
+ ground: true,
672
+ target: -1,
673
+ turn: Math.floor(rand() * 240),
674
+ melee: 0,
675
+ swing: 0,
676
+ shoot: Math.floor(rand() * 90)
677
+ };
678
+ });
679
+ };
680
+ spawnAll();
681
+ const mid = (m) => m.y + monsterBody(m).h / 2;
682
+ const eye = (m) => [
683
+ m.x,
684
+ m.kind === MONSTER.WALKER ? m.y + EYE : mid(m),
685
+ m.z
686
+ ];
687
+ const eyeOf = (p) => [
688
+ p.x,
689
+ p.y + EYE,
690
+ p.z
691
+ ];
692
+ const hunt = (m, id) => {
693
+ m.target = id;
694
+ m.chase = id >= 0;
695
+ };
696
+ /** The monsters within ALERT_R of `src` that it can see, and that are not hunting, hunt `who`. */
697
+ const alert = (src, who) => {
698
+ for (const m of mobs) if (m !== src && !m.chase && Math.hypot(m.x - src.x, m.z - src.z) < 12 && !blocked(lvl, eye(src), eye(m))) hunt(m, who);
699
+ };
700
+ /** The nearest player in range, inside the sight cone and not hidden becomes the target. */
701
+ const look = (m, players) => {
702
+ const [fx, fz] = forward(m.yaw);
703
+ let seen;
704
+ let near = Infinity;
705
+ for (const p of players) {
706
+ const [dx, dz] = [p.x - m.x, p.z - m.z];
707
+ const d = Math.hypot(dx, dz);
708
+ if (d <= 30 && d < near && dx * fx + dz * fz >= SIGHT_COS * d && !blocked(lvl, eye(m), eyeOf(p))) [seen, near] = [p, d];
709
+ }
710
+ if (seen) {
711
+ const spotted = !m.chase;
712
+ hunt(m, seen.id);
713
+ if (spotted) alert(m, seen.id);
714
+ }
715
+ };
716
+ const turnTo = (m, yaw) => {
717
+ const arc = ((yaw - m.yaw + Math.PI) % TAU + TAU) % TAU - Math.PI;
718
+ m.yaw = norm(m.yaw + Math.max(-.05, Math.min(TURN$1, arc)));
719
+ };
720
+ /** Whether the floor under the axis is more than a step below `y`. */
721
+ const ledge = (m, y) => lvl.map.sectors[Math.max(sectorAt(lvl, m.x, m.z), 0)].floor < y - STEP_H;
722
+ const patrol = (m) => {
723
+ const s = (m.kind === MONSTER.WALKER ? WALKER_SPEED : FLYER_SPEED) * PATROL * DT;
724
+ const [fx, fz] = forward(m.yaw);
725
+ const before = {
726
+ x: m.x,
727
+ y: m.y,
728
+ z: m.z,
729
+ vy: m.vy,
730
+ ground: m.ground
731
+ };
732
+ if (m.kind === MONSTER.WALKER) walk(m, fx * s, fz * s, false, lvl);
733
+ else fly(m, fx * s, -s, fz * s, lvl);
734
+ const drop = m.kind === MONSTER.WALKER && ledge(m, before.y);
735
+ if (drop || Math.hypot(m.x - before.x, m.z - before.z) < s / 2) {
736
+ if (drop) Object.assign(m, before);
737
+ m.yaw = norm(m.yaw + rand() * TAU);
738
+ } else if (--m.turn <= 0) {
739
+ m.turn = 120 + Math.floor(rand() * 240);
740
+ m.yaw = norm(m.yaw + (rand() - .5) * Math.PI);
741
+ }
742
+ };
743
+ /** A walker that sees the player fires a bullet from its eye at the chest, and waits. */
744
+ const shootAt = (m, p) => {
745
+ const [ox, oy, oz] = eye(m);
746
+ if (shells.length >= MAX_BULLETS || blocked(lvl, [
747
+ ox,
748
+ oy,
749
+ oz
750
+ ], eyeOf(p))) {
751
+ m.shoot = 0;
752
+ return;
753
+ }
754
+ const v = [
755
+ p.x - ox,
756
+ p.y + CHEST - oy,
757
+ p.z - oz
758
+ ];
759
+ const k = 12 * DT / Math.hypot(...v);
760
+ shells.push({
761
+ id: nextBullet++ & 255,
762
+ x: ox,
763
+ y: oy,
764
+ z: oz,
765
+ vx: v[0] * k,
766
+ vy: v[1] * k,
767
+ vz: v[2] * k,
768
+ life: 300
769
+ });
770
+ m.shoot = 90 + Math.floor((rand() - .5) * 20);
771
+ };
772
+ const chase = (m, p) => {
773
+ const [dx, dz] = [p.x - m.x, p.z - m.z];
774
+ const d = Math.hypot(dx, dz);
775
+ if (d > 1e-6) turnTo(m, Math.atan2(-dx, -dz));
776
+ if (m.kind === MONSTER.WALKER) {
777
+ const [fx, fz] = forward(m.yaw);
778
+ const s = d > STOP ? WALKER_SPEED * DT : 0;
779
+ walk(m, fx * s, fz * s, false, lvl);
780
+ } else {
781
+ const dy = p.y + CHEST - FLYER_H / 2 - m.y;
782
+ const k = Math.min(1, FLYER_SPEED * DT / (Math.hypot(d, dy) || 1));
783
+ fly(m, d > STOP ? dx * k : 0, dy * k, d > STOP ? dz * k : 0, lvl);
784
+ }
785
+ const near = Math.hypot(p.x - m.x, p.z - m.z) <= 1.4 && m.y < p.y + 1.8 && p.y < m.y + monsterBody(m).h;
786
+ m.melee = Math.max(0, m.melee - 1);
787
+ if (m.swing && !--m.swing && near) {
788
+ const [fx, fz] = forward(m.yaw);
789
+ if ((p.x - m.x) * fx + (p.z - m.z) * fz > 0) events.push({
790
+ type: EVENT.HURT,
791
+ id: p.id,
792
+ x: p.x,
793
+ y: p.y + CHEST,
794
+ z: p.z
795
+ });
796
+ }
797
+ if (near && !m.melee) {
798
+ events.push({
799
+ type: EVENT.SWING,
800
+ id: m.id,
801
+ x: m.x,
802
+ y: mid(m),
803
+ z: m.z
804
+ });
805
+ [m.melee, m.swing] = [45, SWING_DELAY];
806
+ }
807
+ if (m.kind === MONSTER.WALKER && m.shoot-- <= 0 && d <= 30) shootAt(m, p);
808
+ };
809
+ /** Moves a bullet one tick; false when it is spent: it hit a player or the level, or timed out. */
810
+ const advance = (b, players) => {
811
+ const len = Math.hypot(b.vx, b.vy, b.vz);
812
+ const o = [
813
+ b.x,
814
+ b.y,
815
+ b.z
816
+ ];
817
+ const dir = [
818
+ b.vx / len,
819
+ b.vy / len,
820
+ b.vz / len
821
+ ];
822
+ let t = trace(lvl, o, dir, len);
823
+ let who = -1;
824
+ for (const p of players) {
825
+ const u = hit(o, dir, {
826
+ id: p.id,
827
+ x: p.x,
828
+ y: p.y - BULLET_R,
829
+ z: p.z,
830
+ r: PLAYER_R + BULLET_R,
831
+ h: PLAYER_H + 2 * BULLET_R
832
+ });
833
+ if (u < t) [t, who] = [u, p.id];
834
+ }
835
+ [b.x, b.y, b.z] = [
836
+ o[0] + dir[0] * t,
837
+ o[1] + dir[1] * t,
838
+ o[2] + dir[2] * t
839
+ ];
840
+ if (who >= 0) events.push({
841
+ type: EVENT.HURT,
842
+ id: who,
843
+ x: b.x,
844
+ y: b.y,
845
+ z: b.z
846
+ });
847
+ else if (t < len) events.push({
848
+ type: EVENT.BOOM,
849
+ id: b.id,
850
+ x: b.x,
851
+ y: b.y,
852
+ z: b.z
853
+ });
854
+ return who < 0 && t >= len && --b.life > 0;
855
+ };
856
+ return {
857
+ monsters: () => mobs.map(({ id, kind, x, y, z, yaw, chase }) => ({
858
+ id,
859
+ kind,
860
+ x,
861
+ y,
862
+ z,
863
+ yaw,
864
+ chase
865
+ })),
866
+ bullets: () => shells.map(({ id, x, y, z }) => ({
867
+ id,
868
+ x,
869
+ y,
870
+ z
871
+ })),
872
+ events,
873
+ step: (players) => {
874
+ tick++;
875
+ for (const m of mobs) {
876
+ if ((tick + m.id) % 60 === 0) look(m, players);
877
+ const target = players.find((p) => p.id === m.target);
878
+ if (m.chase && !target) hunt(m, -1);
879
+ if (target) chase(m, target);
880
+ else patrol(m);
881
+ }
882
+ shells = shells.filter((b) => advance(b, players));
883
+ if (!mobs.length && def.length && --wait <= 0) spawnAll();
884
+ },
885
+ kill: (id, by) => {
886
+ const i = mobs.findIndex((m) => m.id === id);
887
+ if (i < 0) return;
888
+ const [m] = mobs.splice(i, 1);
889
+ events.push({
890
+ type: EVENT.DIE,
891
+ id,
892
+ x: m.x,
893
+ y: mid(m),
894
+ z: m.z
895
+ });
896
+ alert(m, by);
897
+ wait = 300;
898
+ }
339
899
  };
340
900
  };
341
901
  var TURN = 65536 / (2 * Math.PI);
@@ -348,18 +908,23 @@ var fromPitch = (w) => w / 1e4;
348
908
  var fromTurn = (w) => w / TURN;
349
909
  /** Null on anything that is not a well-formed input frame. */
350
910
  var decodeInput = (buf) => {
351
- if (buf.byteLength !== 8) return null;
911
+ if (buf.byteLength !== 11) return null;
352
912
  const v = new DataView(buf);
353
913
  if (v.getUint8(0) !== 1) return null;
354
914
  return {
355
915
  seq: v.getUint16(1),
356
916
  keys: v.getUint8(3),
357
917
  yaw: fromTurn(v.getUint16(4)),
358
- pitch: fromPitch(v.getInt16(6))
918
+ pitch: fromPitch(v.getInt16(6)),
919
+ view: (v.getUint16(8) * 256 + v.getUint8(10)) / 256
359
920
  };
360
921
  };
361
922
  var encodeSnapshot = (s) => {
362
- const v = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(4 + 24 * s.players.length));
923
+ const shots = 4 + 24 * s.players.length;
924
+ const monsters = shots + 1 + 14 * s.shots.length;
925
+ const bullets = monsters + 1 + 16 * s.monsters.length;
926
+ const events = bullets + 1 + 13 * s.bullets.length;
927
+ const v = new DataView(new ArrayBuffer(events + 1 + 14 * s.events.length));
363
928
  v.setUint8(0, 2);
364
929
  v.setUint16(1, s.tick & 65535);
365
930
  v.setUint8(3, s.players.length);
@@ -373,7 +938,43 @@ var encodeSnapshot = (s) => {
373
938
  v.setUint16(o + 17, toTurn(p.yaw));
374
939
  v.setInt16(o + 19, toPitch(p.pitch));
375
940
  v.setUint16(o + 21, p.ack & 65535);
376
- v.setUint8(o + 23, +p.ground);
941
+ v.setUint8(o + 23, +p.ground | p.cool << 1);
942
+ });
943
+ v.setUint8(shots, s.shots.length);
944
+ s.shots.forEach((h, i) => {
945
+ const o = shots + 1 + i * 14;
946
+ v.setUint8(o, h.id);
947
+ v.setFloat32(o + 1, h.x);
948
+ v.setFloat32(o + 5, h.y);
949
+ v.setFloat32(o + 9, h.z);
950
+ v.setUint8(o + 13, h.hit & 255);
951
+ });
952
+ v.setUint8(monsters, s.monsters.length);
953
+ s.monsters.forEach((m, i) => {
954
+ const o = monsters + 1 + i * 16;
955
+ v.setUint8(o, m.id);
956
+ v.setUint8(o + 1, m.kind & 1 | +m.chase << 1);
957
+ v.setFloat32(o + 2, m.x);
958
+ v.setFloat32(o + 6, m.y);
959
+ v.setFloat32(o + 10, m.z);
960
+ v.setUint16(o + 14, toTurn(m.yaw));
961
+ });
962
+ v.setUint8(bullets, s.bullets.length);
963
+ s.bullets.forEach((b, i) => {
964
+ const o = bullets + 1 + i * 13;
965
+ v.setUint8(o, b.id);
966
+ v.setFloat32(o + 1, b.x);
967
+ v.setFloat32(o + 5, b.y);
968
+ v.setFloat32(o + 9, b.z);
969
+ });
970
+ v.setUint8(events, s.events.length);
971
+ s.events.forEach((e, i) => {
972
+ const o = events + 1 + i * 14;
973
+ v.setUint8(o, e.type);
974
+ v.setUint8(o + 1, e.id);
975
+ v.setFloat32(o + 2, e.x);
976
+ v.setFloat32(o + 6, e.y);
977
+ v.setFloat32(o + 10, e.z);
377
978
  });
378
979
  return v.buffer;
379
980
  };
@@ -432,22 +1033,33 @@ var setEvery = (cb, ms) => {
432
1033
  * taken by another player; 'full' beyond rules.maxPlayers. Everyone gets a fresh 'roster' on
433
1034
  * every join and leave.
434
1035
  * - Each input frame moves its player at once with move(); the INPUT_BURST bank drops the excess.
435
- * - Every SNAP_EVERY ticks of TICK_HZ, one snapshot with every player goes to every peer.
1036
+ * A step that fires resolves its shot at once with fire(), the other players rewound to the
1037
+ * view tick of the input (lag compensation, at most MAX_REWIND ticks back).
1038
+ * - The room owns the horde (monsters.ts), stepped every tick while a player is present. A shot
1039
+ * rewinds the monsters with the players, and one that hits a monster kills it.
1040
+ * - Every SNAP_EVERY ticks of TICK_HZ, one snapshot with every player, the shots resolved since
1041
+ * the last one, the monsters, the bullets and the events since the last one goes to every peer.
436
1042
  */
437
1043
  var Room = class {
438
1044
  /** Every connected peer; null until it joins. */
439
1045
  peers = /* @__PURE__ */ new Map();
440
1046
  ticks = 0;
1047
+ /** The players and monsters as each snapshot of the last MAX_REWIND ticks sent them. */
1048
+ history = [];
1049
+ horde;
1050
+ /** Shots resolved since the last snapshot. */
1051
+ shots = [];
441
1052
  halt;
442
1053
  rules;
443
1054
  /** Round-robin cursor over the spawn points, used once they are all taken. */
444
1055
  rr = 0;
445
- /** Missing rules fall back to RULES. */
446
- constructor(rules = {}) {
1056
+ /** Missing rules fall back to RULES. The seed drives the monsters. */
1057
+ constructor(rules = {}, seed = Date.now()) {
447
1058
  this.rules = {
448
1059
  ...RULES,
449
1060
  ...rules
450
1061
  };
1062
+ this.horde = createHorde(LEVEL, mulberry32(seed));
451
1063
  }
452
1064
  /** Number of joined players. */
453
1065
  get size() {
@@ -468,7 +1080,11 @@ var Room = class {
468
1080
  const input = p && decodeInput(data);
469
1081
  if (input && p.bank > 0) {
470
1082
  p.bank--;
471
- move(p.state, input, LEVEL);
1083
+ if (move(p.state, input, LEVEL)) {
1084
+ const shot = fire(LEVEL, p.state, input.seq, this.rewind(p, input.view));
1085
+ this.shots.push(shot);
1086
+ if (shot.hit >= 16) this.horde.kill(shot.hit, p.state.id);
1087
+ }
472
1088
  p.ack = input.seq;
473
1089
  }
474
1090
  }
@@ -483,14 +1099,27 @@ var Room = class {
483
1099
  const players = this.players();
484
1100
  if (!players.length) return;
485
1101
  players.forEach((p) => p.bank = Math.min(10, p.bank + 1));
1102
+ this.horde.step(players.map((p) => p.state));
486
1103
  if (++this.ticks % 2 === 0) {
1104
+ const monsters = this.horde.monsters();
1105
+ this.history.push({
1106
+ tick: this.ticks,
1107
+ players: players.map((p) => ({ ...p.state })),
1108
+ monsters
1109
+ });
1110
+ while (this.history[0].tick < this.ticks - 30) this.history.shift();
487
1111
  const snap = encodeSnapshot({
488
1112
  tick: this.ticks,
489
1113
  players: players.map((p) => ({
490
1114
  ...p.state,
491
1115
  ack: p.ack
492
- }))
1116
+ })),
1117
+ shots: this.shots,
1118
+ monsters,
1119
+ bullets: this.horde.bullets(),
1120
+ events: this.horde.events.splice(0, 255)
493
1121
  });
1122
+ this.shots = [];
494
1123
  players.forEach((p) => p.conn.send(snap));
495
1124
  }
496
1125
  }
@@ -521,6 +1150,36 @@ var Room = class {
521
1150
  this.halt?.();
522
1151
  this.halt = void 0;
523
1152
  }
1153
+ /**
1154
+ * The bodies a shot of `shooter` can hit as the shooter drew them at `view` (a u16 tick,
1155
+ * fractional, read against the current tick and clamped to the kept history): the other players
1156
+ * and the monsters, x, y, z interpolated between the two snapshots around it like the client
1157
+ * does. One the history does not hold stands where it is.
1158
+ */
1159
+ rewind(shooter, view = 0) {
1160
+ const now = this.players().filter((p) => p !== shooter).map((p) => p.state);
1161
+ const mobs = this.horde.monsters();
1162
+ const [first, last] = [this.history[0], this.history.at(-1)];
1163
+ if (!first || !last) return [...now.map(body), ...mobs.map(monsterBody)];
1164
+ const back = ((this.ticks - view + 32768) % 65536 + 65536) % 65536 - 32768;
1165
+ const t = Math.min(Math.max(this.ticks - back, first.tick), last.tick);
1166
+ let k = 0;
1167
+ while (k + 1 < this.history.length && this.history[k + 1].tick <= t) k++;
1168
+ const [a, b] = [this.history[k], this.history[k + 1] ?? this.history[k]];
1169
+ const u = b.tick > a.tick ? (t - a.tick) / (b.tick - a.tick) : 0;
1170
+ const l = (m, n) => m + (n - m) * u;
1171
+ const at = (cur, list) => cur.map((p) => {
1172
+ const pa = list(a).find((q) => q.id === p.id);
1173
+ const pb = list(b).find((q) => q.id === p.id);
1174
+ return pa && pb ? {
1175
+ ...pb,
1176
+ x: l(pa.x, pb.x),
1177
+ y: l(pa.y, pb.y),
1178
+ z: l(pa.z, pb.z)
1179
+ } : pb ?? pa ?? p;
1180
+ });
1181
+ return [...at(now, (h) => h.players).map(body), ...at(mobs, (h) => h.monsters).map(monsterBody)];
1182
+ }
524
1183
  players() {
525
1184
  return [...this.peers.values()].filter((p) => p !== null);
526
1185
  }