aboutsummaryrefslogtreecommitdiff
path: root/static/src/main.ts
blob: eb98ba82ca31ae3d274ba70d639f3ca7602d8338 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import $ from "jquery";
import { Vec2 } from "./vector";
import {
  EventType,
  type SetControllableEvent,
  type Event,
  type EventPublisher,
} from "./event";
import { MouseController } from "./mouse_controller";
import {
  EntityPositionUpdateEvent,
  EventProcessor,
  EventQueue,
  WebSocketEventQueue,
} from "./network";

class KennelClient {
  private running: boolean;
  private last_update: number;

  private controllable_entities: Set<string>;
  private mouse_controller: MouseController;

  constructor(
    private readonly event_queue: EventQueue,
    private readonly event_publisher: EventPublisher,
  ) {
    this.last_update = 0;
    this.running = false;

    this.mouse_controller = new MouseController((position: Vec2) =>
      this.on_mouse_move(position),
    );
  }

  public start() {
    this.running = true;
    this.last_update = performance.now();
    this.mouse_controller.start();

    const loop = (timestamp: number) => {
      const dt = timestamp - this.last_update;
      this.propogate_state_after(dt);
      requestAnimationFrame(loop); // tail call recursion! /s
    };
    requestAnimationFrame(loop);
  }

  public close() {
    this.running = false;
    this.mouse_controller.stop();
    this.controllable_entities.clear();
  }

  private propogate_state_after(dt: number) {
    // TODO: interpolate cats and lasers and stuff
  }

  private on_mouse_move(position: Vec2) {
    for (const id of this.controllable_entities) {
      const event: EntityPositionUpdateEvent = {
        event_type: EventType.ENTITY_POSITION_UPDATE,
        data: { id, position: { x: position.x, y: position.y } },
      };
      this.event_publisher.send(event);
    }
  }
}

$(async () => {
  const session_id = await fetch("/assign", {
    credentials: "include",
  })
    .then((res) => res.json())
    .then(({ session }) => session);

  const ws = new WebSocket("/ws");
  await new Promise<void>((resolve) => {
    ws.onopen = () => resolve();
  });

  const queue: EventQueue = new WebSocketEventQueue(ws);

  const kennel_client = new KennelClient(session_id, null);

  ws.onclose = () => kennel_client.close();

  const mouse_controller = new MouseController(on_mouse_move);
  $(document).on("mousemove", (event) => {
    mouse_controller.move(event.clientX, event.clientY);
  });
  mouse_controller.start();
});