humus-old/server/game.js
2019-04-20 14:16:06 -05:00

110 lines
2.9 KiB
JavaScript

// Node.
import msgpack from 'msgpack-lite';
import {performance} from 'perf_hooks';
// 3rd party.
// 2nd party.
import {InputPacket} from '@avocado/input';
import {Synchronizer} from '@avocado/state';
import {Ticker} from '@avocado/timing';
// 1st party.
import {WorldTime} from '../common/world-time';
import {createEntityForConnection} from './create-entity-for-connection';
import {createRoom} from './create-server-room';
// Create game.
export default class Game {
constructor() {
const config = this.readConfig();
// Room.
this.room = createRoom();
// World time. Start at 10 am for testing.
this.worldTime = new WorldTime();
this.worldTime.hour = 10;
// Entity tracking.
this.informables = [];
// State synchronization.
this.synchronizer = new Synchronizer({
room: this.room,
worldTime: this.worldTime,
});
this.informTicker = new Ticker(1 / 40);
this.informTicker.on('tick', () => {
// Inform entities of the new state.
for (let i = 0; i < this.informables.length; ++i) {
const entity = this.informables[i];
entity.inform(this.synchronizer.state);
}
});
// Simulation.
this.mainLoopHandle = setInterval(
this.createMainLoop(),
1000 * config.simulationInterval
);
}
acceptConnection(socket) {
// Create and track a new entity for the connection.
const entity = createEntityForConnection(socket);
// Track informables.
this.informables.push(entity);
entity.on('destroyed', () => {
const index = this.informables.indexOf(entity);
if (-1 !== index) {
this.informables.splice(index, 1);
}
});
// Add entity to room.
this.room.addEntityToLayer(entity, 'everything');
// Initial information.
entity.inform(this.synchronizer.state);
// Listen for events.
socket.on('packet', this.createPacketListener(socket));
socket.on('disconnect', this.createDisconnectionListener(socket));
}
destroy() {
clearInterval(this.mainLoopHandle);
for (let i = 0; i < this.informables.length; ++i) {
const entity = this.informables[i];
entity.socket.disconnect();
}
this.room.destroy();
}
createMainLoop() {
let lastTime = performance.now();
return () => {
const now = performance.now();
const elapsed = (now - lastTime) / 1000;
lastTime = now;
// Tick synchronized.
this.synchronizer.tick(elapsed);
// Tick informer.
this.informTicker.tick(elapsed);
}
}
createDisconnectionListener(socket) {
const {entity} = socket;
return () => {
entity.destroy();
};
}
createPacketListener(socket) {
const {entity} = socket;
return (packet) => {
if (packet instanceof InputPacket) {
entity.inputState = packet.toState();
}
};
}
readConfig() {
return {
simulationInterval: 1 / 80,
};
}
}