Пример #1
0
        public ChunkColumn GetChunk(ChunkCoordinates coordinates, string basePath, IWorldGenerator generator)
        {
            try
            {
                const int width = 32;
                const int depth = 32;

                int rx = coordinates.X >> 5;
                int rz = coordinates.Z >> 5;

                string filePath = Path.Combine(basePath, string.Format(@"region{2}r.{0}.{1}.mca", rx, rz, Path.DirectorySeparatorChar));

                if (!File.Exists(filePath))
                {
                    var chunkColumn = generator?.GenerateChunkColumn(coordinates);
                    if (chunkColumn != null)
                    {
                        //SkyLightBlockAccess blockAccess = new SkyLightBlockAccess(this, chunkColumn);
                        //new SkyLightCalculations().RecalcSkyLight(chunkColumn, blockAccess);
                    }

                    return(chunkColumn);
                }

                using (var regionFile = File.OpenRead(filePath))
                {
                    int locationIndex = ((coordinates.X & (width - 1)) + (coordinates.Z & (depth - 1)) * width) << 2;
                    regionFile.Seek(locationIndex, SeekOrigin.Begin);

                    byte[] offsetBuffer = new byte[4];
                    regionFile.Read(offsetBuffer, 0, 3);
                    Array.Reverse(offsetBuffer);
                    int offset = BitConverter.ToInt32(offsetBuffer, 0) << 4;

                    int sectorCount = regionFile.ReadByte();

                    if (offset == 0 || sectorCount == 0)
                    {
                        var chunkColumn = generator?.GenerateChunkColumn(coordinates);
                        if (chunkColumn != null)
                        {
                            chunkColumn.NeedSave = true;
                        }

                        return(chunkColumn);
                    }

                    /*regionFile.Seek(4096 + locationIndex, SeekOrigin.Begin);
                     * regionFile.Read(offsetBuffer, 0, 4);
                     * Array.Reverse(offsetBuffer);
                     * int lastModified = BitConverter.ToInt32(offsetBuffer, 0);
                     * Log.Warn("Last modified: " + lastModified);*/

                    regionFile.Seek(offset + 4, SeekOrigin.Begin);                     //Offset + the length header

                    int compressionMode = regionFile.ReadByte();

                    if (compressionMode != 0x02)
                    {
                        throw new Exception($"CX={coordinates.X}, CZ={coordinates.Z}, NBT wrong compression. Expected 0x02, got 0x{compressionMode:X2}. " +
                                            $"Offset={offset}, Sectors={sectorCount}");
                    }

                    var nbt = new NbtFile();
                    nbt.LoadFromStream(regionFile, NbtCompression.ZLib);

                    NbtCompound dataTag = (NbtCompound)nbt.RootTag["Level"];

                    bool isPocketEdition = false;
                    if (dataTag.Contains("MCPE BID"))
                    {
                        isPocketEdition = dataTag["MCPE BID"].ByteValue == 1;
                    }

                    NbtList sections = dataTag["Sections"] as NbtList;

                    ChunkColumn chunk = new ChunkColumn
                    {
                        x        = coordinates.X,
                        z        = coordinates.Z,
                        biomeId  = dataTag["Biomes"].ByteArrayValue,
                        isAllAir = true
                    };

                    if (chunk.biomeId.Length > 256)
                    {
                        throw new Exception();
                    }

                    NbtTag heights = dataTag["HeightMap"] as NbtIntArray;
                    if (heights != null)
                    {
                        int[] intHeights = heights.IntArrayValue;
                        for (int i = 0; i < 256; i++)
                        {
                            chunk.height[i] = (short)intHeights[i];
                        }
                    }

                    // This will turn into a full chunk column
                    foreach (NbtTag sectionTag in sections)
                    {
                        ReadSection(sectionTag, chunk, !isPocketEdition);
                    }

                    NbtList entities = dataTag["Entities"] as NbtList;
                    if (entities != null)
                    {
                        chunk.Entities = entities.ToArray <NbtCompound>();
                    }

                    NbtList blockEntities = dataTag["TileEntities"] as NbtList;
                    if (blockEntities != null)
                    {
                        foreach (var nbtTag in blockEntities)
                        {
                            var    blockEntityTag = (NbtCompound)nbtTag.Clone();
                            string entityId       = blockEntityTag["id"].StringValue;
                            int    x = blockEntityTag["x"].IntValue;
                            int    y = blockEntityTag["y"].IntValue;
                            int    z = blockEntityTag["z"].IntValue;

                            if (entityId.StartsWith("minecraft:"))
                            {
                                var id = entityId.Split(':')[1];

                                entityId = id.First().ToString().ToUpper() + id.Substring(1);

                                blockEntityTag["id"] = new NbtString("id", entityId);
                            }

                            BlockEntity blockEntity = BlockEntityFactory.GetBlockEntityById(entityId);

                            if (blockEntity != null)
                            {
                                blockEntityTag.Name = string.Empty;

                                if (blockEntity is Sign)
                                {
                                    // Remove the JSON stuff and get the text out of extra data.
                                    // TAG_String("Text2"): "{"extra":["10c a loaf!"],"text":""}"
                                    CleanSignText(blockEntityTag, "Text1");
                                    CleanSignText(blockEntityTag, "Text2");
                                    CleanSignText(blockEntityTag, "Text3");
                                    CleanSignText(blockEntityTag, "Text4");
                                }
                                else if (blockEntity is ChestBlockEntity)
                                {
                                    NbtList items = (NbtList)blockEntityTag["Items"];

                                    if (items != null)
                                    {
                                        //for (byte i = 0; i < items.Count; i++)
                                        //{
                                        //	NbtCompound item = (NbtCompound) items[i];

                                        //	item.Add(new NbtShort("OriginalDamage", item["Damage"].ShortValue));

                                        //	byte metadata = (byte) (item["Damage"].ShortValue & 0xff);
                                        //	item.Remove("Damage");
                                        //	item.Add(new NbtByte("Damage", metadata));
                                        //}
                                    }
                                }

                                chunk.SetBlockEntity(new BlockCoordinates(x, y, z), blockEntityTag);
                            }
                            else
                            {
                                if (Log.IsDebugEnabled)
                                {
                                    Log.Debug($"Loaded unknown block entity: {blockEntityTag}");
                                }
                            }
                        }
                    }

                    //NbtList tileTicks = dataTag["TileTicks"] as NbtList;

                    chunk.RecalcHeight();

                    chunk.isDirty  = false;
                    chunk.NeedSave = false;

                    if (Config.GetProperty("CalculateLights", false))
                    {
                        SkyLightBlockAccess blockAccess = new SkyLightBlockAccess(this, chunk);
                        new SkyLightCalculations().RecalcSkyLight(chunk, blockAccess);
                        //TODO: Block lights.
                    }

                    return(chunk);
                }
            }
            catch (Exception e)
            {
                Log.Error($"Loading chunk {coordinates}", e);
                var chunkColumn = generator?.GenerateChunkColumn(coordinates);
                if (chunkColumn != null)
                {
                    //chunkColumn.NeedSave = true;
                }

                return(chunkColumn);
            }
        }
