silphius/app/engine/engine.js
2024-06-21 04:53:09 -05:00

245 lines
5.8 KiB
JavaScript

import {
TPS,
} from '@/constants.js';
import Ecs from '@/ecs/ecs.js';
import Components from '@/ecs-components/index.js';
import Systems from '@/ecs-systems/index.js';
import {decode, encode} from '@/packets/index.js';
function join(...parts) {
return parts.join('/');
}
export default class Engine {
incomingActions = [];
connections = [];
connectedPlayers = new Map();
ecses = {};
frame = 0;
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));
}
}
this.server = new SilphiusServer();
this.server.addPacketListener('Action', (connection, payload) => {
this.incomingActions.push([this.connectedPlayers.get(connection).entity, payload]);
});
}
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 = ecs.create(entityJson);
this.connections.push(connection);
this.connectedPlayers.set(
connection,
{
entity: ecs.get(entity),
id,
memory: new Set(),
},
);
}
createEcs() {
return new Ecs({Components, Systems});
}
async createHomestead(id) {
const ecs = this.createEcs();
const area = {x: 100, y: 60};
ecs.create({
AreaSize: {x: area.x * 16, y: area.y * 16},
TileLayers: {
layers: [
{
area,
data: Array(area.x * area.y).fill(0).map(() => 1 + Math.floor(Math.random() * 4)),
source: '/assets/tileset.json',
tileSize: {x: 16, y: 16},
}
],
},
});
const defaultSystems = [
'ApplyControlItem',
'ApplyControlMovement',
'ApplyMomentum',
'ClampPositions',
'FollowCamera',
'CalculateAabbs',
'UpdateSpatialHash',
'ControlDirection',
'SpriteDirection',
'RunAnimations',
];
defaultSystems.forEach((defaultSystem) => {
ecs.system(defaultSystem).active = true;
});
const view = Ecs.serialize(ecs);
await this.server.writeData(
join('homesteads', `${id}`),
view,
);
}
async createPlayer(id) {
const player = {
Camera: {},
Controlled: {},
Direction: {direction: 2},
Ecs: {path: join('homesteads', `${id}`)},
Momentum: {},
Position: {x: 368, y: 368},
VisibleAabb: {},
Speed: {speed: 100},
Sprite: {
animation: 'moving:down',
frame: 0,
frames: 8,
source: '/assets/dude.json',
speed: 0.115,
},
Wielder: {
activeSlot: 0,
},
};
const buffer = (new TextEncoder()).encode(JSON.stringify(player));
await this.server.writeData(
join('players', `${id}`),
buffer,
);
return buffer;
}
async disconnectPlayer(connection) {
const {entity, id} = this.connectedPlayers.get(connection);
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] = Ecs.deserialize(
this.createEcs(),
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.createHomestead(id);
buffer = await this.createPlayer(id);
}
return JSON.parse((new TextDecoder()).decode(buffer));
}
async savePlayer(id, entity) {
const encoder = new TextEncoder();
const buffer = encoder.encode(JSON.stringify(entity.toJSON()));
await this.server.writeData(['players', `${id}`].join('/'), buffer);
}
start() {
return setInterval(() => {
const elapsed = (Date.now() - this.last) / 1000;
this.last = Date.now();
this.tick(elapsed);
this.update(elapsed);
this.frame += 1;
}, 1000 / TPS);
}
tick(elapsed) {
for (const i in this.ecses) {
this.ecses[i].setClean();
}
// TODO: SANITIZE
for (const [{Controlled}, payload] of this.incomingActions) {
Controlled[payload.type] = payload.value;
}
this.incomingActions = [];
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];
const nearby = ecs.system('UpdateSpatialHash').nearby(entity);
// 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;
}
}