Typed Array Buffer Schema (objects to buffer converter)

logo

Typed Array Buffer Schema

Hi everyone!

This is not really Phaser related, but I’m sure many of you can use it.

It’s a library to convert JavaScript Objects to ArrayBuffers.
Here is a introduction video I’ve made. And you will find the source code on github.

Usage

import { BufferSchema, Model } from '@geckos.io/typed-array-buffer-schema'
import { uint8, int16, uint16, uint64, string8 } from '@geckos.io/typed-array-buffer-schema'

// create the player schema
const playerSchema = BufferSchema.schema('player', {
  id: uint8,
  name: string8,
  x: { type: int16, digits: 2 },
  y: { type: int16, digits: 2 }
})

// create the main schema
const mainSchema = BufferSchema.schema('main', {
  time: uint64,
  tick: uint16,
  players: [playerSchema],
})

// create the main model
const mainModel = new Model(mainSchema)

// your game state
const gameState = {
  time: new Date().getTime(),
  tick: 32580,
  players: [
    { id: 0, name: 'Player1', x: -14.43, y: 47.78 },
    { id: 1, name: 'Player2', x: 21.85, y: -78.48 }
  ]
}

// toBuffer()
const buffer = mainModel.toBuffer(gameState)

// fromBuffer()
const data = mainModel.fromBuffer(buffer)

Hope you like it :smiley:

Hi, looks cool !
Friendly feedback/questions here…

  1. Diving a little bit in your code, my eyes went to flatten method and line 42 checking prop after looping them looks redundant?
  2. Why is needed to define a string id in " BufferSchema.schema('id', {...?
    I mean, in your examples, “player” and “main” ids are never used anymore, right?

Anyway very nice idea and great work.
Thanks for sharing!

Thanks :smiley:

I don’t know. I usually always use hasOwnProperty.
This is from developer.mozilla.org: If you only want to consider properties attached to the object itself, and not its prototypes, use getOwnPropertyNames() or perform a hasOwnProperty() check.

It is needed to create a unique id for the schema. I once had the issue that 2 schemas looked the same, so their hash (I use the schema’s hash for the id), where the same. By including a unique name, I can make sure the hashes will be unique.

1 Like