Esempio n. 1
0
        public void LoadingBigFileBuffer()
        {
            byte[] fileBytes = File.ReadAllBytes(TestFiles.Big);
            var file = new NbtFile();

            Assert.Throws<ArgumentNullException>(
                () => file.LoadFromBuffer(null, 0, fileBytes.Length, NbtCompression.AutoDetect, null));

            long length = file.LoadFromBuffer(fileBytes, 0, fileBytes.Length, NbtCompression.AutoDetect, null);
            TestFiles.AssertNbtBigFile(file);
            Assert.AreEqual(length, new FileInfo(TestFiles.Big).Length);
        }
Esempio n. 2
0
        public void LoadingBigFileBuffer()
        {
            byte[] fileBytes = File.ReadAllBytes(TestFiles.Big);
            var    file      = new NbtFile();

            Assert.Throws <ArgumentNullException>(
                () => file.LoadFromBuffer(null, 0, fileBytes.Length, NbtCompression.AutoDetect, null));

            long length = file.LoadFromBuffer(fileBytes, 0, fileBytes.Length, NbtCompression.AutoDetect, null);

            TestFiles.AssertNbtBigFile(file);
            Assert.AreEqual(length, new FileInfo(TestFiles.Big).Length);
        }
Esempio n. 3
0
        protected static ItemStack ReadItem(StreamWrapper buff)
        {
            var id   = buff.ReadShort();
            var item = ItemStack.CreateItemStack(id);

            if (item == null)
            {
                return(null);
            }

            item.ItemCount  = buff.ReadByte();
            item.ItemDamage = buff.ReadShort();
            var nbtLength = buff.ReadShort();

            if (nbtLength < 0)
            {
                return(item);
            }

            item.NbtData = buff.ReadBytes(nbtLength);

            var reader = new NbtFile()
            {
                BigEndian = true
            };

            reader.LoadFromBuffer(item.NbtData, 0, nbtLength, NbtCompression.AutoDetect);

            item.NbtRoot = reader.RootTag;
            return(item);
        }
Esempio n. 4
0
        public void SerializingEmpty()
        {
            // check saving/loading lists of all possible value types
            var testFile = new NbtFile(new NbtCompound("root")
            {
                new NbtList("emptyList", NbtTagType.End),
                new NbtList("listyList", NbtTagType.List)
                {
                    new NbtList(NbtTagType.End)
                }
            });

            byte[] buffer = testFile.SaveToBuffer(NbtCompression.None);

            testFile.LoadFromBuffer(buffer, 0, buffer.Length, NbtCompression.None);

            NbtList list1 = testFile.RootTag.Get <NbtList>("emptyList");

            Assert.AreEqual(list1.Count, 0);
            Assert.AreEqual(list1.ListType, NbtTagType.End);

            NbtList list2 = testFile.RootTag.Get <NbtList>("listyList");

            Assert.AreEqual(list2.Count, 1);
            Assert.AreEqual(list2.ListType, NbtTagType.List);
            Assert.AreEqual(list2.Get <NbtList>(0).Count, 0);
            Assert.AreEqual(list2.Get <NbtList>(0).ListType, NbtTagType.End);
        }
Esempio n. 5
0
 public void SkippingLists()
 {
     var file = new NbtFile(TestFiles.MakeListTest());
     byte[] savedFile = file.SaveToBuffer(NbtCompression.None);
     file.LoadFromBuffer(savedFile, 0, savedFile.Length, NbtCompression.None, tag => false);
     Assert.AreEqual(file.RootTag.Count, 0);
 }
Esempio n. 6
0
        public override IEnumerable <string> GetPlayerIDs()
        {
            OpenDB();
            var          names         = new List <string>();
            const string PlayerKeyword = "player";
            var          iterator      = BedrockDB.CreateIterator();

            iterator.Seek(PlayerKeyword);
            while (iterator.IsValid())
            {
                var name  = iterator.StringKey();
                var value = iterator.Value();
                if (UuidString(name, out string uuid))
                {
                    NbtFile nbtfile = new NbtFile();
                    nbtfile.BigEndian = false;
                    nbtfile.LoadFromBuffer(value, 0, value.Length, NbtCompression.AutoDetect);
                    if (nbtfile.RootTag["Inventory"] != null)
                    {
                        names.Add(uuid);
                    }
                }
                else
                {
                    break;
                }
                iterator.Next();
            }
            iterator.Dispose();
            CloseDB();
            return(names);
        }
        private static ItemStack ReadItemStack(PacketDataReader reader, int length = 0)
        {
            var itemStack = new ItemStack(reader.Read <short>());

            if (itemStack.Empty)
            {
                return(itemStack);
            }

            itemStack.Count  = reader.Read <byte>();
            itemStack.Damage = reader.Read <short>();

            var buffLength = reader.Read <short>();

            if (buffLength == -1 || buffLength == 0)
            {
                return(itemStack);
            }

            itemStack.Nbt = new NbtCompound();
            var buffer = reader.Read <byte[]>(null, buffLength);
            var nbt    = new NbtFile();

            nbt.LoadFromBuffer(buffer, 0, buffLength, NbtCompression.GZip, null);
            itemStack.Nbt = nbt.RootTag;

            return(itemStack);
        }
