silphius/app/engine.js
2024-07-02 20:43:55 -05:00

277 lines
6.9 KiB
JavaScript

import {
RESOLUTION,
TPS,
} from '@/constants.js';
import Ecs from '@/ecs/ecs.js';
import {decode, encode} from '@/packets/index.js';
import Script from '@/util/script.js';
import createEcs from './create-ecs.js';
import createHomestead from './create-homestead.js';
import createPlayer from './create-player.js';
export default class Engine {
connections = [];
connectedPlayers = new Map();
connectingPlayers = [];
ecses = {};
frame = 0;
handle;
incomingActions = [];
last = Date.now();
server;
constructor(Server) {
this.ecses = {};
class SilphiusServer extends Server {
accept(connection, packed) {
super.accept(connection, decode(packed));
}
transmit(connection, packet) {
super.transmit(connection, encode(packet));
}
}
const server = this.server = new SilphiusServer();
this.Ecs = class EngineEcs extends Ecs {
async readAsset(uri) {
return server.readAsset(uri);
}
async readJson(uri) {
const chars = await this.readAsset(uri);
return chars.byteLength > 0 ? JSON.parse((new TextDecoder()).decode(chars)) : {};
}
async readScript(uri, context) {
const code = await this.readAsset(uri);
if (code.byteLength > 0) {
return Script.fromCode((new TextDecoder()).decode(code), context);
}
}
}
this.server.addPacketListener('Action', (connection, payload) => {
this.incomingActions.push([connection, payload]);
});
}
acceptActions() {
for (const [
connection,
payload,
] of this.incomingActions) {
if (!this.connectedPlayers.get(connection)) {
continue;
}
const {entity} = this.connectedPlayers.get(connection);
const {Controlled, Ecs, Interacts, Inventory, Wielder} = entity;
switch (payload.type) {
case 'changeSlot': {
if (!Controlled.locked) {
Wielder.activeSlot = payload.value - 1;
}
break;
}
case 'moveUp':
case 'moveRight':
case 'moveDown':
case 'moveLeft': {
Controlled[payload.type] = payload.value;
break;
}
case 'swapSlots': {
if (!Controlled.locked) {
Inventory.swapSlots(...payload.value);
}
break;
}
case 'use': {
if (!Controlled.locked) {
Wielder.useActiveItem(payload.value);
}
break;
}
case 'interact': {
if (!Controlled.locked) {
if (payload.value) {
if (Interacts.willInteractWith) {
const ecs = this.ecses[Ecs.path];
const subject = ecs.get(Interacts.willInteractWith);
subject.Interactive.interact(entity);
}
}
}
break;
}
}
}
this.incomingActions = [];
}
async connectPlayer(connection, id) {
const entityJson = await this.loadPlayer(id);
if (!this.ecses[entityJson.Ecs.path]) {
await this.loadEcs(entityJson.Ecs.path);
}
const ecs = this.ecses[entityJson.Ecs.path];
const entity = await ecs.create(entityJson);
this.connections.push(connection);
this.connectedPlayers.set(
connection,
{
entity: ecs.get(entity),
id,
memory: new Set(),
},
);
}
async disconnectPlayer(connection) {
const connectedPlayer = this.connectedPlayers.get(connection);
if (!connectedPlayer) {
return;
}
const {entity, id} = connectedPlayer;
const ecs = this.ecses[entity.Ecs.path];
await this.savePlayer(id, entity);
ecs.destroy(entity.id);
this.connectedPlayers.delete(connection);
this.connections.splice(this.connections.indexOf(connection), 1);
}
async load() {
}
async loadEcs(path) {
this.ecses[path] = await this.Ecs.deserialize(
createEcs(this.Ecs),
await this.server.readData(path),
);
}
async loadPlayer(id) {
let buffer;
try {
buffer = await this.server.readData(['players', `${id}`].join('/'))
}
catch (error) {
if ('ENOENT' !== error.code) {
throw error;
}
await this.saveEcs(
['homesteads', `${id}`].join('/'),
await createHomestead(this.Ecs),
);
buffer = await createPlayer(id);
await this.server.writeData(
['players', `${id}`].join('/'),
buffer,
);
}
return JSON.parse((new TextDecoder()).decode(buffer));
}
async saveEcs(path, ecs) {
const view = this.Ecs.serialize(ecs);
await this.server.writeData(path, view);
}
async saveEcses() {
const promises = []
for (const i in this.ecses) {
promises.push(this.saveEcs(i, this.ecses[i]));
}
await Promise.all(promises);
}
async savePlayer(id, entity) {
const encoder = new TextEncoder();
const buffer = encoder.encode(JSON.stringify(entity.toJSON()));
await this.server.writeData(['players', `${id}`].join('/'), buffer);
}
setClean() {
for (const i in this.ecses) {
this.ecses[i].setClean();
}
}
start() {
const loop = async () => {
this.acceptActions();
const elapsed = (Date.now() - this.last) / 1000;
this.last = Date.now();
this.tick(elapsed);
this.update(elapsed);
this.setClean();
this.frame += 1;
this.handle = setTimeout(loop, 1000 / TPS);
};
loop();
}
stop() {
clearTimeout(this.handle);
this.handle = undefined;
}
tick(elapsed) {
for (const i in this.ecses) {
this.ecses[i].tick(elapsed);
}
}
update(elapsed) {
for (const connection of this.connections) {
this.server.send(
connection,
{
type: 'Tick',
payload: {
ecs: this.updateFor(connection),
elapsed,
frame: this.frame,
},
},
);
}
}
updateFor(connection) {
const update = {};
const {entity, memory} = this.connectedPlayers.get(connection);
const mainEntityId = entity.id;
const ecs = this.ecses[entity.Ecs.path];
// Entities within half a screen offscreen.
const x0 = entity.Position.x - RESOLUTION.x;
const y0 = entity.Position.y - RESOLUTION.y;
const nearby = ecs.system('VisibleAabbs').within({
x0,
x1: x0 + (RESOLUTION.x * 2),
y0,
y1: y0 + (RESOLUTION.y * 2),
});
// Master entity.
nearby.add(ecs.get(1));
const lastMemory = new Set(memory.values());
for (const entity of nearby) {
const {id} = entity;
lastMemory.delete(id);
if (!memory.has(id)) {
update[id] = entity.toJSON();
if (mainEntityId === id) {
update[id].MainEntity = {};
}
}
else if (ecs.diff[id]) {
update[id] = ecs.diff[id];
}
memory.add(id);
}
for (const id of lastMemory) {
memory.delete(id);
update[id] = false;
}
return update;
}
}