Exemplo n.º 1
0
        public void CopyConstructorTest()
        {
            NbtByte byteTag = new NbtByte("byteTag", 1);
            NbtByte byteTagClone = (NbtByte)byteTag.Clone();
            Assert.AreNotSame(byteTag, byteTagClone);
            Assert.AreEqual(byteTag.Name, byteTagClone.Name);
            Assert.AreEqual(byteTag.Value, byteTagClone.Value);
            Assert.Throws<ArgumentNullException>(() => new NbtByte((NbtByte)null));

            NbtByteArray byteArrTag = new NbtByteArray("byteArrTag", new byte[] { 1, 2, 3, 4 });
            NbtByteArray byteArrTagClone = (NbtByteArray)byteArrTag.Clone();
            Assert.AreNotSame(byteArrTag, byteArrTagClone);
            Assert.AreEqual(byteArrTag.Name, byteArrTagClone.Name);
            Assert.AreNotSame(byteArrTag.Value, byteArrTagClone.Value);
            CollectionAssert.AreEqual(byteArrTag.Value, byteArrTagClone.Value);
            Assert.Throws<ArgumentNullException>(() => new NbtByteArray((NbtByteArray)null));

            NbtCompound compTag = new NbtCompound("compTag", new NbtTag[] { new NbtByte("innerTag", 1) });
            NbtCompound compTagClone = (NbtCompound)compTag.Clone();
            Assert.AreNotSame(compTag, compTagClone);
            Assert.AreEqual(compTag.Name, compTagClone.Name);
            Assert.AreNotSame(compTag["innerTag"], compTagClone["innerTag"]);
            Assert.AreEqual(compTag["innerTag"].Name, compTagClone["innerTag"].Name);
            Assert.AreEqual(compTag["innerTag"].ByteValue, compTagClone["innerTag"].ByteValue);
            Assert.Throws<ArgumentNullException>(() => new NbtCompound((NbtCompound)null));

            NbtDouble doubleTag = new NbtDouble("doubleTag", 1);
            NbtDouble doubleTagClone = (NbtDouble)doubleTag.Clone();
            Assert.AreNotSame(doubleTag, doubleTagClone);
            Assert.AreEqual(doubleTag.Name, doubleTagClone.Name);
            Assert.AreEqual(doubleTag.Value, doubleTagClone.Value);
            Assert.Throws<ArgumentNullException>(() => new NbtDouble((NbtDouble)null));

            NbtFloat floatTag = new NbtFloat("floatTag", 1);
            NbtFloat floatTagClone = (NbtFloat)floatTag.Clone();
            Assert.AreNotSame(floatTag, floatTagClone);
            Assert.AreEqual(floatTag.Name, floatTagClone.Name);
            Assert.AreEqual(floatTag.Value, floatTagClone.Value);
            Assert.Throws<ArgumentNullException>(() => new NbtFloat((NbtFloat)null));

            NbtInt intTag = new NbtInt("intTag", 1);
            NbtInt intTagClone = (NbtInt)intTag.Clone();
            Assert.AreNotSame(intTag, intTagClone);
            Assert.AreEqual(intTag.Name, intTagClone.Name);
            Assert.AreEqual(intTag.Value, intTagClone.Value);
            Assert.Throws<ArgumentNullException>(() => new NbtInt((NbtInt)null));

            NbtIntArray intArrTag = new NbtIntArray("intArrTag", new[] { 1, 2, 3, 4 });
            NbtIntArray intArrTagClone = (NbtIntArray)intArrTag.Clone();
            Assert.AreNotSame(intArrTag, intArrTagClone);
            Assert.AreEqual(intArrTag.Name, intArrTagClone.Name);
            Assert.AreNotSame(intArrTag.Value, intArrTagClone.Value);
            CollectionAssert.AreEqual(intArrTag.Value, intArrTagClone.Value);
            Assert.Throws<ArgumentNullException>(() => new NbtIntArray((NbtIntArray)null));

            NbtList listTag = new NbtList("listTag", new NbtTag[] { new NbtByte(1) });
            NbtList listTagClone = (NbtList)listTag.Clone();
            Assert.AreNotSame(listTag, listTagClone);
            Assert.AreEqual(listTag.Name, listTagClone.Name);
            Assert.AreNotSame(listTag[0], listTagClone[0]);
            Assert.AreEqual(listTag[0].ByteValue, listTagClone[0].ByteValue);
            Assert.Throws<ArgumentNullException>(() => new NbtList((NbtList)null));

            NbtLong longTag = new NbtLong("longTag", 1);
            NbtLong longTagClone = (NbtLong)longTag.Clone();
            Assert.AreNotSame(longTag, longTagClone);
            Assert.AreEqual(longTag.Name, longTagClone.Name);
            Assert.AreEqual(longTag.Value, longTagClone.Value);
            Assert.Throws<ArgumentNullException>(() => new NbtLong((NbtLong)null));

            NbtShort shortTag = new NbtShort("shortTag", 1);
            NbtShort shortTagClone = (NbtShort)shortTag.Clone();
            Assert.AreNotSame(shortTag, shortTagClone);
            Assert.AreEqual(shortTag.Name, shortTagClone.Name);
            Assert.AreEqual(shortTag.Value, shortTagClone.Value);
            Assert.Throws<ArgumentNullException>(() => new NbtShort((NbtShort)null));

            NbtString stringTag = new NbtString("stringTag", "foo");
            NbtString stringTagClone = (NbtString)stringTag.Clone();
            Assert.AreNotSame(stringTag, stringTagClone);
            Assert.AreEqual(stringTag.Name, stringTagClone.Name);
            Assert.AreEqual(stringTag.Value, stringTagClone.Value);
            Assert.Throws<ArgumentNullException>(() => new NbtString((NbtString)null));
        }
