refactor: encode trait type for net

This commit is contained in:
cha0s 2019-09-30 19:23:11 -05:00
parent 147b8d1556
commit 37028a8bd9
2 changed files with 21 additions and 1 deletions

View File

@ -1,10 +1,14 @@
import {BundlePacket, SynchronizedUpdatePacket} from '@avocado/net';
import {idFromTrait, lookupTrait, traitFromId} from '../trait/registry';
export class EntityUpdateTraitPacket extends SynchronizedUpdatePacket {
static pack(packet) {
const data = packet.data[1];
for (let i = 0; i < data.traits.length; i++) {
const Trait = lookupTrait(data.traits[i].type);
data.traits[i].type = idFromTrait(Trait);
data.traits[i].packets = BundlePacket.packPacket(
new BundlePacket(data.traits[i].packets)
);
@ -16,7 +20,7 @@ export class EntityUpdateTraitPacket extends SynchronizedUpdatePacket {
return {
traits: [
{
type: 'string',
type: 'uint8',
packets: 'buffer',
},
],
@ -26,6 +30,8 @@ export class EntityUpdateTraitPacket extends SynchronizedUpdatePacket {
static unpack(packet) {
const data = super.unpack(packet);
for (let i = 0; i < data.traits.length; i++) {
const Trait = traitFromId(data.traits[i].type);
data.traits[i].type = Trait.type();
data.traits[i].packets = BundlePacket.unpack(data.traits[i].packets);
}
return data;

View File

@ -1,13 +1,27 @@
let traitId = 0;
const idToTraitMap = new Map();
const traitToIdMap = new Map();
const traitRegistry = new Map();
export function registerTrait(Trait) {
traitRegistry.set(Trait.type(), Trait);
traitToIdMap.set(Trait, traitId);
idToTraitMap.set(traitId, Trait);
traitId += 1;
}
export function hasTrait(type) {
return traitRegistry.has(type);
}
export function idFromTrait(Trait) {
return traitToIdMap.get(Trait);
}
export function lookupTrait(type) {
return traitRegistry.get(type);
}
export function traitFromId(id) {
return idToTraitMap.get(id);
}