Esempio n. 8
0
        public override bool AddChests(IEnumerable <long> mapids, string playerid)
        {
            // acquire the file this player is stored in, and the tag that represents said player
            byte[] playeridbytes;
            if (playerid == LOCAL_IDENTIFIER)
            {
                playeridbytes = Encoding.Default.GetBytes("~local_player");
            }
            else
            {
                playeridbytes = Encoding.Default.GetBytes(playerid);
            }
            byte[] playerdata = BedrockDB.Get(playeridbytes.ToArray());
            var    file       = new NbtFile();

            file.BigEndian = false;
            file.LoadFromBuffer(playerdata, 0, playerdata.Length, NbtCompression.None);
            var invtag = (NbtList)file.RootTag["Inventory"];

            var success = PutChestsInInventory(invtag, mapids);

            byte[] bytes = file.SaveToBuffer(NbtCompression.None);
            BedrockDB.Put(playeridbytes, bytes);

            return(success);
        }
Esempio n. 9
0
        public void Load()
        {
            lock (_chunkCache)
            {
                string filePath = FilePath;
                if (!File.Exists(filePath))
                {
                    // Welp, nothing to load.
                    IsLoaded = true;
                    return;
                }

                using (FileStream regionFile = File.OpenRead(filePath))
                {
                    AnvilRegionHeader header = LoadRegionHeader(regionFile);
                    RegionHeader = header;

                    //File.WriteAllLines(FilePath + ".header", header.GetAllChunkData().Select(h => string.Format("{0,-10}\t=>\t{1,-10}\t{2,-10}\t{3,-10}", h.ChunkCoordinates, h.LocationOffset, h.SectorCount, h.UpdatedTimestamp)).ToArray());

                    foreach (AnvilRegionHeaderChunkData data in header.GetAllChunkData())
                    {
                        // Attempt to load NbtFile for each chunk.
                        if (!data.ChunkExists)
                        {
                            continue;
                        }

                        regionFile.Seek(data.LocationOffset, SeekOrigin.Begin);
                        var lengthBuffer = new byte[4];
                        regionFile.Read(lengthBuffer, 0, 4);
                        Array.Reverse(lengthBuffer);

                        int nbtDataLength = BitConverter.ToInt32(lengthBuffer, 0) - 1;


                        int            compressionMode = regionFile.ReadByte();
                        NbtCompression compression     = compressionMode == 2
                                                                                                                ? NbtCompression.ZLib
                                                                                                                : (compressionMode == 1 ? NbtCompression.GZip : NbtCompression.None);

                        var nbtDataBuffer = new byte[nbtDataLength];
                        regionFile.Read(nbtDataBuffer, 0, nbtDataLength);

                        //Debug.WriteLine($"({data.ChunkCoordinates.X}, {data.ChunkCoordinates.Z}) Offset: {data.LocationOffset}, Header Length: {data.SectorCount}, NbtDataLength: {nbtDataLength}");

                        var nbtFile = new NbtFile();
                        nbtFile.LoadFromBuffer(nbtDataBuffer, 0, nbtDataLength, compression);

                        //File.WriteAllText(Path.Combine(Provider.BasePath, "region", FileName + $"_{data.ChunkCoordinates.X}-{data.ChunkCoordinates.Z}.txt"), nbtFile.ToString());

                        //Debug.WriteLine(
                        //	$"Region: ({X},{Z}), Chunk({data.ChunkCoordinates.X}, {data.ChunkCoordinates.Z}): NbtDataLength: {nbtDataLength}");

                        _containingChunks.TryAdd(data.ChunkCoordinates, nbtFile);
                    }
                }

                IsLoaded = true;
            }
        }
Esempio n. 10
0
 public void SkippingLists()
 {
     {
         var    file      = new NbtFile(TestFiles.MakeListTest());
         byte[] savedFile = file.SaveToBuffer(NbtCompression.None);
         file.LoadFromBuffer(savedFile, 0, savedFile.Length, NbtCompression.None,
                             tag => tag.TagType != NbtTagType.List);
         Assert.AreEqual(0, file.RootTag.Count);
     }
     {
         // Check list-compound interaction
         NbtCompound comp = new NbtCompound("root")
         {
             new NbtCompound("compOfLists")
             {
                 new NbtList("listOfComps")
                 {
                     new NbtCompound {
                         new NbtList("emptyList", NbtTagType.Compound)
                     }
                 }
             }
         };
         var    file      = new NbtFile(comp);
         byte[] savedFile = file.SaveToBuffer(NbtCompression.None);
         file.LoadFromBuffer(savedFile, 0, savedFile.Length, NbtCompression.None,
                             tag => tag.TagType != NbtTagType.List);
         Assert.AreEqual(1, file.RootTag.Count);
     }
 }
