minecraft.js
Version:
Minecraft data serialization/deserialization and networking
97 lines (81 loc) • 2.95 kB
JavaScript
var Tag = require(__dirname + '/tag.js');
/** @constructor */
var TagFormat = module.exports = function(type, tagId, objId, payload) {
if(type && typeof type == 'string' &&
typeof Tag.prototype.types[type.toUpperCase()] != 'undefined' &&
typeof tagId != 'undefined') {
this.type = Tag.prototype.types[type.toUpperCase()];
if(typeof payload != 'undefined') {
this.tagId = tagId;
this.objId = objId;
if(Array.isArray(payload)) this.payload = payload;
else if(payload instanceof TagFormat) this.payload = [payload];
else throw new Error('payload must be a TagFormat or an array of TagFormats');
} else if(typeof objId != 'undefined') {
this.tagId = tagId;
this.objId = objId;
this.payload = [];
} else if(typeof tagId != 'undefined') {
this.tagId = '';
this.objId = '';
if(Array.isArray(tagId)) this.payload = tagId;
else if(tagId instanceof TagFormat) this.payload = [tagId];
else throw new Error('payload must be a TagFormat or an array of TagFormats');
}
if(this.type.name == 'List') {
var tagType;
for(var i = 0; i < this.payload.length; i++) {
if(!tagType) {
tagType = this.payload[i].type.name;
} else if(tagType != this.payload[i].type.name) {
throw new Error('Payload array members must all be the same type');
}
}
}
} else {
throw new Error('Invalid argument');
}
};
TagFormat.prototype.encode = function(data) {
var mainTag;
if(this.type.name == 'Compound' || this.type.name == 'List') {
var subTags = [];
for(var i = 0; i < this.payload.length; i++) {
var subDataId = this.payload[i].objId;
var subData = data;
do {
subData = subData[subDataId.split('.')[0]];
subDataId = subDataId.substr(subDataId.indexOf('.') + 1);
} while(subDataId.indexOf('.') > -1);
subTags.push(this.payload[i].encode(subData));
}
mainTag = new Tag(this.type.name, this.tagId, subTags);
} else {
mainTag = new Tag(this.type.name, this.tagId, data);
}
return mainTag;
};
TagFormat.prototype.decode = function(data) {
throw new Error('not yet implemented');
};
TagFormat.prototype.append = function(tagFormat) {
if(this.type.name == 'Compound' || this.type.name == 'List') {
if(tagFormat instanceof TagFormat) {
this.payload.push(tagFormat);
} else if(Array.isArray(tagFormat)) {
for(var i = 0; i < tagFormat.length; i++) {
this.payload.push(tagFormat[i]);
}
} else {
throw new Error('Appension must be a TagFormat or an array of TagFormats');
}
} else {
throw new Error('Cannot append to a ' + this.type.name);
}
return this;
};
TagFormat.prototype.clone = function() {
var payload = [];
for(var i = 0; i < this.payload.length; i++) payload.push(this.payload[i]);
return new TagFormat(this.type.name, this.tagId, this.objId, payload || []);
};