Exemplo n.º 2
0
 public void NbtStringTest()
 {
     object dummy;
     NbtTag test = new NbtString( "HELLO WORLD THIS IS A TEST STRING ÅÄÖ!" );
     Assert.Throws<InvalidCastException>( () => dummy = test.ByteArrayValue );
     Assert.Throws<InvalidCastException>( () => dummy = test.ByteValue );
     Assert.Throws<InvalidCastException>( () => dummy = test.DoubleValue );
     Assert.Throws<InvalidCastException>( () => dummy = test.FloatValue );
     Assert.Throws<InvalidCastException>( () => dummy = test.IntArrayValue );
     Assert.Throws<InvalidCastException>( () => dummy = test.IntValue );
     Assert.Throws<InvalidCastException>( () => dummy = test.LongValue );
     Assert.Throws<InvalidCastException>( () => dummy = test.ShortValue );
     Assert.AreEqual( "HELLO WORLD THIS IS A TEST STRING ÅÄÖ!", test.StringValue );
 }
Exemplo n.º 3
0
        public void SetPropertyValue <T>(NbtTag tag, Expression <Func <T> > property, bool upperFirst = true)
        {
            var propertyInfo = ((MemberExpression)property.Body).Member as PropertyInfo;

            if (propertyInfo == null)
            {
                throw new ArgumentException("The lambda expression 'property' should point to a valid Property");
            }

            NbtTag nbtTag = tag[propertyInfo.Name];

            if (nbtTag == null)
            {
                nbtTag = tag[LowercaseFirst(propertyInfo.Name)];
            }

            if (nbtTag == null)
            {
                if (propertyInfo.PropertyType == typeof(bool))
                {
                    nbtTag = new NbtByte(propertyInfo.Name);
                }
                else if (propertyInfo.PropertyType == typeof(byte))
                {
                    nbtTag = new NbtByte(LowercaseFirst(propertyInfo.Name));
                }
                else if (propertyInfo.PropertyType == typeof(short))
                {
                    nbtTag = new NbtShort(LowercaseFirst(propertyInfo.Name));
                }
                else if (propertyInfo.PropertyType == typeof(int))
                {
                    nbtTag = new NbtInt(LowercaseFirst(propertyInfo.Name));
                }
                else if (propertyInfo.PropertyType == typeof(long))
                {
                    nbtTag = new NbtLong(LowercaseFirst(propertyInfo.Name));
                }
                else if (propertyInfo.PropertyType == typeof(float))
                {
                    nbtTag = new NbtFloat(LowercaseFirst(propertyInfo.Name));
                }
                else if (propertyInfo.PropertyType == typeof(double))
                {
                    nbtTag = new NbtDouble(LowercaseFirst(propertyInfo.Name));
                }
                else if (propertyInfo.PropertyType == typeof(string))
                {
                    nbtTag = new NbtString(LowercaseFirst(propertyInfo.Name), "");
                }
                else
                {
                    return;
                }
            }

            var mex    = property.Body as MemberExpression;
            var target = Expression.Lambda(mex.Expression).Compile().DynamicInvoke();

            switch (nbtTag.TagType)
            {
            case NbtTagType.Unknown:
                break;

            case NbtTagType.End:
                break;

            case NbtTagType.Byte:
                if (propertyInfo.PropertyType == typeof(bool))
                {
                    tag[nbtTag.Name] = new NbtByte(nbtTag.Name, (byte)((bool)propertyInfo.GetValue(target) ? 1 : 0));
                }
                else
                {
                    tag[nbtTag.Name] = new NbtByte(nbtTag.Name, (byte)propertyInfo.GetValue(target));
                }
                break;

            case NbtTagType.Short:
                tag[nbtTag.Name] = new NbtShort(nbtTag.Name, (short)propertyInfo.GetValue(target));
                break;

            case NbtTagType.Int:
                if (propertyInfo.PropertyType == typeof(bool))
                {
                    tag[nbtTag.Name] = new NbtInt(nbtTag.Name, (bool)propertyInfo.GetValue(target) ? 1 : 0);
                }
                else
                {
                    tag[nbtTag.Name] = new NbtInt(nbtTag.Name, (int)propertyInfo.GetValue(target));
                }
                break;

            case NbtTagType.Long:
                tag[nbtTag.Name] = new NbtLong(nbtTag.Name, (long)propertyInfo.GetValue(target));
                break;

            case NbtTagType.Float:
                tag[nbtTag.Name] = new NbtFloat(nbtTag.Name, (float)propertyInfo.GetValue(target));
                break;

            case NbtTagType.Double:
                tag[nbtTag.Name] = new NbtDouble(nbtTag.Name, (double)propertyInfo.GetValue(target));
                break;

            case NbtTagType.ByteArray:
                tag[nbtTag.Name] = new NbtByteArray(nbtTag.Name, (byte[])propertyInfo.GetValue(target));
                break;

            case NbtTagType.String:
                tag[nbtTag.Name] = new NbtString(nbtTag.Name, (string)propertyInfo.GetValue(target) ?? "");
                break;

            case NbtTagType.List:
                break;

            case NbtTagType.Compound:
                break;

            case NbtTagType.IntArray:
                tag[nbtTag.Name] = new NbtIntArray(nbtTag.Name, (int[])propertyInfo.GetValue(target));
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            //return (T) propertyInfo.GetValue(target);
        }
Exemplo n.º 4
0
        public ChunkColumn GetChunk(ChunkCoordinates coordinates, string basePath, IWorldProvider generator, int yoffset)
        {
            int width = 32;
            int depth = 32;

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

            Log.Debug($"Generating chunk @{coordinates}");

            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);
                //return new ChunkColumn
                //{
                //	x = coordinates.X,
                //	z = coordinates.Z,
                //};
            }

            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);
                    //return new ChunkColumn
                    //{
                    //	x = coordinates.X,
                    //	z = coordinates.Z,
                    //};
                }

                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);

                NbtTag dataTag = nbt.RootTag["Level"];

                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();
                }

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

                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 - yoffset;
                        int    z = blockEntityTag["z"].IntValue;
                        blockEntityTag["y"] = new NbtInt("y", y);

                        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.isDirty = false;
                return(chunk);
            }
        }