Esempio n. 11
0
        /// <summary>
        /// Creates and returns a new item stack read from a Minecraft stream.
        /// </summary>
        /// <param name="stream">The stream to read from.</param>
        /// <returns></returns>
        public static ItemStack FromStream(IMinecraftStream stream)
        {
            var slot = ItemStack.EmptyStack;

            slot.ID = stream.ReadInt16();
            if (slot.Empty)
            {
                return(slot);
            }
            slot.Count    = stream.ReadInt8();
            slot.Metadata = stream.ReadInt16();
            var length = stream.ReadInt16();

            if (length == -1)
            {
                return(slot);
            }
            slot.Nbt = new NbtCompound();
            var buffer = stream.ReadUInt8Array(length);
            var nbt    = new NbtFile();

            nbt.LoadFromBuffer(buffer, 0, length, NbtCompression.GZip, null);
            slot.Nbt = nbt.RootTag;
            return(slot);
        }
Esempio n. 12
0
        public override bool AddChests(IEnumerable <long> mapids, string playerid)
        {
            OpenDB();
            // acquire the file this player is stored in, and the tag that represents said player
            string file_identifier;

            if (playerid == LOCAL_IDENTIFIER)
            {
                file_identifier = "~local_player";
            }
            else
            {
                file_identifier = UuidToKey(playerid);
            }
            byte[] playerdata = BedrockDB.Get(file_identifier);
            if (playerdata == null)
            {
                throw new FileNotFoundException($"Player with UUID {playerid} not found");
            }
            var file = new NbtFile();

            file.BigEndian = false;
            file.LoadFromBuffer(playerdata, 0, playerdata.Length, NbtCompression.None);
            var invtag = (NbtList)file.RootTag["Inventory"];

            var success = PutChestsInInventory(invtag, mapids);

            byte[] bytes = file.SaveToBuffer(NbtCompression.None);
            BedrockDB.Put(file_identifier, bytes);
            CloseDB();

            return(success);
        }
Esempio n. 13
0
 public void SkippingLists()
 {
     {
         var file = new NbtFile(TestFiles.MakeListTest());
         byte[] savedFile = file.SaveToBuffer(NbtCompression.None);
         file.LoadFromBuffer(savedFile, 0, savedFile.Length, NbtCompression.None,
                             tag => tag.TagType != NbtTagType.List);
         Assert.AreEqual(0, file.RootTag.Count);
     }
     {
         // Check list-compound interaction
         NbtCompound comp = new NbtCompound("root") {
             new NbtCompound("compOfLists") {
                 new NbtList("listOfComps") {
                     new NbtCompound {
                         new NbtList("emptyList", NbtTagType.Compound)
                     }
                 }
             }
         };
         var file = new NbtFile(comp);
         byte[] savedFile = file.SaveToBuffer(NbtCompression.None);
         file.LoadFromBuffer(savedFile, 0, savedFile.Length, NbtCompression.None,
                             tag => tag.TagType != NbtTagType.List);
         Assert.AreEqual(1, file.RootTag.Count);
     }
 }
Esempio n. 14
0
    public void NestedListAndCompoundTest()
    {
        byte[] data;
        {
            var root          = new NbtCompound("Root");
            var outerList     = new NbtList("OuterList", NbtTagType.Compound);
            var outerCompound = new NbtCompound();
            var innerList     = new NbtList("InnerList", NbtTagType.Compound);
            var innerCompound = new NbtCompound();

            innerList.Add(innerCompound);
            outerCompound.Add(innerList);
            outerList.Add(outerCompound);
            root.Add(outerList);

            var file = new NbtFile(root);
            data = file.SaveToBuffer(NbtCompression.None);
        }
        {
            var  file      = new NbtFile();
            long bytesRead = file.LoadFromBuffer(data, 0, data.Length, NbtCompression.None);
            Assert.Equal(bytesRead, data.Length);
            Assert.Single(file.RootTag.Get <NbtList>("OuterList"));
            Assert.Null(file.RootTag.Get <NbtList>("OuterList").Get <NbtCompound>(0).Name);
            Assert.Single(file.RootTag.Get <NbtList>("OuterList")
                          .Get <NbtCompound>(0)
                          .Get <NbtList>("InnerList"));
            Assert.Null(file.RootTag.Get <NbtList>("OuterList")
                        .Get <NbtCompound>(0)
                        .Get <NbtList>("InnerList")
                        .Get <NbtCompound>(0)
                        .Name);
        }
    }
