summaryrefslogtreecommitdiff
path: root/client/src/net/game.ts
blob: c8e59916ccedbf801cd0579ce47ae03b352be834 (plain)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import { Frame, GameState, Input, Key, KeyMap, PlayerInput } from "../types.js";
import { startInputListener } from "./input.js";
import { multiplayer } from "./multiplayer.js";

/**
 * @author tint
 * @template Data, Input
 */
export class Game {

    historysize: number
    history: Frame[]
    historyStart: number
    currentFrame: number
    advance: (pastData: GameState, input: Input, frame: number) => GameState

	constructor(history: number) {
		this.historysize = history;
		
		this.history = [];
		this.historyStart = 0;
		
		// the game may have inputs from the "future"
		// (local input delay to make sure inputs play at the same time on all machines)
		// so the "present" isn't always the latest frame
		// the game loop should set this every frame
		this.currentFrame = 0;
	}
	
	startHistory(frame: number, data: GameState) {
		this.historyStart = frame;
		this.history = [{ data, input: { players: {} }}];
		this.currentFrame = frame;
	}
	
	getHistory(frame: number): Frame {
		return this.history[frame - this.historyStart];
	}
	
	getFrame(): number {
		return this.historyStart + this.history.length - 1;
	}
	
	getCurrentData(): GameState {
		const entry = this.history[this.history.length - 1];
		return entry && entry.data;
	}
	
	/**
	 * Sets the input at a specific frame. If that frame is in history,
	 * the game will be rewound, the input applied, and then fast-forwarded to the current head.
	 * If the frame is ahead of the current latest frame, the game will be run until that frame.
	 */
	setInput(frame: number, input: Input) {
        console.log('input', frame, input)
		this.editFrame(frame, (index: number): void => {
			let past = this.history[index - 1];
			if(index === 0) {
				past = { data: undefined, input: undefined };
			}
			this.history[index] = {
				input,
				data: this.advance(past ? past.data : undefined, input, frame),
			};
		});
	}
	
	setData(frame: number, data: GameState) {
        console.log('data', frame, data)
		this.editFrame(frame, (index: number): void => {
			this.history[index] = {
				data,
				input: this.history[index] && this.history[index].input,
			}
		});
	}
	
	editFrame(frame: number, edit: (index: number) => void) {
		const head = this.historyStart + this.history.length;
		if(frame < head) {
			if(frame < this.historyStart) {
				throw new Error("Tried to edit a past frame not in history: " + frame);
			}
			
			edit(frame - this.historyStart);
			// fast forward back to the present with the new data
			for(let i = frame + 1; i < head; i++) {
				const past = this.history[i - this.historyStart - 1];
				this.history[i - this.historyStart].data = this.advance(
					past ? past.data : undefined,
					this.history[i - this.historyStart].input,
					i
				);
			}
		} else {
			// fast forward the inbetween frames with no input
			for(let i = head; i < frame; i++) {
				const entry = this.history[i - this.historyStart - 1];
				this.history[i - this.historyStart] = {
					input: undefined,
					data: this.advance(entry ? entry.data : undefined, undefined, i),
				};
			}
			edit(frame - this.historyStart);
		}
		
		while(this.history.length > this.historysize) {
			this.history.shift();
			this.historyStart++;
		}
	}

    start (
        code: string,
        keymap: KeyMap, 
        onLoad: (startFrame: Frame) => boolean,
        onFrame: (data: Frame, frame: number) => void,
        onLogic: (pastData: GameState, input: Input, frame: number) => GameState, 
        data: PlayerInput = { start: false, key: Key.NOTHING }
    ): void {
        
	    const fps = 60;
	    let delay = 3;

        this.advance = onLogic

        const onStart = (
            startFrame: number, 
            latency: number,
            _connection: number,
            update: (input: PlayerInput, frame: number) => void, 
            _ping: () => Promise<number>, 
            _desyncCheck: (frame: number) => Promise<boolean>,
        ) => { 
		    console.log("started game at frame", startFrame);
		    // window.desyncCheck = () => desyncCheck(this.currentFrame - 5);
            
		    let startTs = performance.now() - latency;
		    let lastFrame = startFrame;
		    update(data, startFrame + 1);

            let getInput = startInputListener(keymap)
            
            const startData = this.getHistory(startFrame)

            if (!onLoad(startData)) return false

		    let lastTs = performance.now();
            
            let loop = (ts: number) => {
                
			    const frame = Math.floor((ts - startTs) / 1000 * fps) + startFrame;

			    if(frame !== lastFrame) { // update input once per frame, regardless of the display refresh rate
			    	lastFrame = frame;
			    	
			    	// gather input
			    	const input: PlayerInput = getInput();
			    	
			    	// apply input
			    	update(input, frame + delay);
			    }

                this.currentFrame = frame
                const data = this.getHistory(frame)

                onFrame(data, frame)

                lastTs = ts

                requestAnimationFrame(loop)
            }

            requestAnimationFrame(loop)

		    if(startFrame === -1) {
			    update(data, 0);
		    }

            return true
        }

        multiplayer(this, code, onStart)

    }
}