Пример #2
0
        public ChunkColumn GenerateChunkColumn(ChunkCoordinates chunkCoordinates)
        {
            lock (_chunkCache)
            {
                ChunkColumn cachedChunk;
                if (_chunkCache.TryGetValue(chunkCoordinates, out cachedChunk))
                {
                    return(cachedChunk);
                }

                ChunkColumn chunk = new ChunkColumn();
                chunk.x = chunkCoordinates.X;
                chunk.z = chunkCoordinates.Z;
                //chunk.biomeId = ArrayOf<byte>.Create(256, (byte) rand.Next(0, 37));

                int h = PopulateChunk(chunk);

                //BuildStructures(chunk);


                //chunk.SetBlock(0, h + 1, 0, 7);
                //chunk.SetBlock(1, h + 1, 0, 41);
                //chunk.SetBlock(2, h + 1, 0, 41);
                //chunk.SetBlock(3, h + 1, 0, 41);
                //chunk.SetBlock(3, h + 1, 0, 41);

                ////chunk.SetBlock(6, h + 1, 6, 57);

                //chunk.SetBlock(9, h, 3, 31);
                //chunk.SetBiome(9, 3, 30);
                //chunk.SetBlock(0, h, 1, 161);
                //chunk.SetBlock(0, h, 2, 18);

                //chunk.SetBlock(0, h, 15, 31);
                //chunk.SetBlock(0, h, 14, 161);
                //chunk.SetBlock(5, h, 13, 18);
                //chunk.SetBiome(5, 13, 30);

                //chunk.SetBlock(6, h, 9, 63);
                //chunk.SetMetadata(6, h, 9, 12);
                //var blockEntity = GetBlockEntity((chunkCoordinates.X*16) + 6, h, (chunkCoordinates.Z*16) + 9);
                //chunk.SetBlockEntity(blockEntity.Coordinates, blockEntity.GetCompound());

                //if (chunkCoordinates.X == 1 && chunkCoordinates.Z == 1)
                //{
                //	for (int x = 0; x < 10; x++)
                //	{
                //		for (int z = 0; z < 10; z++)
                //		{
                //			for (int y = h - 2; y < h; y++)
                //			{
                //				chunk.SetBlock(x, y, z, 8);
                //			}
                //		}
                //	}
                //}

                //if (chunkCoordinates.X == 3 && chunkCoordinates.Z == 1)
                //{
                //	for (int x = 0; x < 10; x++)
                //	{
                //		for (int z = 0; z < 10; z++)
                //		{
                //			for (int y = h - 1; y < h; y++)
                //			{
                //				chunk.SetBlock(x, y, z, 10);
                //			}
                //		}
                //	}
                //}

                //for (int x = 0; x < 16; x++)
                //{
                //	for (int z = 0; z < 16; z++)
                //	{
                //		for (int y = 15; y > 0; y--)
                //		{
                //			if (chunk.GetBlock(x, y, z) == 0x00)
                //			{
                //				//chunk.SetSkylight(x, y, z, 0xff);
                //			}
                //			else
                //			{
                //				//chunk.SetSkylight(x, y, z, 0x00);
                //			}
                //		}
                //	}
                //}

                chunk.RecalcHeight();

                _spawnPoint.Y = h + 2;

                // Cache
                chunk.GetBatch();
                _chunkCache[chunkCoordinates] = chunk;

                return(chunk);
            }
        }