Esempio n. 15
0
 public void LoadingBigFileBuffer()
 {
     byte[] fileBytes = File.ReadAllBytes( "TestFiles/bigtest.nbt" );
     var file = new NbtFile();
     int length = file.LoadFromBuffer( fileBytes, 0, fileBytes.Length, NbtCompression.AutoDetect, null );
     AssertNbtBigFile( file );
     Assert.AreEqual( length, new FileInfo( "TestFiles/bigtest.nbt" ).Length );
 }
Esempio n. 16
0
        private NbtFile LoadNbtFromBytes(byte[] data, int skip = 0)
        {
            var file = new NbtFile();

            file.BigEndian = false;
            file.LoadFromBuffer(data, skip, data.Length - skip, NbtCompression.None);
            return(file);
        }
Esempio n. 17
0
        public void LoadingBigFileBuffer()
        {
            var fileBytes = File.ReadAllBytes("TestFiles/bigtest.nbt");
            var file      = new NbtFile();
            var length    = file.LoadFromBuffer(fileBytes, 0, fileBytes.Length, NbtCompression.AutoDetect, null);

            AssertNbtBigFile(file);
            Assert.AreEqual(length, new FileInfo("TestFiles/bigtest.nbt").Length);
        }
Esempio n. 18
0
        public void Serializing2()
        {
            // check saving/loading lists of all possible value types
            var testFile = new NbtFile(TestFiles.MakeListTest());

            byte[] buffer    = testFile.SaveToBuffer(NbtCompression.None);
            long   bytesRead = testFile.LoadFromBuffer(buffer, 0, buffer.Length, NbtCompression.None);

            Assert.AreEqual(bytesRead, buffer.Length);
        }
Esempio n. 19
0
        public void SkippingValuesInCompoundTest()
        {
            NbtCompound root = TestFiles.MakeValueTest();
            NbtCompound nestedComp = TestFiles.MakeValueTest();
            nestedComp.Name = "NestedComp";
            root.Add(nestedComp);

            var file = new NbtFile(root);
            byte[] savedFile = file.SaveToBuffer(NbtCompression.None);
            file.LoadFromBuffer(savedFile, 0, savedFile.Length, NbtCompression.None, tag => false);
            Assert.AreEqual(0, file.RootTag.Count);
        }
Esempio n. 20
0
        public void NullParameterTest()
        {
            Assert.Throws <ArgumentNullException>(() => new NbtFile((NbtCompound)null));
            Assert.Throws <ArgumentNullException>(() => new NbtFile((string)null));

            NbtFile file = new NbtFile();

            Assert.Throws <ArgumentNullException>(() => file.LoadFromBuffer(null, 0, 1, NbtCompression.None));
            Assert.Throws <ArgumentNullException>(() => file.LoadFromBuffer(null, 0, 1, NbtCompression.None, tag => true));
            Assert.Throws <ArgumentNullException>(() => file.LoadFromFile(null));
            Assert.Throws <ArgumentNullException>(() => file.LoadFromFile(null, NbtCompression.None, tag => true));
            Assert.Throws <ArgumentNullException>(() => file.LoadFromStream(null, NbtCompression.AutoDetect));
            Assert.Throws <ArgumentNullException>(() => file.LoadFromStream(null, NbtCompression.AutoDetect, tag => true));

            Assert.Throws <ArgumentNullException>(() => file.SaveToBuffer(null, 0, NbtCompression.None));
            Assert.Throws <ArgumentNullException>(() => file.SaveToFile(null, NbtCompression.None));
            Assert.Throws <ArgumentNullException>(() => file.SaveToStream(null, NbtCompression.None));

            Assert.Throws <ArgumentNullException>(() => NbtFile.ReadRootTagName(null));
            Assert.Throws <ArgumentNullException>(
                () => NbtFile.ReadRootTagName((Stream)null, NbtCompression.None, true, 0));
        }