Exemplo n.º 5
0
		public void Write_StringTag()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			NbtString tag = new NbtString("asdf", "jkl;");
			byte[] expected = new byte[] { 0x08, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x00, 0x04, 0x6A, 0x6B, 0x6C, 0x3B };

			// Act
			writer.Write(tag);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
Exemplo n.º 6
0
		public void Write_List()
		{
			// Arrange
			MemoryStream stream = new MemoryStream();
			NbtWriter writer = new NbtWriter(stream);
			string name = "asdf";
			NbtTagType elementType = NbtTagType.String;
			NbtString[] value = new NbtString[] {
				new NbtString(string.Empty, "jkl;1"),
				new NbtString(string.Empty, "jkl;2"),
				new NbtString(string.Empty, "jkl;3"),
				new NbtString(string.Empty, "jkl;4")
			};
			byte[] expected = new byte[] { 0x09, 0x00, 0x04, 0x61, 0x73, 0x64, 0x66, 0x08, 0x00, 0x00, 0x00, 0x04, 0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x31, 0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x32, 0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x33, 0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x34 };

			// Act
			writer.Write(name, elementType, value);
			byte[] result = stream.ToArray();

			// Assert
			CollectionAssert.AreEqual(expected, result);
		}
Exemplo n.º 7
0
		/// <summary>
		/// Writes out the specified tag.
		/// </summary>
		/// <param name="tag">The tag.</param>
		/// <exception cref="System.ArgumentNullException"><paramref name="tag"/> is <c>null</c>.</exception>
		/// <exception cref="System.ObjectDisposedException">The stream is closed.</exception>
		/// <exception cref="System.IO.IOException">An I/O error occured.</exception>
		public void Write(NbtString tag)
		{
			if (tag == null)
				throw new ArgumentNullException("tag", "tag is null.");

			Write(tag, true);
		}
