jumpstorm/engine/systems/NetworkUpdate.ts

73 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-08-25 18:48:17 -04:00
import { System, SystemNames } from '.';
import { Game } from '../Game';
2023-08-26 19:55:27 -04:00
import { ComponentNames } from '../components';
2023-08-23 21:44:59 -04:00
import {
type MessageQueueProvider,
type MessagePublisher,
2023-08-26 19:55:27 -04:00
type MessageProcessor,
MessageType,
EntityUpdateBody
2023-08-25 18:48:17 -04:00
} from '../network';
2023-08-13 18:47:58 -04:00
export class NetworkUpdate extends System {
private queueProvider: MessageQueueProvider;
private publisher: MessagePublisher;
2023-08-23 21:44:59 -04:00
private messageProcessor: MessageProcessor;
2023-08-26 19:55:27 -04:00
private entityUpdateTimers: Map<string, number>;
constructor(
queueProvider: MessageQueueProvider,
2023-08-23 21:44:59 -04:00
publisher: MessagePublisher,
2023-08-25 18:48:17 -04:00
messageProcessor: MessageProcessor
) {
2023-08-13 18:47:58 -04:00
super(SystemNames.NetworkUpdate);
this.queueProvider = queueProvider;
this.publisher = publisher;
2023-08-23 21:44:59 -04:00
this.messageProcessor = messageProcessor;
2023-08-26 19:55:27 -04:00
this.entityUpdateTimers = new Map();
2023-08-13 18:47:58 -04:00
}
2023-08-26 19:55:27 -04:00
public update(dt: number, game: Game) {
// 1. process new messages
2023-08-23 21:44:59 -04:00
this.queueProvider
.getNewMessages()
.forEach((message) => this.messageProcessor.process(message));
this.queueProvider.clearMessages();
2023-08-26 19:55:27 -04:00
// 2. send entity updates
const updateMessages: EntityUpdateBody[] = [];
game.forEachEntityWithComponent(
ComponentNames.NetworkUpdateable,
(entity) => {
2023-08-26 19:55:27 -04:00
let timer = this.entityUpdateTimers.get(entity.id) ?? dt;
timer -= dt;
this.entityUpdateTimers.set(entity.id, timer);
if (timer > 0) return;
this.entityUpdateTimers.set(entity.id, this.getNextUpdateTimeMs());
if (entity.hasComponent(ComponentNames.NetworkUpdateable)) {
updateMessages.push({
id: entity.id,
args: entity.serialize()
});
}
2023-08-25 18:48:17 -04:00
}
);
2023-08-26 19:55:27 -04:00
this.publisher.addMessage({
type: MessageType.UPDATE_ENTITIES,
body: updateMessages
});
2023-08-23 21:44:59 -04:00
2023-08-26 19:55:27 -04:00
// 3. publish changes
2023-08-23 21:44:59 -04:00
this.publisher.publish();
}
2023-08-26 19:55:27 -04:00
private getNextUpdateTimeMs() {
return Math.random() * 70 + 50;
}
2023-08-13 18:47:58 -04:00
}