Esempio n. 21
0
        private void ParseRegion(string regionPath)
        {
            string fileName   = Path.GetFileName(regionPath);
            int    chunkCount = 0;

            using (BinaryReader binaryReader = new BinaryReader(File.Open(regionPath, FileMode.Open)))
            {
                List <LocationData> locationList = new List <LocationData>();
                for (int idx = 0; idx < 1024; idx++)
                {
                    int  row         = Endian.ToBig(binaryReader.ReadInt32());
                    int  offset      = (row >> 8);
                    byte sectorCount = (byte)(row & 0x000000FF);
                    if (offset != 0 || sectorCount != 0)
                    {
                        locationList.Add(new LocationData(idx % 32, idx / 32, offset, sectorCount));
                    }
                }

                for (int locationIdx = 0; locationIdx < locationList.Count; locationIdx++)
                {
                    binaryReader.BaseStream.Seek(sectorSize * locationList[locationIdx].offset, SeekOrigin.Begin);
                    int     length          = Endian.ToBig(binaryReader.ReadInt32());
                    byte    compressionType = binaryReader.ReadByte();
                    byte[]  dataBuffer      = binaryReader.ReadBytes(length - 1);
                    NbtFile region          = new NbtFile();
                    region.LoadFromBuffer(dataBuffer, 0, dataBuffer.Length, NbtCompression.ZLib);
                    NbtTag  levelTag = region.RootTag["Level"];
                    int     chunkX   = levelTag["xPos"].IntValue;
                    int     chunkZ   = levelTag["zPos"].IntValue;
                    NbtList sections = levelTag["Sections"] as NbtList;
                    for (int sectionIdx = 0; sectionIdx < sections.Count; sectionIdx++)
                    {
                        Block[] blocks     = new Block[16 * 16 * 16];
                        NbtTag  sectionTag = sections[sectionIdx];
                        int     offsetY    = sectionTag["Y"].ByteValue;
                        byte[]  blockIDs   = sectionTag["Blocks"].ByteArrayValue;
                        byte[]  blockData  = sectionTag["Data"].ByteArrayValue;
                        for (int blockIdx = 0; blockIdx < blockIDs.Length; blockIdx++)
                        {
                            blocks[blockIdx] = new Block((BlockIdentifier)blockIDs[blockIdx], MaskTo4Bit(blockData, blockIdx));
                        }
                        CoordinateInt coord = new CoordinateInt(chunkX, offsetY, chunkZ);
                        chunks.Add(coord, blocks);
                        chunkCount++;
                    }
                }
                Console.WriteLine("Parsed {0} ({1} chunks)", fileName, chunkCount);
            }
        }
Esempio n. 22
0
        public void SkippingValuesInCompoundTest()
        {
            NbtCompound root       = TestFiles.MakeValueTest();
            NbtCompound nestedComp = TestFiles.MakeValueTest();

            nestedComp.Name = "NestedComp";
            root.Add(nestedComp);

            var file = new NbtFile(root);

            byte[] savedFile = file.SaveToBuffer(NbtCompression.None);
            file.LoadFromBuffer(savedFile, 0, savedFile.Length, NbtCompression.None, tag => false);
            Assert.AreEqual(0, file.RootTag.Count);
        }
Esempio n. 23
0
        static void addChunk(byte[] data, World world)
        {
            if (data == null)
            {
                return;
            }

            var nbt = new NbtFile();

            nbt.LoadFromBuffer(data, 0, data.Length, NbtCompression.AutoDetect);

            var level = nbt.RootTag.Get <NbtCompound>("Level");

            int chunk_x = level.Get("xPos").IntValue;
            int chunk_y = level.Get("zPos").IntValue;

            if (chunk_x >= 40 || chunk_y >= 40)
            {
                return;
            }

            for (int z = 0; z < 256; z += 32)
            {
                world.set(chunk_x * 16, chunk_y * 16, z, "void");
            }

            var sections = level.Get <NbtList>("Sections");

            foreach (NbtCompound section in sections)
            {
                byte[] blocks  = section.Get("Blocks").ByteArrayValue;
                int    chunk_z = section.Get("Y").ByteValue;
                Console.WriteLine(">>>" + chunk_x + " " + chunk_y + " " + chunk_z);

                for (int z = 0; z < 16; z++)
                {
                    for (int y = 0; y < 16; y++)
                    {
                        for (int x = 0; x < 16; x++)
                        {
                            byte d = blocks[z * 256 + y * 16 + x];

                            world.set(x + chunk_x * 16, y + chunk_y * 16, z + chunk_z * 16, getBlockName(d));
                        }
                    }
                }
            }
        }
Esempio n. 24
0
        public void Serializing1()
        {
            // check the basics of saving/loading
            const NbtTagType expectedListType = NbtTagType.Int;
            const int        elements         = 10;

            // construct nbt file
            var writtenFile = new NbtFile(new NbtCompound("ListTypeTest"));
            var writtenList = new NbtList("Entities", null, expectedListType);

            for (int i = 0; i < elements; i++)
            {
                writtenList.Add(new NbtInt(i));
            }

            NbtCompound rootTag = (NbtCompound)writtenFile.RootTag;

            rootTag.Add(writtenList);

            // test saving
            byte[] data = writtenFile.SaveToBuffer(NbtCompression.None);

            // test loading
            var  readFile  = new NbtFile();
            long bytesRead = readFile.LoadFromBuffer(data, 0, data.Length, NbtCompression.None);

            Assert.AreEqual(bytesRead, data.Length);

            // check contents of loaded file
            Assert.NotNull(readFile.RootTag);
            Assert.IsInstanceOf <NbtList>(readFile.RootTag["Entities"]);
            var readList = (NbtList)readFile.RootTag["Entities"];

            Assert.AreEqual(writtenList.ListType, readList.ListType);
            Assert.AreEqual(readList.Count, writtenList.Count);

            // check .ToArray
            CollectionAssert.AreEquivalent(readList, readList.ToArray());
            CollectionAssert.AreEquivalent(readList, readList.ToArray <NbtInt>());

            // check contents of loaded list
            for (int i = 0; i < elements; i++)
            {
                Assert.AreEqual(readList.Get <NbtInt>(i).Value, writtenList.Get <NbtInt>(i).Value);
            }
        }
