UNPKG

minecraft.js

Version:

Minecraft data serialization/deserialization and networking

68 lines (57 loc) 2.01 kB
var constants = require(__dirname + '/constants.js'); /** @constructor */ var Region = module.exports = function() { this.chunks = []; for(var i = 0; i < constants.REGION_SIZE; i++) { this.chunks[i] = []; } }; Region.prototype.getChunk = function(x, z) { return this.chunks[x & constants.REGION_SIZE - 1][z & constants.REGION_SIZE - 1]; }; Region.prototype.setChunk = function(x, z, chunk) { if(x >= 0 && x < constants.REGION_SIZE && z >= 0 && z < constants.REGION_SIZE) { this.chunks[x][z] = chunk; return this; } else { throw new Error('Chunk coordinates out of bounds'); } }; Region.prototype.toText = function(callback) { var locations = [], timestamps = [], data = [], completed = 0, offset = 0, output = ''; //for each chunk, build deflated binary data, add to chunk data var processChunks = function(region) { for(var i = 0; i < constants.REGION_SIZE; i++) { for(var j = 0; j < constants.REGION_SIZE; j++) { if(typeof region.chunks[i][j] != 'undefined') { var chunk = region.chunks[i][j]; var id = i * constants.REGION_SIZE + j; data[id] = RawDeflate.deflate(chunk.toTag().toText()); var sectorCount = Math.ceil((data[id].length + 5) / 4096); //add chunk info to header locations[id] = ((offset / 4096) << 24) + sectorCount; timestamps[id] = 0; //TODO: figure this out //create chunk metadata data[id].length; //size of chunk (in bytes) //Zlib compression (we just use DEFLATE) //add 4 bytes to the end for Zlib var footer = '\0\0\0\0'; offset += sectorCount * 4096; completed++; } else completed++; } } }; setTimeout(processChunks, 0, this); var waitForEnd = function() { if(completed >= constants.REGION_SIZE * constants.REGION_SIZE - 1) { callback(output); } else setTimeout(waitForEnd, 40); }; waitForEnd(); };