base2020/src/Net/LockstepClient.ts

97 lines
3 KiB
TypeScript
Raw Normal View History

import { Callbag } from "callbag";
2020-02-16 02:10:19 +00:00
import animationFrames from "callbag-animation-frames";
import map from "callbag-map";
2020-04-03 22:35:23 +00:00
import pipe from "callbag-pipe";
import { INPUT_FREQUENCY, LockstepProcessor, LockstepState } from "../Ecs/Lockstep";
export const enum MessageTypes {
META = 0,
SET_STATE = 1,
INPUT = 2,
GET_STATE = 3,
PING = 4
}
export type Packet<TypeId, Payload> = { t: TypeId } & Payload;
export type ClientMessage<Input, State> =
| Packet<MessageTypes.SET_STATE, { s: Partial<State> }>
2020-02-16 05:42:58 +00:00
| Packet<MessageTypes.INPUT, { i: Input }>;
export type ServerMessage<Input, State> =
| Packet<MessageTypes.SET_STATE, { s: Partial<State> }>
| Packet<MessageTypes.INPUT, { i: Input }>;
2020-02-16 05:42:58 +00:00
export type Server<Input, State> = Callbag<ClientMessage<Input, State>, ServerMessage<Input, State>>;
export abstract class LockstepClient<Input, State> {
private state: LockstepState<Input, State>;
public constructor(
public readonly engine: LockstepProcessor<Input, State>,
) {
const initialState = this.initState({});
this.state = new LockstepState(initialState, engine);
}
public abstract initState(init: Partial<State>): State;
public abstract gatherInput(): Input;
/**
* Connect to a [perhaps emulated] server and return a disconnect callback
*/
public connect(server: Server<Input, State>): () => void {
let serverTalkback: Server<Input, State> | null = null;
const sampleInput = () => {
if (serverTalkback) {
const input = this.gatherInput();
this.state.addLocalInput(input);
2020-02-16 02:10:19 +00:00
serverTalkback(1, { t: MessageTypes.INPUT, i: input });
setTimeout(sampleInput, INPUT_FREQUENCY);
}
};
// connect to server
server(0, (mode: number, data: Server<Input, State> | ServerMessage<Input, State>) => {
if (mode == 0) {
serverTalkback = data as Server<Input, State>;
// kickoff input sender
setTimeout(sampleInput, INPUT_FREQUENCY);
} else if (mode == 1) {
// server message
const message = data as ServerMessage<Input, State>;
2020-02-16 02:10:19 +00:00
switch (message.t) {
case MessageTypes.SET_STATE:
const resetState = this.initState(message.s);
this.state = new LockstepState(resetState, this.engine);
break;
case MessageTypes.INPUT:
this.state.addCanonInput(message.i);
break;
}
} else if (mode == 2) {
// disconnected
console.log("Disconnected from server", data);
serverTalkback = null;
}
});
// disposal
return () => {
serverTalkback?.(2);
serverTalkback = null;
};
}
2020-04-03 22:35:23 +00:00
public renderFrames = pipe(
animationFrames,
map(_ms => this.state.getStateToRender())
);
2020-02-16 02:10:19 +00:00
}