Exemplo n.º 8
0
		internal void Write(NbtString tag, bool writeHeader)
		{
			Write(tag.Name, tag.Value, writeHeader);
		}
Exemplo n.º 9
0
        static BlockFactory()
        {
            for (int i = 0; i < byte.MaxValue * 2; i++)
            {
                var block = GetBlockById(i);
                if (block != null)
                {
                    if (block.IsTransparent)
                    {
                        TransparentBlocks[block.Id] = 1;
                    }
                    if (block.LightLevel > 0)
                    {
                        LuminousBlocks[block.Id] = (byte)block.LightLevel;
                    }
                }
            }

            NameToId = BuildNameToId();

            for (int i = 0; i < LegacyToRuntimeId.Length; ++i)
            {
                LegacyToRuntimeId[i] = -1;
            }

            var assembly = Assembly.GetAssembly(typeof(Block));

            lock (lockObj)
            {
                Dictionary <string, int> idMapping;
                using (var stream = assembly.GetManifestResourceStream(typeof(Block).Namespace + ".block_id_map.json"))
                    using (var reader = new StreamReader(stream))
                    {
                        idMapping = JsonConvert.DeserializeObject <Dictionary <string, int> >(reader.ReadToEnd());
                    }

                Dictionary <string, short> itemIdMapping;
                using (var stream = assembly.GetManifestResourceStream(typeof(Block).Namespace + ".item_id_map.json"))
                    using (var reader = new StreamReader(stream))
                    {
                        itemIdMapping = JsonConvert.DeserializeObject <Dictionary <string, short> >(reader.ReadToEnd());
                    }

                int runtimeId = 0;
                BlockPalette = new BlockPalette();
                using (var stream = assembly.GetManifestResourceStream(typeof(Block).Namespace + ".canonical_block_states.nbt"))
                {
                    var reader = new NbtFile();
                    reader.UseVarInt = true;
                    reader.AllowAlternativeRootTag = true;

                    do
                    {
                        reader.LoadFromStream(stream, NbtCompression.AutoDetect);
                        var record = new BlockStateContainer();

                        var    tag  = reader.RootTag;
                        string name = tag["name"].StringValue;
                        record.Name   = name;
                        record.States = new List <IBlockState>();

                        if (idMapping.TryGetValue(name, out var id))
                        {
                            record.Id = id;
                        }

                        var states = tag["states"];
                        if (states != null && states is NbtCompound compound)
                        {
                            foreach (var stateEntry in compound)
                            {
                                switch (stateEntry)
                                {
                                case NbtInt nbtInt:
                                    record.States.Add(new BlockStateInt()
                                    {
                                        Name  = nbtInt.Name,
                                        Value = nbtInt.Value
                                    });
                                    break;

                                case NbtByte nbtByte:
                                    record.States.Add(new BlockStateByte()
                                    {
                                        Name  = nbtByte.Name,
                                        Value = nbtByte.Value
                                    });
                                    break;

                                case NbtString nbtString:
                                    record.States.Add(new BlockStateString()
                                    {
                                        Name  = nbtString.Name,
                                        Value = nbtString.Value
                                    });
                                    break;
                                }
                            }
                        }

                        if (itemIdMapping.TryGetValue(name, out var itemId))
                        {
                            record.ItemInstance = new ItemPickInstance()
                            {
                                Id       = itemId,
                                WantNbt  = false,
                                Metadata = 0
                            };
                        }

                        record.RuntimeId = runtimeId++;
                        BlockPalette.Add(record);
                    } while (stream.Position < stream.Length);
                }

                /*using (var stream = assembly.GetManifestResourceStream(typeof(Block).Namespace + ".blockstates.json"))
                 * using (var reader = new StreamReader(stream))
                 * {
                 *      BlockPalette = BlockPalette.FromJson(reader.ReadToEnd());
                 * }*/

                foreach (var record in BlockPalette)
                {
                    var states = new List <NbtTag>();
                    foreach (IBlockState state in record.States)
                    {
                        NbtTag stateTag = null;
                        switch (state)
                        {
                        case BlockStateByte blockStateByte:
                            stateTag = new NbtByte(state.Name, blockStateByte.Value);
                            break;

                        case BlockStateInt blockStateInt:
                            stateTag = new NbtInt(state.Name, blockStateInt.Value);
                            break;

                        case BlockStateString blockStateString:
                            stateTag = new NbtString(state.Name, blockStateString.Value);
                            break;

                        default:
                            throw new ArgumentOutOfRangeException(nameof(state));
                        }
                        states.Add(stateTag);
                    }

                    var nbt = new NbtFile()
                    {
                        BigEndian = false,
                        UseVarInt = true,
                        RootTag   = new NbtCompound("states", states)
                    };

                    byte[] nbtBinary = nbt.SaveToBuffer(NbtCompression.None);

                    record.StatesCacheNbt = nbtBinary;
                }
            }
            int palletSize = BlockPalette.Count;

            for (int i = 0; i < palletSize; i++)
            {
                if (BlockPalette[i].Data > 15)
                {
                    continue;                                            // TODO: figure out why palette contains blocks with meta more than 15
                }
                if (BlockPalette[i].Data == -1)
                {
                    continue;                                             // These are blockstates that does not have a metadata mapping
                }
                LegacyToRuntimeId[(BlockPalette[i].Id << 4) | (byte)BlockPalette[i].Data] = i;
            }

            BlockStates = new HashSet <BlockStateContainer>(BlockPalette);
        }
