diff options
author | Elizabeth (Lizzy) Hunt <elizabeth.hunt@simponic.xyz> | 2023-08-26 17:57:05 -0600 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-08-26 17:57:05 -0600 |
commit | 8a4ab8d79b5ce1dabb431168398b5d5111fe326c (patch) | |
tree | e60767dc5295edf379cf421e20171dc418e548b7 /engine/systems/NetworkUpdate.ts | |
parent | c6e9baa0009f7cce0f6ff156a3957ef04a8cb684 (diff) | |
parent | 6ce6946a4401d2ee6fa5cb747fab7d4c658a63c8 (diff) | |
download | jumpstorm-8a4ab8d79b5ce1dabb431168398b5d5111fe326c.tar.gz jumpstorm-8a4ab8d79b5ce1dabb431168398b5d5111fe326c.zip |
Merge pull request #1 from Simponic/network
Network
Diffstat (limited to 'engine/systems/NetworkUpdate.ts')
-rw-r--r-- | engine/systems/NetworkUpdate.ts | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/engine/systems/NetworkUpdate.ts b/engine/systems/NetworkUpdate.ts new file mode 100644 index 0000000..6d13574 --- /dev/null +++ b/engine/systems/NetworkUpdate.ts @@ -0,0 +1,72 @@ +import { System, SystemNames } from '.'; +import { Game } from '../Game'; +import { ComponentNames } from '../components'; +import { + type MessageQueueProvider, + type MessagePublisher, + type MessageProcessor, + MessageType, + EntityUpdateBody +} from '../network'; + +export class NetworkUpdate extends System { + private queueProvider: MessageQueueProvider; + private publisher: MessagePublisher; + private messageProcessor: MessageProcessor; + + private entityUpdateTimers: Map<string, number>; + + constructor( + queueProvider: MessageQueueProvider, + publisher: MessagePublisher, + messageProcessor: MessageProcessor + ) { + super(SystemNames.NetworkUpdate); + + this.queueProvider = queueProvider; + this.publisher = publisher; + this.messageProcessor = messageProcessor; + + this.entityUpdateTimers = new Map(); + } + + public update(dt: number, game: Game) { + // 1. process new messages + this.queueProvider + .getNewMessages() + .forEach((message) => this.messageProcessor.process(message)); + this.queueProvider.clearMessages(); + + // 2. send entity updates + const updateMessages: EntityUpdateBody[] = []; + game.forEachEntityWithComponent( + ComponentNames.NetworkUpdateable, + (entity) => { + 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() + }); + } + } + ); + this.publisher.addMessage({ + type: MessageType.UPDATE_ENTITIES, + body: updateMessages + }); + + // 3. publish changes + this.publisher.publish(); + } + + private getNextUpdateTimeMs() { + return Math.random() * 70 + 50; + } +} |