Esempio n. 25
0
        protected override Dictionary <long, Map> LoadMaps()
        {
            var maps = new Dictionary <long, Map>();

            foreach (var pair in BedrockDB)
            {
                string name = Encoding.Default.GetString(pair.Key);
                if (MapString(name, out long number))
                {
                    NbtFile nbtfile = new NbtFile();
                    nbtfile.BigEndian = false;
                    nbtfile.LoadFromBuffer(pair.Value, 0, pair.Value.Length, NbtCompression.AutoDetect);
                    maps.Add(number, new BedrockMap(nbtfile.RootTag["colors"].ByteArrayValue));
                }
            }
            return(maps);
        }
Esempio n. 26
0
 public override IEnumerable <string> GetPlayerIDs()
 {
     foreach (var pair in BedrockDB)
     {
         string name = Encoding.Default.GetString(pair.Key);
         if (UuidString(name))
         {
             NbtFile nbtfile = new NbtFile();
             nbtfile.BigEndian = false;
             nbtfile.LoadFromBuffer(pair.Value, 0, pair.Value.Length, NbtCompression.AutoDetect);
             if (nbtfile.RootTag["Inventory"] != null)
             {
                 yield return(name);
             }
         }
     }
 }
        public override void ReadPacketData(StreamWrapper buff)
        {
            X      = buff.ReadInt();
            Y      = buff.ReadShort();
            Z      = buff.ReadInt();
            Action = buff.ReadByte();
            int length = buff.ReadShort();

            if (length > 0)
            {
                NbtData = buff.ReadBytes(length);
                var reader = new NbtFile()
                {
                    BigEndian = true
                };
                reader.LoadFromBuffer(NbtData, 0, length, NbtCompression.AutoDetect);
                Root = reader.RootTag;
            }
        }
Esempio n. 28
0
 public void WriteTagTest()
 {
     using (var ms = new MemoryStream()) {
         var writer = new NbtWriter(ms, "root");
         {
             foreach (NbtTag tag in TestFiles.MakeValueTest().Tags)
             {
                 writer.WriteTag(tag);
             }
             writer.EndCompound();
             Assert.IsTrue(writer.IsDone);
             writer.Finish();
         }
         ms.Position = 0;
         var  file      = new NbtFile();
         long bytesRead = file.LoadFromBuffer(ms.ToArray(), 0, (int)ms.Length, NbtCompression.None);
         Assert.AreEqual(bytesRead, ms.Length);
         TestFiles.AssertValueTest(file);
     }
 }
Esempio n. 29
0
        protected override Dictionary <long, Map> LoadMaps()
        {
            var maps = new Dictionary <long, Map>();

            OpenDB();
            // thank you A Cynodont for help with this section
            const string MapKeyword = "map";
            var          iterator   = BedrockDB.CreateIterator();

            iterator.Seek(MapKeyword);
            while (iterator.IsValid())
            {
                var name = iterator.StringKey();
                if (name.StartsWith(MapKeyword))
                {
                    if (MapString(name, out long number))
                    {
                        NbtFile nbtfile = new NbtFile();
                        nbtfile.BigEndian = false;
                        byte[] data = iterator.Value();
                        nbtfile.LoadFromBuffer(data, 0, data.Length, NbtCompression.AutoDetect);
                        var colors = nbtfile.RootTag["colors"].ByteArrayValue;
                        // skip completely blank maps (bedrock likes generating pointless parents)
                        if (!colors.All(x => x == 0))
                        {
                            maps.Add(number, new BedrockMap(colors));
                        }
                    }
                }
                else
                {
                    break;
                }
                iterator.Next();
            }
            iterator.Dispose();
            CloseDB();
            return(maps);
        }
Esempio n. 30
0
        public NbtWrapper ReadNBT()
        {
            if (!this.ReadBoolean())
            {
                return(null);
            }

            byte[] nbt = new byte[this.ReadInt32(15)];
            for (int nbtIndex = 0; nbtIndex < nbt.Length; nbtIndex++)
            {
                nbt[nbtIndex] = (byte)this.ReadInt32(8);
            }

            var nbtFile = new NbtFile();

            nbtFile.LoadFromBuffer(nbt, 0, nbt.Length, NbtCompression.GZip);
            NbtCompound rootTag = nbtFile.RootTag;

            return(new NbtWrapper {
                OriginalData = nbt, RootTag = rootTag
            });
        }