Exemplo n.º 10
0
 public static string ToSnbt(this NbtString tag, SnbtOptions options)
 {
     return(QuoteIfRequested(tag.Value, options.ShouldQuoteStrings, options.StringQuoteMode, options.EscapeNewlines));
 }
Exemplo n.º 11
0
    public void CopyConstructorTest()
    {
        NbtByte byteTag      = new NbtByte("byteTag", 1);
        NbtByte byteTagClone = (NbtByte)byteTag.Clone();

        Assert.NotSame(byteTag, byteTagClone);
        Assert.Equal(byteTag.Name, byteTagClone.Name);
        Assert.Equal(byteTag.Value, byteTagClone.Value);
        Assert.Throws <ArgumentNullException>(() => new NbtByte((NbtByte)null));

        NbtByteArray byteArrTag      = new NbtByteArray("byteArrTag", new byte[] { 1, 2, 3, 4 });
        NbtByteArray byteArrTagClone = (NbtByteArray)byteArrTag.Clone();

        Assert.NotSame(byteArrTag, byteArrTagClone);
        Assert.Equal(byteArrTag.Name, byteArrTagClone.Name);
        Assert.NotSame(byteArrTag.Value, byteArrTagClone.Value);
        Assert.Equal(byteArrTag.Value, byteArrTagClone.Value);
        Assert.Throws <ArgumentNullException>(() => new NbtByteArray((NbtByteArray)null));

        NbtCompound compTag      = new NbtCompound("compTag", new NbtTag[] { new NbtByte("innerTag", 1) });
        NbtCompound compTagClone = (NbtCompound)compTag.Clone();

        Assert.NotSame(compTag, compTagClone);
        Assert.Equal(compTag.Name, compTagClone.Name);
        Assert.NotSame(compTag["innerTag"], compTagClone["innerTag"]);
        Assert.Equal(compTag["innerTag"].Name, compTagClone["innerTag"].Name);
        Assert.Equal(compTag["innerTag"].ByteValue, compTagClone["innerTag"].ByteValue);
        Assert.Throws <ArgumentNullException>(() => new NbtCompound((NbtCompound)null));

        NbtDouble doubleTag      = new NbtDouble("doubleTag", 1);
        NbtDouble doubleTagClone = (NbtDouble)doubleTag.Clone();

        Assert.NotSame(doubleTag, doubleTagClone);
        Assert.Equal(doubleTag.Name, doubleTagClone.Name);
        Assert.Equal(doubleTag.Value, doubleTagClone.Value);
        Assert.Throws <ArgumentNullException>(() => new NbtDouble((NbtDouble)null));

        NbtFloat floatTag      = new NbtFloat("floatTag", 1);
        NbtFloat floatTagClone = (NbtFloat)floatTag.Clone();

        Assert.NotSame(floatTag, floatTagClone);
        Assert.Equal(floatTag.Name, floatTagClone.Name);
        Assert.Equal(floatTag.Value, floatTagClone.Value);
        Assert.Throws <ArgumentNullException>(() => new NbtFloat((NbtFloat)null));

        NbtInt intTag      = new NbtInt("intTag", 1);
        NbtInt intTagClone = (NbtInt)intTag.Clone();

        Assert.NotSame(intTag, intTagClone);
        Assert.Equal(intTag.Name, intTagClone.Name);
        Assert.Equal(intTag.Value, intTagClone.Value);
        Assert.Throws <ArgumentNullException>(() => new NbtInt((NbtInt)null));

        NbtIntArray intArrTag      = new NbtIntArray("intArrTag", new[] { 1, 2, 3, 4 });
        NbtIntArray intArrTagClone = (NbtIntArray)intArrTag.Clone();

        Assert.NotSame(intArrTag, intArrTagClone);
        Assert.Equal(intArrTag.Name, intArrTagClone.Name);
        Assert.NotSame(intArrTag.Value, intArrTagClone.Value);
        Assert.Equal(intArrTag.Value, intArrTagClone.Value);
        Assert.Throws <ArgumentNullException>(() => new NbtIntArray((NbtIntArray)null));

        NbtList listTag      = new NbtList("listTag", new NbtTag[] { new NbtByte(1) });
        NbtList listTagClone = (NbtList)listTag.Clone();

        Assert.NotSame(listTag, listTagClone);
        Assert.Equal(listTag.Name, listTagClone.Name);
        Assert.NotSame(listTag[0], listTagClone[0]);
        Assert.Equal(listTag[0].ByteValue, listTagClone[0].ByteValue);
        Assert.Throws <ArgumentNullException>(() => new NbtList((NbtList)null));

        NbtLong longTag      = new NbtLong("longTag", 1);
        NbtLong longTagClone = (NbtLong)longTag.Clone();

        Assert.NotSame(longTag, longTagClone);
        Assert.Equal(longTag.Name, longTagClone.Name);
        Assert.Equal(longTag.Value, longTagClone.Value);
        Assert.Throws <ArgumentNullException>(() => new NbtLong((NbtLong)null));

        NbtShort shortTag      = new NbtShort("shortTag", 1);
        NbtShort shortTagClone = (NbtShort)shortTag.Clone();

        Assert.NotSame(shortTag, shortTagClone);
        Assert.Equal(shortTag.Name, shortTagClone.Name);
        Assert.Equal(shortTag.Value, shortTagClone.Value);
        Assert.Throws <ArgumentNullException>(() => new NbtShort((NbtShort)null));

        NbtString stringTag      = new NbtString("stringTag", "foo");
        NbtString stringTagClone = (NbtString)stringTag.Clone();

        Assert.NotSame(stringTag, stringTagClone);
        Assert.Equal(stringTag.Name, stringTagClone.Name);
        Assert.Equal(stringTag.Value, stringTagClone.Value);
        Assert.Throws <ArgumentNullException>(() => new NbtString((NbtString)null));
    }