Пример #3
0
        public ChunkColumn GetChunk(ChunkCoordinates coordinates, string basePath, IWorldGenerator generator)
        {
            try
            {
                int width = 32;
                int depth = 32;

                int rx = coordinates.X >> 5;
                int rz = coordinates.Z >> 5;

                string filePath = Path.Combine(basePath, string.Format(@"region{2}r.{0}.{1}.mca", rx, rz, Path.DirectorySeparatorChar));

                if (!File.Exists(filePath))
                {
                    var chunkColumn = generator?.GenerateChunkColumn(coordinates);
                    if (chunkColumn != null)
                    {
                        //chunkColumn.NeedSave = true;
                    }

                    return(chunkColumn);
                }

                using (var regionFile = File.OpenRead(filePath))
                {
                    byte[] buffer = new byte[8192];

                    regionFile.Read(buffer, 0, 8192);

                    int xi = (coordinates.X % width);
                    if (xi < 0)
                    {
                        xi += 32;
                    }
                    int zi = (coordinates.Z % depth);
                    if (zi < 0)
                    {
                        zi += 32;
                    }
                    int tableOffset = (xi + zi * width) * 4;

                    regionFile.Seek(tableOffset, SeekOrigin.Begin);

                    byte[] offsetBuffer = new byte[4];
                    regionFile.Read(offsetBuffer, 0, 3);
                    Array.Reverse(offsetBuffer);
                    int offset = BitConverter.ToInt32(offsetBuffer, 0) << 4;

                    byte[] bytes = BitConverter.GetBytes(offset >> 4);
                    Array.Reverse(bytes);
                    if (offset != 0 && offsetBuffer[0] != bytes[0] && offsetBuffer[1] != bytes[1] && offsetBuffer[2] != bytes[2])
                    {
                        throw new Exception($"Not the same buffer\n{Package.HexDump(offsetBuffer)}\n{Package.HexDump(bytes)}");
                    }

                    int length = regionFile.ReadByte();

                    if (offset == 0 || length == 0)
                    {
                        var chunkColumn = generator?.GenerateChunkColumn(coordinates);
                        if (chunkColumn != null)
                        {
                            //chunkColumn.NeedSave = true;
                        }

                        return(chunkColumn);
                    }

                    regionFile.Seek(offset, SeekOrigin.Begin);
                    byte[] waste = new byte[4];
                    regionFile.Read(waste, 0, 4);
                    int compressionMode = regionFile.ReadByte();

                    if (compressionMode != 0x02)
                    {
                        throw new Exception($"CX={coordinates.X}, CZ={coordinates.Z}, NBT wrong compression. Expected 0x02, got 0x{compressionMode:X2}. " +
                                            $"Offset={offset}, length={length}\n{Package.HexDump(waste)}");
                    }

                    var nbt = new NbtFile();
                    nbt.LoadFromStream(regionFile, NbtCompression.ZLib);

                    NbtCompound dataTag = (NbtCompound)nbt.RootTag["Level"];

                    bool isPocketEdition = false;
                    if (dataTag.Contains("MCPE BID"))
                    {
                        isPocketEdition = dataTag["MCPE BID"].ByteValue == 1;
                    }

                    NbtList sections = dataTag["Sections"] as NbtList;

                    ChunkColumn chunk = new ChunkColumn
                    {
                        x        = coordinates.X,
                        z        = coordinates.Z,
                        biomeId  = dataTag["Biomes"].ByteArrayValue,
                        isAllAir = true
                    };

                    if (chunk.biomeId.Length > 256)
                    {
                        throw new Exception();
                    }

                    NbtTag heights = dataTag["HeightMap"] as NbtIntArray;
                    if (heights != null)
                    {
                        int[] intHeights = heights.IntArrayValue;
                        for (int i = 0; i < 256; i++)
                        {
                            chunk.height[i] = (short)intHeights[i];
                        }
                    }

                    // This will turn into a full chunk column
                    foreach (NbtTag sectionTag in sections)
                    {
                        ReadSection(sectionTag, chunk, !isPocketEdition);
                    }

                    NbtList entities      = dataTag["Entities"] as NbtList;
                    NbtList blockEntities = dataTag["TileEntities"] as NbtList;
                    if (blockEntities != null)
                    {
                        foreach (var nbtTag in blockEntities)
                        {
                            var    blockEntityTag = (NbtCompound)nbtTag.Clone();
                            string entityId       = blockEntityTag["id"].StringValue;
                            int    x = blockEntityTag["x"].IntValue;
                            int    y = blockEntityTag["y"].IntValue;
                            int    z = blockEntityTag["z"].IntValue;

                            if (entityId.StartsWith("minecraft:"))
                            {
                                var id = entityId.Split(':')[1];

                                entityId = id.First().ToString().ToUpper() + id.Substring(1);

                                blockEntityTag["id"] = new NbtString("id", entityId);
                            }

                            BlockEntity blockEntity = BlockEntityFactory.GetBlockEntityById(entityId);

                            if (blockEntity != null)
                            {
                                blockEntityTag.Name = string.Empty;

                                if (blockEntity is Sign)
                                {
                                    // Remove the JSON stuff and get the text out of extra data.
                                    // TAG_String("Text2"): "{"extra":["10c a loaf!"],"text":""}"
                                    CleanSignText(blockEntityTag, "Text1");
                                    CleanSignText(blockEntityTag, "Text2");
                                    CleanSignText(blockEntityTag, "Text3");
                                    CleanSignText(blockEntityTag, "Text4");
                                }
                                else if (blockEntity is ChestBlockEntity)
                                {
                                    NbtList items = (NbtList)blockEntityTag["Items"];

                                    if (items != null)
                                    {
                                        //for (byte i = 0; i < items.Count; i++)
                                        //{
                                        //	NbtCompound item = (NbtCompound) items[i];

                                        //	item.Add(new NbtShort("OriginalDamage", item["Damage"].ShortValue));

                                        //	byte metadata = (byte) (item["Damage"].ShortValue & 0xff);
                                        //	item.Remove("Damage");
                                        //	item.Add(new NbtByte("Damage", metadata));
                                        //}
                                    }
                                }

                                chunk.SetBlockEntity(new BlockCoordinates(x, y, z), blockEntityTag);
                            }
                            else
                            {
                                if (Log.IsDebugEnabled)
                                {
                                    Log.Debug($"Loaded unknown block entity: {blockEntityTag}");
                                }
                            }
                        }
                    }

                    //NbtList tileTicks = dataTag["TileTicks"] as NbtList;

                    chunk.RecalcHeight();

                    chunk.isDirty  = false;
                    chunk.NeedSave = false;
                    return(chunk);
                }
            }
            catch (Exception e)
            {
                Log.Error($"Loading chunk {coordinates}", e);
                var chunkColumn = generator?.GenerateChunkColumn(coordinates);
                if (chunkColumn != null)
                {
                    //chunkColumn.NeedSave = true;
                }

                return(chunkColumn);
            }
        }