Esempio n. 31
0
        public void NullParameterTest()
        {
            Assert.Throws<ArgumentNullException>(() => new NbtFile((NbtCompound)null));
            Assert.Throws<ArgumentNullException>(() => new NbtFile((string)null));

            NbtFile file = new NbtFile();
            Assert.Throws<ArgumentNullException>(() => file.LoadFromBuffer(null, 0, 1, NbtCompression.None));
            Assert.Throws<ArgumentNullException>(() => file.LoadFromBuffer(null, 0, 1, NbtCompression.None, tag => true));
            Assert.Throws<ArgumentNullException>(() => file.LoadFromFile(null));
            Assert.Throws<ArgumentNullException>(() => file.LoadFromFile(null, NbtCompression.None, tag => true));
            Assert.Throws<ArgumentNullException>(() => file.LoadFromStream(null, NbtCompression.AutoDetect));
            Assert.Throws<ArgumentNullException>(() => file.LoadFromStream(null, NbtCompression.AutoDetect, tag => true));

            Assert.Throws<ArgumentNullException>(() => file.SaveToBuffer(null, 0, NbtCompression.None));
            Assert.Throws<ArgumentNullException>(() => file.SaveToFile(null, NbtCompression.None));
            Assert.Throws<ArgumentNullException>(() => file.SaveToStream(null, NbtCompression.None));

            Assert.Throws<ArgumentNullException>(() => NbtFile.ReadRootTagName(null));
            Assert.Throws<ArgumentNullException>(
                () => NbtFile.ReadRootTagName((Stream)null, NbtCompression.None, true, 0));
        }