Exemplo n.º 12
0
		public void ReadList_Normal()
		{
			// Arrange
			NbtTagInfo tagInfo = (NbtTagInfo)new byte[] { 0x09, 0x00, 0x04 };
			byte[] data = new byte[] {
				0x61, 0x73, 0x64, 0x66, // name: "asdf"
				0x08, // type: TAG_String
				0x00, 0x00, 0x00, 0x04, // size: 4
				0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x31, // "jkl;1"
				0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x32, // "jkl;2"
				0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x33, // "jkl;3"
				0x00, 0x05, 0x6A, 0x6B, 0x6C, 0x3B, 0x34  // "jkl;4"
			};

			MemoryStream stream = new MemoryStream(data);

			NbtReader reader = new NbtReader(stream);

			NbtTagType expectedTagType = NbtTagType.List;
			string expectedName = "asdf";
			NbtString[] expectedValue = new NbtString[] {
				new NbtString(string.Empty, "jkl;1"),
				new NbtString(string.Empty, "jkl;2"),
				new NbtString(string.Empty, "jkl;3"),
				new NbtString(string.Empty, "jkl;4")
			};

			// Act
			NbtList result = reader.ReadList(tagInfo);

			// Assert
			Assert.AreEqual(expectedName, result.Name);
			Assert.AreEqual(expectedTagType, result.Type);
			for (int i = 0; i < expectedValue.Length && i < result.Value.Length; i++)
			{
				Assert.AreEqual(expectedValue[i].Name, result.Value[i].Name);
				Assert.AreEqual(expectedValue[i].Type, result.Value[i].Type);
				Assert.AreEqual(expectedValue[i].Value, result.Value[i].GetValue());
			}
		}
