1
0
mirror of https://github.com/tobspr/shapez.io.git synced 2025-06-13 13:04:03 +00:00
tobspr_shapez.io/src/js/savegame/serializer_internal.js

75 lines
2.1 KiB
JavaScript
Raw Normal View History

2020-05-14 19:54:11 +00:00
import { gComponentRegistry } from "../core/global_registries";
2020-05-09 14:45:23 +00:00
import { Entity } from "../game/entity";
import { enumLayer, GameRoot } from "../game/root";
2020-05-09 14:45:23 +00:00
// Internal serializer methods
export class SerializerInternal {
/**
* Serializes an array of entities
* @param {Array<Entity>} array
*/
serializeEntityArray(array) {
const serialized = [];
for (let i = 0; i < array.length; ++i) {
const entity = array[i];
if (!entity.queuedForDestroy && !entity.destroyed) {
serialized.push(entity.serialize());
}
}
return serialized;
}
/**
*
* @param {GameRoot} root
* @param {Array<any>} array
* @returns {string|void}
*/
2020-05-14 19:54:11 +00:00
deserializeEntityArray(root, array) {
2020-05-09 14:45:23 +00:00
for (let i = 0; i < array.length; ++i) {
this.deserializeEntity(root, array[i]);
2020-05-09 14:45:23 +00:00
}
}
/**
*
* @param {GameRoot} root
2020-05-14 19:54:11 +00:00
* @param {Entity} payload
2020-05-09 14:45:23 +00:00
*/
2020-05-14 19:54:11 +00:00
deserializeEntity(root, payload) {
2020-05-27 12:30:59 +00:00
const entity = new Entity(root);
2020-05-14 19:54:11 +00:00
this.deserializeComponents(entity, payload.components);
entity.layer = payload.layer;
if (!enumLayer[payload.layer]) {
assert(false, "Invalid layer: " + payload.layer);
}
2020-05-14 19:54:11 +00:00
root.entityMgr.registerEntity(entity, payload.uid);
if (entity.components.StaticMapEntity) {
root.map.placeStaticEntity(entity);
2020-05-09 14:45:23 +00:00
}
}
/////// COMPONENTS ////
/**
* Deserializes components of an entity
* @param {Entity} entity
* @param {Object.<string, any>} data
* @returns {string|void}
*/
deserializeComponents(entity, data) {
for (const componentId in data) {
2020-05-14 19:54:11 +00:00
const componentClass = gComponentRegistry.findById(componentId);
const componentHandle = new componentClass({});
entity.addComponent(componentHandle);
const errorStatus = componentHandle.deserialize(data[componentId]);
2020-05-09 14:45:23 +00:00
if (errorStatus) {
return errorStatus;
}
}
}
}