Esempio n. 32
0
        // страшная вещь
        static void GetData(string from, string to)
        {
            // эту функцию не следует вообще смотреть
            // страшный, одноразовый, write-only код, задача которого 1 раз распарсить mca файл и самоуничтожиться
            // однако, последняя функция не сработала, поэтому он всё ещё здесь
            var file = File.ReadAllBytes(from);

            for (var chx = 0; chx < 16; chx++)
            {
                for (var chz = 0; chz < 24; chz++)
                {
                    var index = SwapEndian(BitConverter.ToUInt32(file, 4 * (32 * chz + chx)));

                    var size   = index & 0xFF;
                    var offset = (index >> 8) * 4096; // тут даже есть куча магических констант
                    //Console.WriteLine("{0} {1} {2} {3}", chx, chz, offset, size);
                    //Console.SetCursorPosition(chx, chz);
                    //Console.WriteLine("{0}", size);

                    if (offset != 0 && size != 0)
                    {
                        var nbt    = new NbtFile();
                        var length = SwapEndian(BitConverter.ToUInt32(file, (int)offset));
                        nbt.LoadFromBuffer(file, (int)offset + 5, (int)length, NbtCompression.AutoDetect);

                        if (chz < 16)
                        {
                            continue;
                        }

                        var sections = nbt.RootTag.Get <NbtCompound>("Level").Get <NbtList>("Sections");
                        foreach (var section in sections)
                        {
                            //Console.Write("{0}", ((NbtCompound)section).Get<NbtByte>("Y").Value // о, отладочный вывод
                            var sy     = ((NbtCompound)section).Get <NbtByte>("Y").Value;
                            var blocks = ((NbtCompound)section).Get <NbtByteArray>("Blocks").Value;
                            for (var by = 0; by < 16; by++)
                            {
                                for (var bz = 0; bz < 16; bz++)
                                {
                                    for (var bx = 0; bx < 16; bx++)
                                    {
                                        var gx = chx * 16 + bx;
                                        var gy = sy * 16 + by;
                                        var gz = (chz - 16) * 16 + bz;
                                        chunks[
                                            ((gy / 64) * 4 * 2 + (gz / 64) * 4 + (gx / 64)) * 64 * 64 * 64 * 4 // непонятные формулы
                                            + (64 * 64 * (gy % 64) + 64 * (gz % 64) + (gx % 64)) * 4           // неведомые константы
                                            + 3
                                        ] = blocks[by * 16 * 16 + bz * 16 + bx];
                                        //if(gy==0)Console.WriteLine("{0} {1} {2}", gx, gy, gz); // мм, комментарии с кодом

                                        /* if(gy==0 && gx<32 && gz<32) {
                                         *   Console.SetCursorPosition(gx, gz);
                                         *   Console.WriteLine("{0}", blocks[by * 16 * 16 + bz * 16 + bx]%10);
                                         * }*/
                                        if (gy == 0 && blocks[by * 16 * 16 + bz * 16 + bx] != 7)
                                        {
                                            //Console.WriteLine("{0} {1} {2}", gx, gy, gz);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            File.WriteAllBytes(to + "1.bin", chunks);
        }
Esempio n. 33
0
        public void NestedListAndCompoundTest()
        {
            byte[] data;
            {
                var root = new NbtCompound("Root");
                var outerList = new NbtList("OuterList", NbtTagType.Compound);
                var outerCompound = new NbtCompound();
                var innerList = new NbtList("InnerList", NbtTagType.Compound);
                var innerCompound = new NbtCompound();

                innerList.Add(innerCompound);
                outerCompound.Add(innerList);
                outerList.Add(outerCompound);
                root.Add(outerList);

                var file = new NbtFile(root);
                data = file.SaveToBuffer(NbtCompression.None);
            }
            {
                var file = new NbtFile();
                long bytesRead = file.LoadFromBuffer(data, 0, data.Length, NbtCompression.None);
                Assert.AreEqual(bytesRead, data.Length);
                Assert.AreEqual(1, file.RootTag.Get<NbtList>("OuterList").Count);
                Assert.AreEqual(null, file.RootTag.Get<NbtList>("OuterList").Get<NbtCompound>(0).Name);
                Assert.AreEqual(1,
                                file.RootTag.Get<NbtList>("OuterList")
                                    .Get<NbtCompound>(0)
                                    .Get<NbtList>("InnerList")
                                    .Count);
                Assert.AreEqual(null,
                                file.RootTag.Get<NbtList>("OuterList")
                                    .Get<NbtCompound>(0)
                                    .Get<NbtList>("InnerList")
                                    .Get<NbtCompound>(0)
                                    .Name);
            }
        }
Esempio n. 34
0
 public void WriteTagTest()
 {
     using (var ms = new MemoryStream()) {
         var writer = new NbtWriter(ms, "root");
         {
             foreach (NbtTag tag in TestFiles.MakeValueTest().Tags) {
                 writer.WriteTag(tag);
             }
             writer.EndCompound();
             writer.Finish();
         }
         ms.Position = 0;
         var file = new NbtFile();
         file.LoadFromBuffer(ms.ToArray(), 0, (int)ms.Length, NbtCompression.None);
         TestFiles.AssertValueTest(file);
     }
 }
Esempio n. 35
0
        public void Serializing1()
        {
            // check the basics of saving/loading
            const NbtTagType expectedListType = NbtTagType.Int;
            const int elements = 10;

            // construct nbt file
            var writtenFile = new NbtFile(new NbtCompound("ListTypeTest"));
            var writtenList = new NbtList("Entities", null, expectedListType);
            for (int i = 0; i < elements; i++) {
                writtenList.Add(new NbtInt(i));
            }
            writtenFile.RootTag.Add(writtenList);

            // test saving
            byte[] data = writtenFile.SaveToBuffer(NbtCompression.None);

            // test loading
            var readFile = new NbtFile();
            long bytesRead = readFile.LoadFromBuffer(data, 0, data.Length, NbtCompression.None);
            Assert.AreEqual(bytesRead, data.Length);

            // check contents of loaded file
            Assert.NotNull(readFile.RootTag);
            Assert.IsInstanceOf<NbtList>(readFile.RootTag["Entities"]);
            var readList = (NbtList)readFile.RootTag["Entities"];
            Assert.AreEqual(writtenList.ListType, readList.ListType);
            Assert.AreEqual(readList.Count, writtenList.Count);

            // check .ToArray
            CollectionAssert.AreEquivalent(readList, readList.ToArray());
            CollectionAssert.AreEquivalent(readList, readList.ToArray<NbtInt>());

            // check contents of loaded list
            for (int i = 0; i < elements; i++) {
                Assert.AreEqual(readList.Get<NbtInt>(i).Value, writtenList.Get<NbtInt>(i).Value);
            }
        }
Esempio n. 36
0
 public void Serializing2()
 {
     // check saving/loading lists of all possible value types
     var testFile = new NbtFile(TestFiles.MakeListTest());
     byte[] buffer = testFile.SaveToBuffer(NbtCompression.None);
     long bytesRead = testFile.LoadFromBuffer(buffer, 0, buffer.Length, NbtCompression.None);
     Assert.AreEqual(bytesRead, buffer.Length);
 }
Esempio n. 37
0
        public void SerializingEmpty()
        {
            // check saving/loading lists of all possible value types
            var testFile = new NbtFile(new NbtCompound("root") {
                new NbtList("emptyList", NbtTagType.End),
                new NbtList("listyList", NbtTagType.List) {
                    new NbtList(NbtTagType.End)
                }
            });
            byte[] buffer = testFile.SaveToBuffer(NbtCompression.None);

            testFile.LoadFromBuffer(buffer, 0, buffer.Length, NbtCompression.None);

            NbtList list1 = testFile.RootTag.Get<NbtList>("emptyList");
            Assert.AreEqual(list1.Count,0);
            Assert.AreEqual(list1.ListType, NbtTagType.End);

            NbtList list2 = testFile.RootTag.Get<NbtList>("listyList");
            Assert.AreEqual(list2.Count,1);
            Assert.AreEqual(list2.ListType, NbtTagType.List);
            Assert.AreEqual(list2.Get<NbtList>(0).Count, 0);
            Assert.AreEqual(list2.Get<NbtList>(0).ListType, NbtTagType.End);
        }