Exemplo n.º 13
0
        static BlockFactory()
        {
            for (int i = 0; i < byte.MaxValue * 2; i++)
            {
                var block = GetBlockById(i);
                if (block != null)
                {
                    if (block.IsTransparent)
                    {
                        TransparentBlocks[block.Id] = 1;
                    }
                    if (block.LightLevel > 0)
                    {
                        LuminousBlocks[block.Id] = (byte)block.LightLevel;
                    }
                }
            }

            NameToId = BuildNameToId();

            for (int i = 0; i < LegacyToRuntimeId.Length; ++i)
            {
                LegacyToRuntimeId[i] = -1;
            }

            var assembly = Assembly.GetAssembly(typeof(Block));

            lock (lockObj)
            {
                using (var stream = assembly.GetManifestResourceStream(typeof(Block).Namespace + ".blockstates.json"))
                    using (var reader = new StreamReader(stream))
                    {
                        BlockPalette = BlockPalette.FromJson(reader.ReadToEnd());
                    }

                foreach (var record in BlockPalette)
                {
                    var states = new List <NbtTag>();
                    foreach (IBlockState state in record.States)
                    {
                        NbtTag stateTag = null;
                        switch (state)
                        {
                        case BlockStateByte blockStateByte:
                            stateTag = new NbtByte(state.Name, blockStateByte.Value);
                            break;

                        case BlockStateInt blockStateInt:
                            stateTag = new NbtInt(state.Name, blockStateInt.Value);
                            break;

                        case BlockStateString blockStateString:
                            stateTag = new NbtString(state.Name, blockStateString.Value);
                            break;

                        default:
                            throw new ArgumentOutOfRangeException(nameof(state));
                        }
                        states.Add(stateTag);
                    }

                    var nbt = new NbtFile()
                    {
                        BigEndian = false,
                        UseVarInt = true,
                        RootTag   = new NbtCompound("states", states)
                    };

                    byte[] nbtBinary = nbt.SaveToBuffer(NbtCompression.None);

                    record.StatesCacheNbt = nbtBinary;
                }
            }
            int palletSize = BlockPalette.Count;

            for (int i = 0; i < palletSize; i++)
            {
                if (BlockPalette[i].Data > 15)
                {
                    continue;                                            // TODO: figure out why palette contains blocks with meta more than 15
                }
                if (BlockPalette[i].Data == -1)
                {
                    continue;                                             // These are blockstates that does not have a metadata mapping
                }
                LegacyToRuntimeId[(BlockPalette[i].Id << 4) | (byte)BlockPalette[i].Data] = i;
            }

            BlockStates = new HashSet <BlockStateContainer>(BlockPalette);
        }