예제 #1
0
 public override NbtCompound ToNBT()
 {
     NbtCompound c = new NbtCompound();
     Base2NBT(ref c);
     c.Add(new NbtString("EntityId", EntityId));
     c.Add(new NbtShort("Delay", Delay));
     return c;
 }
예제 #2
0
 public override NbtCompound ToNBT()
 {
     NbtCompound c = new NbtCompound();
     Base2NBT(ref c,GetID());
     c.Add(new NbtByte("Tile", Tile));
     return c;
 }
예제 #3
0
 public void SaveTo(string file)
 {
     var nbt = new NbtFile(file);
     nbt.RootTag = new NbtCompound("");
     var list = new NbtList("servers", NbtTagType.Compound);
     foreach (var server in Servers)
     {
         var compound = new NbtCompound();
         compound.Add(new NbtString("name", server.Name));
         compound.Add(new NbtString("ip", server.Ip));
         compound.Add(new NbtByte("hideAddress", (byte)(server.HideAddress ? 1 : 0)));
         compound.Add(new NbtByte("acceptTextures", (byte)(server.AcceptTextures ? 1 : 0)));
         list.Add(compound);
     }
     nbt.RootTag.Add(list);
     nbt.SaveToFile(file, NbtCompression.None);
 }
예제 #4
0
        public void AddingAndRemoving()
        {
            NbtCompound test = new NbtCompound();

            NbtInt foo =  new NbtInt( "Foo" );

            test.Add( foo );

            // adding duplicate object
            Assert.Throws<ArgumentException>( () => test.Add( foo ) );

            // adding duplicate name
            Assert.Throws<ArgumentException>( () => test.Add( new NbtByte( "Foo" ) ) );

            // adding unnamed tag
            Assert.Throws<ArgumentException>( () => test.Add( new NbtInt() ) );

            // adding null
            Assert.Throws<ArgumentNullException>( () => test.Add( null ) );

            // contains existing name
            Assert.IsTrue( test.Contains( "Foo" ) );

            // contains existing object
            Assert.IsTrue( test.Contains( foo ) );

            // contains non-existent name
            Assert.IsFalse( test.Contains( "Bar" ) );

            // contains existing name / different object
            Assert.IsFalse( test.Contains( new NbtInt( "Foo" ) ) );

            // removing non-existent name
            Assert.IsFalse( test.Remove( "Bar" ) );

            // removing existing name
            Assert.IsTrue( test.Remove( "Foo" ) );

            // removing non-existent name
            Assert.IsFalse( test.Remove( "Foo" ) );

            // re-adding object
            test.Add( foo );

            // removing existing object
            Assert.IsTrue( test.Remove( foo ) );

            // clearing an empty NbtCompound
            Assert.AreEqual( test.Count, 0 );
            test.Clear();

            // re-adding after clearing
            test.Add( foo );
            Assert.AreEqual( test.Count, 1 );

            // clearing a non-empty NbtCompound
            test.Clear();
            Assert.AreEqual( test.Count, 0 );
        }
예제 #5
0
        public NbtCompound Write() {
            var newCompound = new NbtCompound("Metadata");

            if (Tags == null) 
                return newCompound;

            foreach (NbtTag b in Tags) {
                ((NbtCompound) b.Parent)?.Remove(b);

                newCompound.Add(b);
            }

            return newCompound;
        }
예제 #6
0
        public void Save()
        {
            NbtCompound root = new NbtCompound("base");
            root.Add(new NbtString("fileType", "map"));

            NbtList aList = new NbtList("areas", NbtTagType.Compound);
            foreach(Area alpha in areas) {
                aList.Add(alpha.Save());
            }
            root.Add(aList);

            NbtFile saveFile = new NbtFile(root);
            saveFile.BigEndian = true;
            saveFile.SaveToFile("mapfile.nbt", NbtCompression.None);
        }
예제 #7
0
        public NbtCompound Write()
        {
            var hcBase = new NbtCompound("Hypercube")
            {
                new NbtString("BuildPerms", BuildPerms),
                new NbtString("ShowPerms", ShowPerms),
                new NbtString("JoinPerms", JoinPerms),
                new NbtInt("SaveInterval", SaveInterval),
                new NbtByte("Physics", Convert.ToByte(Physics)),
                new NbtByte("Building", Convert.ToByte(Building)),
                new NbtByte("History", Convert.ToByte(History))
            };

            if (Motd != null)
                hcBase.Add(new NbtString("MOTD", Motd));

            return hcBase;
        }
예제 #8
0
 public static void setTag(this NbtCompound tag, string name, float value)
 {
     tag.Add(new NbtFloat(name, value));
 }
예제 #9
0
 public static void setTag(this NbtCompound tag, string name, byte[] value)
 {
     tag.Add(new NbtByteArray(name, value));
 }
예제 #10
0
        public NbtCompound writeToNbt(NbtCompound tag, bool deleteEntities)
        {
            tag.Add(new NbtByte("hasDoneGen2", this.hasDoneGen2 ? (byte)1 : (byte)0));
            byte[] blockBytes = new byte[Chunk.BLOCK_COUNT];
            int    i, x, y, z;

            for (i = 0; i < Chunk.BLOCK_COUNT; i++)
            {
                blockBytes[i] = (byte)this.blocks[i].id;
            }
            tag.Add(new NbtByteArray("blocks", blockBytes));
            tag.Add(new NbtByteArray("meta", this.metaData));
            tag.Add(new NbtByteArray("light", this.lightLevel));

            // Tile Entites.
            NbtList list = new NbtList("tileEntities", NbtTagType.Compound);

            foreach (TileEntityBase te in this.tileEntityDict.Values)
            {
                list.Add(te.writeToNbt(new NbtCompound()));
            }
            tag.Add(list);

            // Scheduled ticks.
            list = new NbtList("scheduledTicks", NbtTagType.Compound);
            ScheduledTick tick;

            for (i = 0; i < this.scheduledTicks.Count; i++)
            {
                tick = this.scheduledTicks[i];
                list.Add(this.scheduledTicks[i].writeToNbt());
            }
            tag.Add(list);

            // Entites.
            Entity        entity;
            List <Entity> entitiesInChunk = new List <Entity>();

            for (i = this.world.entityList.Count - 1; i >= 0; i--)
            {
                entity = this.world.entityList[i];
                if (!(entity is EntityPlayer))
                {
                    x = MathHelper.floor((int)entity.transform.position.x / (float)Chunk.SIZE);
                    y = MathHelper.floor((int)entity.transform.position.y / (float)Chunk.SIZE);
                    z = MathHelper.floor((int)entity.transform.position.z / (float)Chunk.SIZE);

                    if (x == this.chunkPos.x && y == this.chunkPos.y && z == this.chunkPos.z)
                    {
                        world.entityList.Remove(entity);
                        entitiesInChunk.Add(entity);
                    }
                }
            }
            NbtList list1 = new NbtList("entities", NbtTagType.Compound);

            for (i = 0; i < entitiesInChunk.Count; i++)
            {
                entity = entitiesInChunk[i];
                list1.Add(entity.writeToNbt(new NbtCompound()));
                if (deleteEntities)
                {
                    GameObject.Destroy(entity.gameObject);
                }
            }
            tag.Add(list1);

            return(tag);
        }
예제 #11
0
        public static NbtFile CreateNbtFromChunkColumn(ChunkColumn chunk)
        {
            var nbt = new NbtFile();

            NbtCompound levelTag = new NbtCompound("Level");

            nbt.RootTag.Add(levelTag);

            levelTag.Add(new NbtByte("MCPE BID", 1));             // Indicate that the chunks contain PE block ID's.

            levelTag.Add(new NbtInt("xPos", chunk.x));
            levelTag.Add(new NbtInt("zPos", chunk.z));
            levelTag.Add(new NbtByteArray("Biomes", chunk.biomeId));

            NbtList sectionsTag = new NbtList("Sections", NbtTagType.Compound);

            levelTag.Add(sectionsTag);

            for (int i = 0; i < 16; i++)
            {
                var section = chunk.chunks[i];
                if (section.IsAllAir())
                {
                    continue;
                }

                NbtCompound sectionTag = new NbtCompound();
                sectionsTag.Add(sectionTag);
                sectionTag.Add(new NbtByte("Y", (byte)i));

                byte[] blocks     = new byte[4096];
                byte[] data       = new byte[2048];
                byte[] blockLight = new byte[2048];
                byte[] skyLight   = new byte[2048];

                {
                    for (int x = 0; x < 16; x++)
                    {
                        for (int z = 0; z < 16; z++)
                        {
                            for (int y = 0; y < 16; y++)
                            {
                                int  anvilIndex = y * 16 * 16 + z * 16 + x;
                                byte blockId    = section.GetBlock(x, y, z);
                                blocks[anvilIndex] = blockId;
                                SetNibble4(data, anvilIndex, section.GetMetadata(x, y, z));
                                SetNibble4(blockLight, anvilIndex, section.GetBlocklight(x, y, z));
                                SetNibble4(skyLight, anvilIndex, section.GetSkylight(x, y, z));
                            }
                        }
                    }
                }
                sectionTag.Add(new NbtByteArray("Blocks", blocks));
                sectionTag.Add(new NbtByteArray("Data", data));
                sectionTag.Add(new NbtByteArray("BlockLight", blockLight));
                sectionTag.Add(new NbtByteArray("SkyLight", skyLight));
            }

            int[] heights = new int[256];
            for (int h = 0; h < heights.Length; h++)
            {
                heights[h] = chunk.height[h];
            }
            levelTag.Add(new NbtIntArray("HeightMap", heights));

            // TODO: Save entities
            NbtList entitiesTag = new NbtList("Entities", NbtTagType.Compound);

            //foreach(var entity in )
            levelTag.Add(entitiesTag);

            NbtList blockEntitiesTag = new NbtList("TileEntities", NbtTagType.Compound);

            foreach (NbtCompound blockEntityNbt in chunk.BlockEntities.Values)
            {
                NbtCompound nbtClone = (NbtCompound)blockEntityNbt.Clone();
                nbtClone.Name = null;
                blockEntitiesTag.Add(nbtClone);
            }

            levelTag.Add(blockEntitiesTag);

            levelTag.Add(new NbtList("TileTicks", NbtTagType.Compound));

            return(nbt);
        }
예제 #12
0
 public override NbtCompound writeToNbt(NbtCompound tag)
 {
     base.writeToNbt(tag);
     tag.Add(new NbtInt("unitsLong", this.unitsLong));
     return(tag);
 }
예제 #13
0
        public NbtCompound GetNbt()
        {
            NbtCompound root = new NbtCompound("");

            root.Add(
                new NbtList("slots")
            {
                new NbtCompound()
                {
                    new NbtList("acceptedItems")
                    {
                        new NbtCompound()
                        {
                            new NbtCompound("slotItem")
                            {
                                new NbtByte("Count", 1),
                                new NbtShort("Damage", 0),
                                new NbtShort("id", 329),
                            },
                        }
                    },
                    new NbtCompound("item")
                    {
                        new NbtByte("Count", Slot0.Count),
                        new NbtShort("Damage", Slot0.Metadata),
                        new NbtShort("id", Slot0.Id),
                    },
                    new NbtInt("slotNumber", 0)
                },
                new NbtCompound()
                {
                    new NbtList("acceptedItems")
                    {
                        new NbtCompound()
                        {
                            new NbtCompound("slotItem")
                            {
                                new NbtByte("Count", 1),
                                new NbtShort("Damage", 0),
                                new NbtShort("id", 416),
                            },
                        },
                        new NbtCompound()
                        {
                            new NbtCompound("slotItem")
                            {
                                new NbtByte("Count", 1),
                                new NbtShort("Damage", 0),
                                new NbtShort("id", 417),
                            },
                        },
                        new NbtCompound()
                        {
                            new NbtCompound("slotItem")
                            {
                                new NbtByte("Count", 1),
                                new NbtShort("Damage", 0),
                                new NbtShort("id", 418),
                            },
                        },
                        new NbtCompound()
                        {
                            new NbtCompound("slotItem")
                            {
                                new NbtByte("Count", 1),
                                new NbtShort("Damage", 0),
                                new NbtShort("id", 419),
                            },
                        },
                    },
                    new NbtCompound("item")
                    {
                        new NbtByte("Count", Slot1.Count),
                        new NbtShort("Damage", Slot1.Metadata),
                        new NbtShort("id", Slot1.Id),
                    },
                    new NbtInt("slotNumber", 1)
                },
            });

            return(root);
        }
예제 #14
0
 public void Base2NBT(ref NbtCompound c)
 {
     c.Add(new NbtString("id", ID));
     c.Add(new NbtInt("x", (int)Pos.X));
     c.Add(new NbtInt("y", (int)Pos.Y));
     c.Add(new NbtInt("z", (int)Pos.Z));
 }
예제 #15
0
        public static void writeBlueprint(string filePath, BlueprintPA blueprint)
        {
            bool isv = Options.Get.IsSideView;

            #region metadata
            var metadata = new NbtCompound("Metadata");
            metadata.Add(new NbtString("Name", "NameOfSchematic"));
            metadata.Add(new NbtString("Author", "Taylor Love"));
            metadata.Add(new NbtString("Generator", "PixelStacker (" + Constants.Version + ")"));
            metadata.Add(new NbtString("Generator Website", Constants.Website));
            metadata.Add(new NbtList("RequiredMods", new List <NbtTag>(), NbtTagType.String));
            metadata.Add(new NbtInt("WEOriginX", 1));
            metadata.Add(new NbtInt("WEOriginY", 1));
            metadata.Add(new NbtInt("WEOriginZ", 1));

            if (blueprint.WorldEditOrigin != null)
            {
                metadata.Add(new NbtInt("WEOffsetX", -blueprint.WorldEditOrigin.X));

                if (isv)
                {
                    metadata.Add(new NbtInt("WEOffsetY", blueprint.WorldEditOrigin.Y - blueprint.Mapper.GetYLength(isv)));
                    metadata.Add(new NbtInt("WEOffsetZ", -blueprint.Mapper.GetZLength(isv))); //  Options.Get.IsMultiLayer ? -3 : -1
                }
                else
                {
                    metadata.Add(new NbtInt("WEOffsetY", 0));
                    metadata.Add(new NbtInt("WEOffsetZ", -blueprint.WorldEditOrigin.Y));
                }
            }

            #endregion

            var nbt = new NbtCompound("Schematic");
            // Missing "Offset" which defaults to [0,0,0]. Basically the world offset. Coordinates.
            nbt.Add(new NbtInt("Version", 1));
            nbt.Add(new NbtShort("Width", (short)blueprint.Mapper.GetXLength(isv)));
            nbt.Add(new NbtShort("Height", (short)blueprint.Mapper.GetYLength(isv)));
            nbt.Add(new NbtShort("Length", (short)blueprint.Mapper.GetZLength(isv)));
            nbt.Add(new NbtIntArray("Offset", new int[] { 0, 0, 0 }));
            nbt.Add(metadata);

            //PaletteMax integer Specifies the size of the block palette in number of bytes needed for the maximum palette index.Implementations may use this as a hint for the case that the palette data fits within a datatype smaller than a 32 - bit integer that they may allocate a smaller sized array.
            //Palette Palette Object  Specifies the block palette.This is a mapping of block states to indices which are local to this schematic.These indices are used to reference the block states from within the BlockData array.It is recommeneded for maximum data compression that your indices start at zero and skip no values.The maximum index cannot be greater than PaletteMax - 1.While not required it is highly recommended that you include a palette in order to tightly pack the block ids included in the data array.
            //BlockData   varint[]    Required.Specifies the main storage array which contains Width * Height * Length entries.Each entry is specified as a varint and refers to an index within the Palette.The entries are indexed by x + z * Width + y * Width * Length.
            //TileEntities    TileEntity Object[] Specifies additional data for blocks which require extra data.If no additional data is provided for a block which normally requires extra data then it is assumed that the TileEntity for the block is initialized to its default state.
            var palette      = new Dictionary <string, int>();
            var tileEntities = new List <NbtCompound>();


            //Required.Specifies the main storage array which contains Width *Height * Length entries.Each entry is specified
            //as a varint and refers to an index within the Palette.The entries are indexed by
            //x +z * Width + y * Width * Length.
            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter buffer = new BinaryWriter(ms))
                {
                    int xMax = blueprint.Mapper.GetXLength(isv);
                    int yMax = blueprint.Mapper.GetYLength(isv);
                    int zMax = blueprint.Mapper.GetZLength(isv);

                    for (int y = yMax - 1; y >= 0; y--)
                    {
                        for (int z = 0; z < zMax; z++)
                        {
                            for (int x = 0; x < xMax; x++)
                            {
                                Material m = blueprint.Mapper.GetMaterialAt(isv, x, y, z);

                                string key = m.GetBlockNameAndData(isv);
                                if (!palette.ContainsKey(key))
                                {
                                    palette.Add(key, palette.Count);
                                }

                                int blockId = palette[key];

                                if (blockId <= Byte.MaxValue)
                                {
                                    buffer.Write((byte)blockId);
                                }
                                else if (blockId <= short.MaxValue)
                                {
                                    buffer.Write((short)blockId);
                                }
                                else if (blockId <= int.MaxValue)
                                {
                                    buffer.Write((int)blockId);
                                }
                                //while ((blockId & -128) != 0)
                                //{
                                //    byte b = (byte)(blockId & 127 | 128);
                                //    buffer.Write(b);
                                //    blockId >>= 7;
                                //    //blockId >>> = 7;
                                //}
                                //byte b2 = (byte)(blockId & 127 | 128);
                                //buffer.Write(b2);
                                //buffer.Write((short)blockId);

                                //buffer.Write((byte)blockId);
                            }
                        }
                    }
                }

                // size of block palette in number of bytes needed for the maximum  palette index. Implementations may use
                // this as a hint for the case that the palette data fits within a datatype smaller than a 32 - bit integer
                // that they may allocate a smaller sized array.
                nbt.Add(new NbtInt("PaletteMax", palette.Count));
                var paletteTag = new NbtCompound("Palette");
                foreach (var kvp in palette)
                {
                    paletteTag.Add(new NbtInt(kvp.Key, kvp.Value));
                }
                nbt.Add(paletteTag);
                var blockData = ms.ToArray();
                nbt.Add(new NbtByteArray("BlockData", blockData));
            }

            nbt.Add(new NbtList("TileEntities", NbtTagType.End));

            var serverFile = new NbtFile(nbt);
            serverFile.SaveToFile(filePath, NbtCompression.GZip);
        }
예제 #16
0
    public static NbtCompound ToNbt(this ItemStack?value)
    {
        value ??= new ItemStack(0, 0)
        {
            Present = true
        };

        var item = value.AsItem();

        var compound = new NbtCompound
        {
            new NbtTag <string>("id", item.UnlocalizedName),
            new NbtTag <byte>("Count", (byte)value.Count),
            new NbtTag <byte>("Slot", (byte)value.Slot)
        };

        ItemMeta meta = value.ItemMeta;

        if (meta.HasTags())
        {
            compound.Add(new NbtTag <bool>("Unbreakable", meta.Unbreakable));

            if (meta.Durability > 0)
            {
                compound.Add(new NbtTag <int>("Damage", meta.Durability));
            }

            if (meta.CustomModelData > 0)
            {
                compound.Add(new NbtTag <int>("CustomModelData", meta.CustomModelData));
            }

            if (meta.CanDestroy is not null)
            {
                var list = new NbtList(NbtTagType.String, "CanDestroy");

                foreach (var block in meta.CanDestroy)
                {
                    list.Add(new NbtTag <string>(string.Empty, block));
                }

                compound.Add(list);
            }

            if (meta.Name is not null)
            {
                var displayCompound = new NbtCompound("display")
                {
                    new NbtTag <string>("Name", new List <ChatMessage> {
                        meta.Name
                    }.ToJson())
                };

                if (meta.Lore is not null)
                {
                    var list = new NbtList(NbtTagType.String, "Lore");

                    foreach (var lore in meta.Lore)
                    {
                        list.Add(new NbtTag <string>(string.Empty, new List <ChatMessage> {
                            lore
                        }.ToJson()));
                    }

                    displayCompound.Add(list);
                }

                compound.Add(displayCompound);
            }
            else if (meta.Lore is not null)
            {
                var displayCompound = new NbtCompound("display")
                {
                    new NbtTag <string>("Name", new List <ChatMessage> {
                        meta.Name
                    }.ToJson())
                };

                var list = new NbtList(NbtTagType.String, "Lore");

                foreach (var lore in meta.Lore)
                {
                    list.Add(new NbtTag <string>(string.Empty, new List <ChatMessage> {
                        lore
                    }.ToJson()));
                }

                displayCompound.Add(list);

                compound.Add(displayCompound);
            }
        }

        return(compound);
    }
예제 #17
0
 /// <summary>
 /// Called to save the piece to disk.
 /// </summary>
 public virtual NbtCompound writeToNbt(NbtCompound tag)
 {
     tag.Add(new NbtByte("id", this.getPieceId()));
     NbtHelper.writeDirectBlockPos(tag, this.orgin, "orgin");
     return(tag);
 }
        public static NbtCompound ExportReactor()
        {
            NbtCompound reactor        = new NbtCompound("Schematic");
            bool        coolerIsActive = false;
            int         volume         = (int)(Reactor.interiorDims.X * Reactor.interiorDims.Y * Reactor.interiorDims.Z);

            byte[] blocks = new byte[volume];
            byte[] data   = new byte[volume];
            bool   extra  = false;

            byte[]  extraBlocks                 = new byte[volume];
            byte[]  extraBlocksNibble           = new byte[(int)Math.Ceiling(volume / 2.0)];
            NbtList tileEntities                = new NbtList("TileEntities", NbtTagType.Compound);
            Dictionary <string, short> mappings = new Dictionary <string, short>();

            for (int y = 1; y <= Reactor.interiorDims.Y; y++)
            {
                for (int z = 1; z <= Reactor.interiorDims.Z; z++)
                {
                    for (int x = 1; x <= Reactor.interiorDims.X; x++)
                    {
                        coolerIsActive = false;
                        Block block = Reactor.BlockAt(new Point3D(x, y, z));
                        int   index = (int)((x - 1) + ((y - 1) * Reactor.interiorDims.Z + (z - 1)) * Reactor.interiorDims.X);
                        blocks[index] = (byte)BlockIDLookup[block.BlockType];
                        if (block.BlockType == BlockTypes.FuelCell | block.BlockType == BlockTypes.Air)
                        {
                            data[index] = 0;
                        }
                        else if (block is Cooler cooler)
                        {
                            if (cooler.Active)
                            {
                                coolerIsActive = true;
                                blocks[index]  = 340 - 256;
                                data[index]    = 0;
                                tileEntities.Add(CreateActiveCooler(x - 1, y - 1, z - 1));
                            }
                            else
                            {
                                data[index] = (byte)BlockMetaLookup[cooler.CoolerType.ToString()];
                            }
                        }
                        else if (block.BlockType == BlockTypes.Moderator)
                        {
                            data[index] = (byte)BlockMetaLookup[((Moderator)block).ModeratorType.ToString()];
                        }

                        if (coolerIsActive)
                        {
                            extraBlocks[index] = (byte)(340 >> 8);
                            extra = true;
                        }
                        else
                        if ((extraBlocks[index] = (byte)(BlockIDLookup[block.BlockType] >> 8)) > 0)
                        {
                            if (block.BlockType == BlockTypes.Air)
                            {
                                continue;
                            }
                        }
                        if (coolerIsActive)
                        {
                            if (!mappings.ContainsKey("nuclearcraft:active_cooler"))
                            {
                                mappings.Add("nuclearcraft:active_cooler", 340);
                            }
                            else
                            if (!mappings.ContainsKey(SchematicaMappingLookup[block.BlockType]))
                            {
                                mappings.Add(SchematicaMappingLookup[block.BlockType], (short)BlockIDLookup[block.BlockType]);
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < extraBlocksNibble.Length; i++)
            {
                if (i * 2 + 1 < extraBlocks.Length)
                {
                    extraBlocksNibble[i] = (byte)((extraBlocks[i * 2 + 0] << 4) | extraBlocks[i * 2 + 1]);
                }
                else
                {
                    extraBlocksNibble[i] = (byte)(extraBlocks[i * 2 + 0] << 4);
                }
            }

            reactor.Add(new NbtByteArray("Blocks", blocks));
            reactor.Add(new NbtShort("Length", (short)Reactor.interiorDims.Z));
            reactor.Add(new NbtString("Materials", "Alpha"));
            reactor.Add(new NbtShort("Height", (short)Reactor.interiorDims.Y));
            reactor.Add(new NbtByteArray("Data", data));
            reactor.Add(SetIcon());
            NbtCompound mappingsC = new NbtCompound("SchematicaMapping");

            foreach (KeyValuePair <string, short> kvp in mappings)
            {
                mappingsC.Add(new NbtShort(kvp.Key, kvp.Value));
            }
            reactor.Add(mappingsC);
            reactor.Add(new NbtShort("Width", (short)Reactor.interiorDims.X));
            if (extra)
            {
                reactor.Add(new NbtByteArray("AddBlocks", extraBlocksNibble));
            }
            reactor.Add(tileEntities);
            reactor.Add(new NbtList("Entities", NbtTagType.Compound));



            return(reactor);
        }
        private static NbtCompound CreateActiveCooler(int x, int y, int z)
        {
            NbtCompound activeCooler = new NbtCompound("nbt");

            activeCooler.Add(new NbtByte("isRedstonePowered", 0));
            activeCooler.Add(new NbtByte("emptyUnusable", 0));
            activeCooler.Add(new NbtByte("areTanksShared", 0));
            activeCooler.Add(new NbtByte("alternateComparator", 0));
            activeCooler.Add(new NbtString("fluidName0", "nullFluid"));
            activeCooler.Add(new NbtByte("isActive", 0));
            activeCooler.Add(new NbtInt("fluidAmount", 0));
            activeCooler.Add(new NbtInt("fluidConnections0", 0));
            activeCooler.Add(new NbtByte("voidExcessOutputs", 0));
            activeCooler.Add(new NbtInt("fluidConnections2", 0));
            activeCooler.Add(new NbtDouble("radiationLevel1", 0));
            activeCooler.Add(new NbtInt("fluidConnections1", 0));
            activeCooler.Add(new NbtInt("x", x));
            activeCooler.Add(new NbtInt("fluidConnections4", 0));
            activeCooler.Add(new NbtInt("y", y));
            activeCooler.Add(new NbtInt("fluidConnections3", 0));
            activeCooler.Add(new NbtInt("z", z));
            activeCooler.Add(new NbtString("id", "nuclearcraft:active_cooler"));
            activeCooler.Add(new NbtInt("fluidConnections5", 0));

            return(activeCooler);
        }
예제 #20
0
파일: Chunk.cs 프로젝트: Luigifan/TrueCraft
        public NbtTag Serialize(string tagName)
        {
            var chunk = new NbtCompound(tagName);
            var entities = new NbtList("Entities", NbtTagType.Compound);
            chunk.Add(entities);
            chunk.Add(new NbtInt("X", X));
            chunk.Add(new NbtInt("Z", Z));
            chunk.Add(new NbtByteArray("Blocks", Blocks));
            chunk.Add(new NbtByteArray("Data", Metadata.Data));
            chunk.Add(new NbtByteArray("SkyLight", SkyLight.Data));
            chunk.Add(new NbtByteArray("BlockLight", BlockLight.Data));

            var tiles = new NbtList("TileEntities", NbtTagType.Compound);
            foreach (var kvp in TileEntities)
            {
                var c = new NbtCompound();
                c.Add(new NbtList("coordinates", new[] {
                    new NbtInt(kvp.Key.X),
                    new NbtInt(kvp.Key.Y),
                    new NbtInt(kvp.Key.Z)
                 }));
                 c.Add(new NbtList("value", new[] { kvp.Value }));
                 tiles.Add(c);
            }
            chunk.Add(tiles);

            // TODO: Entities
            return chunk;
        }
예제 #21
0
 public static void setTag(this NbtCompound tag, string name, NbtList value)
 {
     value.Name = name;
     tag.Add(value);
 }
예제 #22
0
 public static void setTag(this NbtCompound tag, string name, short value)
 {
     tag.Add(new NbtShort(name, value));
 }
예제 #23
0
        public void Save(string p)
        {
            var myFile = new NbtFile();

            var root = myFile.RootTag;
            root.Name = "Schematic";

            root.Add(new NbtShort("Height", Height));
            root.Add(new NbtShort("Length", Length));
            root.Add(new NbtShort("Width", Width));

            var nbttile = new NbtList("TileEntities", NbtTagType.Compound);
            var size = Width * Height * Length;
            _data = new byte[size];
            _blocks = new byte[size];

            for (int y = 0; y < Height; y++)
            {
                for (int z = 0; z < Length; z++)
                {
                    for (int x = 0; x < Width; x++)
                    {
                        var d = GetBlock(x, y, z);
                        _blocks[(y * Length + z) * Width + x] = (byte)d.ID;
                        _data[(y * Length + z) * Width + x] = (byte)(d.Metta & 0x0F);

                        if (d.Command != null)
                        {
                            var nbtc = new NbtCompound();
                            nbtc.Add(new NbtString("CustomName", "LuaBlock"));
                            nbtc.Add(new NbtString("Command", d.Command));
                            nbtc.Add(new NbtString("id", "Control"));
                            nbtc.Add(new NbtInt("x", x));
                            nbtc.Add(new NbtInt("y", y));
                            nbtc.Add(new NbtInt("z", z));

                            nbttile.Add(nbtc);
                        }
                    }
                }
            }
            root.Add(new NbtList("Entities", NbtTagType.Byte));
            root.Add(nbttile);
            root.Add(new NbtList("TileTicks", NbtTagType.Byte));

            root.Add(new NbtString("Materials", "Alpha"));

            root.Add(new NbtByteArray("Data", _data));
             //   root.Add(new NbtByteArray("Biomes", new byte[Width * Length]));
            root.Add(new NbtByteArray("Blocks", _blocks));

            myFile.SaveToFile(p, NbtCompression.None);
        }
예제 #24
0
        private static NbtTag SerializeChild(string name, object value)
        {
            if (value is NbtTag normalValue)
            {
                normalValue      = (NbtTag)normalValue.Clone();
                normalValue.Name = name;
                return(normalValue);
            }

            var tag = CreateBaseTag(name, value);

            if (tag != null)
            {
                return(tag);
            }

            if (value is IList list)
            {
                return(GetNbtList(name, list));
            }
            else if (value is IDictionary dictionary)
            {
                return(GetNbtCompound(name, dictionary));
            }

            var type = value.GetType();

            var properties = type.GetProperties(MemberBindingFlags);
            var fields     = type.GetFields(MemberBindingFlags);

            if (properties.Length == 0 && fields.Length == 0)
            {
                return(null);
            }

            var nbt = new NbtCompound();

            if (name != null)
            {
                nbt.Name = name;
            }

            foreach (var property in properties)
            {
                var child = SerializeMember(property, property.GetValue(value));
                if (child != null)
                {
                    nbt.Add(child);
                }
            }

            foreach (var filed in fields)
            {
                var child = SerializeMember(filed, filed.GetValue(value));
                if (child != null)
                {
                    nbt.Add(child);
                }
            }

            if (nbt.Count == 0)
            {
                return(null);
            }

            return(nbt);
        }
예제 #25
0
파일: Item.cs 프로젝트: Caesar008/SaveEdit
        public Item(string name, string id, int damage, int maxDamage, byte stack, byte count, byte slot, NbtCompound tag, string[] kategorie, byte[] povoleneSloty, Bitmap image, Form1 form, bool canChangeColor, bool banner, bool firework, bool vlastnosti, List <string> mandatory, string imageInfo = null)
        {
            Name       = name;
            ID         = id;
            Damage     = damage;
            Stack      = stack;
            Count      = count;
            Slot       = slot;
            Tag        = tag;
            this.form  = form;
            ZmenaBarev = canChangeColor;
            Banner     = banner;
            Firework   = firework;
            Enchanty   = new Dictionary <string, short>();

            NbtCompound item = new NbtCompound();

            item.Add(new NbtString("id", id));
            item.Add(new NbtByte("Count", count));
            item.Add(new NbtByte("Slot", slot));
            if (tag != null)
            {
                item.Add(new NbtCompound(tag));
            }
            if (damage != -1)
            {
                if (item.Get <NbtCompound>("tag") == null)
                {
                    item.Add(new NbtCompound("tag"));
                }
                if (item.Get <NbtCompound>("tag").Get <NbtInt>("Damage") == null)
                {
                    item.Get <NbtCompound>("tag").Add(new NbtInt("Damage", damage));
                }
                else
                {
                    item.Get <NbtCompound>("tag").Get <NbtInt>("Damage").Value = damage;
                }

                if (item.Get <NbtCompound>("tag").Get <NbtList>("Enchantments") != null)
                {
                    foreach (NbtCompound ench in item.Get <NbtCompound>("tag").Get <NbtList>("Enchantments"))
                    {
                        Enchanty.Add(ench.Get <NbtString>("id").Value, ench.Get <NbtShort>("lvl").Value);
                    }
                }

                if (item.Get <NbtCompound>("tag").Get <NbtList>("StoredEnchantments") != null)
                {
                    foreach (NbtCompound ench in item.Get <NbtCompound>("tag").Get <NbtList>("StoredEnchantments"))
                    {
                        Enchanty.Add(ench.Get <NbtString>("id").Value, ench.Get <NbtShort>("lvl").Value);
                    }
                }
            }

            NbtItem       = item;
            Kategorie     = kategorie;
            Image         = image;
            PovoleneSloty = povoleneSloty;
            MaxDamage     = maxDamage;
            Vlastnosti    = vlastnosti;
            Mandatory     = mandatory;
            ImageInfo     = imageInfo;
        }
예제 #26
0
        public NbtFile ToNbt() // TODO: Entities
        {
            NbtFile file = new NbtFile();
            NbtCompound level = new NbtCompound("Level");
            
            // Entities // TODO
            level.Add(new NbtList("Entities", NbtTagType.Compound));

            // Biomes
            level.Add(new NbtByteArray("Biomes", Biomes));

            // Last Update // TODO: What is this
            level.Add(new NbtLong("LastUpdate", 15));

            // Position
            level.Add(new NbtInt("xPos", (int)AbsolutePosition.X));
            level.Add(new NbtInt("zPos", (int)AbsolutePosition.Z));

            // Tile Entities
            var tileEntityList = new NbtList("TileEntities", NbtTagType.Compound);
            foreach (var tileEntity in TileEntities)
            {
                // Get properties
                tileEntityList.Add(tileEntity.Value.ToNbt(tileEntity.Key));
            }
            level.Add(tileEntityList);

            // Terrain Populated // TODO: When is this 0? Will vanilla use this?
            level.Add(new NbtByte("TerrainPopualted", 0));

            // Sections and height
            level.Add(new NbtIntArray("HeightMap", HeightMap));
            NbtList sectionList = new NbtList("Sections", NbtTagType.Compound);
            foreach (var section in Sections)
            {
                if (!section.IsAir)
                {
                    NbtCompound sectionTag = new NbtCompound();
                    sectionTag.Add(new NbtByte("Y", section.Y));
                    sectionTag.Add(new NbtByteArray("Blocks", section.Blocks));
                    sectionTag.Add(new NbtByteArray("Data", section.Metadata.Data));
                    sectionTag.Add(new NbtByteArray("SkyLight", section.SkyLight.Data));
                    sectionTag.Add(new NbtByteArray("BlockLight", section.BlockLight.Data));
                    sectionList.Add(sectionTag);
                }
            }
            level.Add(sectionList);

            var rootCompound = new NbtCompound("");
            rootCompound.Add(level);
            file.RootTag = rootCompound;

            return file;
        }
예제 #27
0
        public NbtCompound Write()
        {
            var newCompound = new NbtCompound("Metadata");

            if (Tags != null)
            {
                foreach (NbtTag b in Tags)
                    newCompound.Add(b);
            }

            return newCompound;
        }
예제 #28
0
        private static NbtFile CreateNbtFromChunkColumn(ChunkColumn chunk, int yoffset)
        {
            var nbt = new NbtFile();

            NbtCompound levelTag = new NbtCompound("Level");

            nbt.RootTag.Add(levelTag);

            levelTag.Add(new NbtInt("xPos", chunk.x));
            levelTag.Add(new NbtInt("zPos", chunk.z));
            levelTag.Add(new NbtByteArray("Biomes", chunk.biomeId));

            NbtList sectionsTag = new NbtList("Sections");

            levelTag.Add(sectionsTag);

            for (int i = 0; i < 8; i++)
            {
                NbtCompound sectionTag = new NbtCompound();
                sectionsTag.Add(sectionTag);
                sectionTag.Add(new NbtByte("Y", (byte)i));
                int sy = i * 16;

                byte[] blocks     = new byte[4096];
                byte[] data       = new byte[2048];
                byte[] blockLight = new byte[2048];
                byte[] skyLight   = new byte[2048];

                for (int x = 0; x < 16; x++)
                {
                    for (int z = 0; z < 16; z++)
                    {
                        for (int y = 0; y < 16; y++)
                        {
                            int yi = sy + y;
                            if (yi < 0 || yi >= 256)
                            {
                                continue;                                                  // ?
                            }
                            int  anvilIndex = (y + yoffset) * 16 * 16 + z * 16 + x;
                            byte blockId    = chunk.GetBlock(x, yi, z);

                            // PE to Anvil friendly converstion
                            if (blockId == 5)
                            {
                                blockId = 125;
                            }
                            else if (blockId == 158)
                            {
                                blockId = 126;
                            }
                            else if (blockId == 50)
                            {
                                blockId = 75;
                            }
                            else if (blockId == 50)
                            {
                                blockId = 76;
                            }
                            else if (blockId == 89)
                            {
                                blockId = 123;
                            }
                            else if (blockId == 89)
                            {
                                blockId = 124;
                            }
                            else if (blockId == 73)
                            {
                                blockId = 152;
                            }

                            blocks[anvilIndex] = blockId;
                            SetNibble4(data, anvilIndex, chunk.GetMetadata(x, yi, z));
                            SetNibble4(blockLight, anvilIndex, chunk.GetBlocklight(x, yi, z));
                            SetNibble4(skyLight, anvilIndex, chunk.GetSkylight(x, yi, z));
                        }
                    }
                }

                sectionTag.Add(new NbtByteArray("Blocks", blocks));
                sectionTag.Add(new NbtByteArray("Data", data));
                sectionTag.Add(new NbtByteArray("BlockLight", blockLight));
                sectionTag.Add(new NbtByteArray("SkyLight", skyLight));
            }

            // TODO: Save entities
            NbtList entitiesTag = new NbtList("Entities", NbtTagType.Compound);

            levelTag.Add(entitiesTag);

            NbtList blockEntitiesTag = new NbtList("TileEntities", NbtTagType.Compound);

            levelTag.Add(blockEntitiesTag);
            foreach (NbtCompound blockEntityNbt in chunk.BlockEntities.Values)
            {
                NbtCompound nbtClone = (NbtCompound)blockEntityNbt.Clone();
                nbtClone.Name = null;
                blockEntitiesTag.Add(nbtClone);
            }

            levelTag.Add(new NbtList("TileTicks", NbtTagType.Compound));

            return(nbt);
        }
예제 #29
0
        /// <summary>
        /// Saves the ClassicWorld map.
        /// </summary>
        public void Save(string Filename)
        {
            var NbtMetadata = Foreignmeta.Write();

            foreach (IMetadataStructure b in MetadataParsers.Values)
            {
                var Nbt = b.Write();

                if (Nbt != null)
                    NbtMetadata.Add(Nbt);

                Nbt = null;
            }

            var compound = new NbtCompound("ClassicWorld") {
                new NbtByte("FormatVersion", 1),
                new NbtString("Name", MapName),
                new NbtByteArray("UUID", UUID),
                new NbtShort("X", Size.x),
                new NbtShort("Y", Size.y),
                new NbtShort("Z", Size.z),
                new NbtCompound("Spawn") {
                    new NbtShort("X", SpawnPos.x),
                    new NbtShort("Y", SpawnPos.y),
                    new NbtShort("Z", SpawnPos.z),
                    new NbtByte("H", (byte)SpawnRotation.x),
                    new NbtByte("P", (byte)SpawnRotation.z)
                },
                new NbtByteArray("BlockArray", BlockData),
                NbtMetadata
            };

            if (CreatingService != null && CreatingUsername != null)
            {
                var CreatedByTag = new NbtCompound("CreatedBy") {
                    new NbtString("Service", CreatingService),
                    new NbtString("Username", CreatingUsername)
                };

                compound.Add(CreatedByTag);
            }

            if (GeneratingSoftware != null && GeneratorName != null)
            {
                var MapGenerator = new NbtCompound("MapGenerator") {
                    new NbtString("Software", GeneratingSoftware),
                    new NbtString("MapGeneratorName", GeneratorName)
                };

                compound.Add(MapGenerator);
            }

            if (TimeCreated != 0.0)
                compound.Add(new NbtLong("TimeCreated", TimeCreated));

            if (LastAccessed != 0.0)
                compound.Add(new NbtLong("LastAccessed", LastAccessed));

            if (LastModified != 0.0)
                compound.Add(new NbtLong("LastModified", LastModified));

            var myFile = new NbtFile(compound);
            myFile.SaveToFile(Filename, NbtCompression.GZip);

            compound = null;
            myFile = null;
            NbtMetadata = null;
        }
예제 #30
0
        public NbtCompound Write()
        {
            var BaseCPE = new NbtCompound("CPE");

            if (ClickDistanceVersion > 0)
            {
                var ClickDistanceTag = new NbtCompound("ClickDistance") {
                    new NbtInt("ExtensionVersion", ClickDistanceVersion),
                    new NbtShort("Distance", ClickDistance)
                };

                BaseCPE.Add(ClickDistanceTag);
            }

            if (CustomBlocksVersion > 0)
            {
                var CustomBlocksTag = new NbtCompound("CustomBlocks") {
                    new NbtInt("ExtensionVersion", CustomBlocksVersion),
                    new NbtShort("SupportLevel", CustomBlocksLevel),
                    new NbtByteArray("Fallback", CustomBlocksFallback)
                };

                BaseCPE.Add(CustomBlocksTag);
            }

            if (EnvColorsVersion > 0)
            {
                var EnvColorsTag = new NbtCompound("EnvColors") {
                    new NbtInt("ExtensionVersion", EnvColorsVersion),
                    new NbtCompound("Sky") {
                        new NbtShort("R", SkyColor[0]),
                        new NbtShort("G", SkyColor[1]),
                        new NbtShort("B", SkyColor[2])
                    },
                    new NbtCompound("Cloud") {
                        new NbtShort("R", CloudColor[0]),
                        new NbtShort("G", CloudColor[1]),
                        new NbtShort("B", CloudColor[2])
                    },
                    new NbtCompound("Fog") {
                        new NbtShort("R", FogColor[0]),
                        new NbtShort("G", FogColor[1]),
                        new NbtShort("B", FogColor[2])
                    },
                    new NbtCompound("Ambient") {
                        new NbtShort("R", AmbientColor[0]),
                        new NbtShort("G", AmbientColor[1]),
                        new NbtShort("B", AmbientColor[2])
                    },
                    new NbtCompound("Sunlight") {
                        new NbtShort("R", SunlightColor[0]),
                        new NbtShort("G", SunlightColor[1]),
                        new NbtShort("B", SunlightColor[2])
                    }
                };

                BaseCPE.Add(EnvColorsTag);
            }

            if (EnvMapAppearanceVersion > 0)
            {
                var EnvAppearanceTag = new NbtCompound("EnvMapAppearance") {
                    new NbtInt("ExtensionVersion",EnvMapAppearanceVersion),
                    new NbtString("TextureURL",TextureURL),
                    new NbtByte("SideBlock",SideBlock),
                    new NbtByte("EdgeBlock", EdgeBlock),
                    new NbtShort("SideLevel", SideLevel)
                };

                BaseCPE.Add(BaseCPE);
            }

            if (BaseCPE.Tags.Count() > 0)
                return BaseCPE;
            else
                return null;
        }
예제 #31
0
 public override void Save(string Folder)
 {
     string f = Path.Combine(Folder, "DefaultMapGenerator.dat");
     NbtFile nf = new NbtFile(f);
     nf.RootTag = new NbtCompound("__ROOT__");
     NbtCompound c = new NbtCompound("DefaultMapGenerator");
     c.Add(new NbtByte("GenerateCaves", (byte)(GenerateCaves ? 1 : 0)));
     c.Add(new NbtByte("GenerateDungeons", (byte)(GenerateDungeons ? 1 : 0)));
     c.Add(new NbtByte("GenerateOres", (byte)(GenerateOres ? 1 : 0)));
     c.Add(new NbtByte("GenerateWater", (byte)(GenerateWater ? 1 : 0)));
     c.Add(new NbtByte("HellMode", (byte)(HellMode ? 1 : 0)));
     c.Add(new NbtByte("GenerateTrees", (byte)(GenerateTrees ? 1 : 0)));
     c.Add(new NbtDouble("Frequency", Frequency));
     c.Add(new NbtByte("NoiseQuality", (byte)NoiseQuality));
     c.Add(new NbtInt("OctaveCount", OctaveCount));
     c.Add(new NbtDouble("Lacunarity", Lacunarity));
     c.Add(new NbtDouble("Persistance", Persistance));
     c.Add(new NbtDouble("ContinentNoiseFrequency", ContinentNoiseFrequency));
     c.Add(new NbtDouble("CaveThreshold", CaveThreshold));
     nf.RootTag.Add(c);
     nf.SaveFile(f);
 }
예제 #32
0
파일: Entity.cs 프로젝트: N3X15/MineEdit
 internal void Base2NBT(ref NbtCompound c,string _id)
 {
     c.Add(new NbtFloat("FallDistance", FallDistance));
     c.Add(new NbtByte("OnGround", OnGround));
     c.Add(new NbtString("id", _id));
     NbtList motion = new NbtList("Motion");
     motion.Tags.AddRange(new NbtDouble[]{
         new NbtDouble("", Motion.X),
         new NbtDouble("", Motion.Y),
         new NbtDouble("", Motion.Z)
     });
     c.Add(motion);
     NbtList pos = new NbtList("Pos");
     pos.Tags.AddRange(new NbtDouble[]{
         new NbtDouble("", Math.IEEERemainder(Pos.X,16)),
         new NbtDouble("", Pos.Y),
         new NbtDouble("", Math.IEEERemainder(Pos.Z,16))
     });
     c.Add(pos);
     c.Add(Rotation.ToNBT());
 }
예제 #33
0
        public void SavePlayer(PlayerEntity entity)
        {
            // TODO: Generalize to all mobs
            NbtFile file = new NbtFile();
            var data = new NbtCompound();
            data.Add(new NbtByte("OnGround", (byte)(entity.OnGround ? 1 : 0)));
            data.Add(new NbtShort("Air", entity.Air));
            data.Add(new NbtShort("Health", entity.Health));
            data.Add(new NbtInt("Dimension", 0)); // TODO
            data.Add(new NbtInt("foodLevel", entity.Food));
            data.Add(new NbtInt("XpLevel", entity.XpLevel));
            data.Add(new NbtInt("XpTotal", entity.XpTotal));
            data.Add(new NbtFloat("foodExhaustionLevel", entity.FoodExhaustion));
            data.Add(new NbtFloat("foodSaturationLevel", entity.FoodSaturation));
            data.Add(new NbtFloat("XpP", entity.XpProgress));
            data.Add(new NbtList("Equipment"));
            var inventory = new NbtList("Inventory");
            for (int index = 0; index < entity.Inventory.Length; index++)
            {
                var slot = entity.Inventory[index];
                if (slot.Empty)
                    continue;
                slot.Index = NetworkSlotToDataSlot(index);
                inventory.Add(slot.ToNbt());
            }
            data.Add(inventory);
            var motion = new NbtList("Motion");
            motion.Add(new NbtDouble(entity.Velocity.X));
            motion.Add(new NbtDouble(entity.Velocity.Y));
            motion.Add(new NbtDouble(entity.Velocity.Z));
            data.Add(motion);

            var pos = new NbtList("Pos");
            pos.Add(new NbtDouble(entity.Position.X));
            pos.Add(new NbtDouble(entity.Position.Y));
            pos.Add(new NbtDouble(entity.Position.Z));
            data.Add(pos);

            var rotation = new NbtList("Rotation");
            rotation.Add(new NbtFloat(entity.Yaw));
            rotation.Add(new NbtFloat(entity.Pitch));
            data.Add(rotation);

            data.Add(new NbtCompound("abilities"));

            file.RootTag = data;
            if (!Directory.Exists(Path.Combine(LevelDirectory, "players")))
                Directory.CreateDirectory(Path.Combine(LevelDirectory, "players"));
            using (Stream stream = File.Open(Path.Combine(LevelDirectory, "players", entity.Username + ".dat"), FileMode.OpenOrCreate))
                file.SaveToStream(stream, NbtCompression.GZip);
        }
예제 #34
0
        //public static void setTag(this NbtCompound tag, string name, NbtCompound value) {
        //    tag.Add(new NbtCompound(name, value));
        //}

        public static void setTag(this NbtCompound tag, string name, double value)
        {
            tag.Add(new NbtDouble(name, value));
        }
예제 #35
0
        private NbtCompound AddCommand(string command, int x, int y, int z, bool auto, string mode)
        {
            var NodePoint = new NbtCompound();

            if (mode == "1.13")
            {
                NodePoint.Add(new NbtString("Id", "minecraft:command_block"));
                NodePoint.Add(new NbtString("Command", command));
                NodePoint.Add(new NbtByte("TrackOutput", 1));
                NodePoint.Add(new NbtString("CustomName", "{\"text\":\"@\"}"));
                NodePoint.Add(new NbtInt("SuccessCount", 0));
                NodePoint.Add(new NbtByte("auto", auto ? (byte)1 : (byte)0));
                NodePoint.Add(new NbtByte("powered", 0));
                NodePoint.Add(new NbtByte("conditionMet", 0));
                NodePoint.Add(new NbtByte("UpdateLastExecution", 1));
                NodePoint.Add(new NbtIntArray("Pos", new int[] { x, y, z }));
            }
            else
            {
                NodePoint.Add(new NbtString("id", "minecraft:command_block"));
                NodePoint.Add(new NbtString("Command", command));
                NodePoint.Add(new NbtByte("TrackOutput", 1));
                NodePoint.Add(new NbtString("CustomName", "@"));
                NodePoint.Add(new NbtInt("SuccessCount", 0));
                NodePoint.Add(new NbtByte("auto", auto ? (byte)1 : (byte)0));
                NodePoint.Add(new NbtByte("powered", 0));
                NodePoint.Add(new NbtByte("conditionMet", 0));
                NodePoint.Add(new NbtByte("UpdateLastExecution", 1));
                NodePoint.Add(new NbtInt("x", x));
                NodePoint.Add(new NbtInt("y", y));
                NodePoint.Add(new NbtInt("z", z));
            }
            return(NodePoint);
        }
예제 #36
0
 public static void setTag(this NbtCompound tag, string name, int[] value)
 {
     tag.Add(new NbtIntArray(name, value));
 }
예제 #37
0
 /// <summary>
 /// 序列化Schmeatic序列
 /// </summary>
 /// <param name="commandLine"></param>
 /// <param name="SettingParam"></param>
 /// <returns></returns>
 public NbtCompound Serialize(CommandLine commandLine, ExportSetting SettingParam)
 {
     try
     {
         var Schematic = new NbtCompound("Schematic");
         //CommandLine -> BlockInfo
         var blockInfo = CommandLine2SchematicInfo(commandLine, SettingParam, (SettingParam.Type == ExportSetting.ExportType.WorldEdit_113) ? "1.13" : "");
         //BlockInfo -> Schematic
         Schematic.Add(blockInfo.Height);
         Schematic.Add(blockInfo.Length);
         Schematic.Add(blockInfo.Width);
         Schematic.Add(new NbtList("Entities", NbtTagType.Compound));
         Schematic.Add(blockInfo.Data);
         Schematic.Add(blockInfo.Blocks);
         Schematic.Add(blockInfo.TileEntities);
         if (SettingParam.Type == ExportSetting.ExportType.WorldEdit)
         {
             var weInfo = BlockInfo2WorldEditBlockInfo(blockInfo, SettingParam.Direction);
             Schematic.Remove("Entities");
             Schematic.Add(weInfo.Materials);
             Schematic.Add(weInfo.WEOriginX);
             Schematic.Add(weInfo.WEOriginY);
             Schematic.Add(weInfo.WEOriginZ);
             Schematic.Add(weInfo.WEOffsetX);
             Schematic.Add(weInfo.WEOffsetY);
             Schematic.Add(weInfo.WEOffsetZ);
         }
         else if (SettingParam.Type == ExportSetting.ExportType.WorldEdit_113) //1.13
         {
             var schem = BlockInfo2Schema113Info(blockInfo, SettingParam.Direction);
             Schematic.Remove(blockInfo.Data);
             Schematic.Remove(blockInfo.Blocks);
             Schematic.Remove("Entities");
             Schematic.Add(schem.Metadata);
             Schematic.Add(schem.Palette);
             Schematic.Add(schem.PaletteMax);
             Schematic.Add(schem.Version);
             Schematic.Add(schem.BlockData);
             Schematic.Add(schem.Offset);
         }
         return(Schematic);
     }
     catch
     {
         return(null);
     }
 }
예제 #38
0
 public static void setTag(this NbtCompound tag, string name, long value)
 {
     tag.Add(new NbtLong(name, value));
 }
예제 #39
0
 public CustomTestItem(uint someVariable)
 {
     SomeVariable = someVariable;
     ExtraData    = new NbtCompound();
     ExtraData.Add(new NbtInt("HashCode", GetHashCode()));
 }
예제 #40
0
 public static void setTag(this NbtCompound tag, string name, Guid value)
 {
     tag.Add(new NbtString(name, value.ToString()));
 }
예제 #41
0
        private static NbtFile CreateNbtFromChunkColumn(ChunkColumn chunk, int yoffset)
        {
            var nbt = new NbtFile();

            var levelTag = new NbtCompound("Level");
            nbt.RootTag.Add(levelTag);

            levelTag.Add(new NbtInt("xPos", chunk.X));
            levelTag.Add(new NbtInt("zPos", chunk.Z));
            levelTag.Add(new NbtByteArray("Biomes", chunk.BiomeId));

            var sectionsTag = new NbtList("Sections");
            levelTag.Add(sectionsTag);

            for (var i = 0; i < 8; i++)
            {
                var sectionTag = new NbtCompound();
                sectionsTag.Add(sectionTag);
                sectionTag.Add(new NbtByte("Y", (byte) i));
                var sy = i*16;

                var blocks = new byte[4096];
                var data = new byte[2048];
                var blockLight = new byte[2048];
                var skyLight = new byte[2048];

                for (var x = 0; x < 16; x++)
                {
                    for (var z = 0; z < 16; z++)
                    {
                        for (var y = 0; y < 16; y++)
                        {
                            var yi = sy + y;
                            if (yi < 0 || yi >= 256) continue; // ?

                            var anvilIndex = (y + yoffset)*16*16 + z*16 + x;
                            var blockId = chunk.GetBlock(x, yi, z);

                            blocks[anvilIndex] = (byte) blockId;
                            SetNibble4(data, anvilIndex, chunk.GetMetadata(x, yi, z));
                            SetNibble4(blockLight, anvilIndex, chunk.GetBlocklight(x, yi, z));
                            SetNibble4(skyLight, anvilIndex, chunk.GetSkylight(x, yi, z));
                        }
                    }
                }

                sectionTag.Add(new NbtByteArray("Blocks", blocks));
                sectionTag.Add(new NbtByteArray("Data", data));
                sectionTag.Add(new NbtByteArray("BlockLight", blockLight));
                sectionTag.Add(new NbtByteArray("SkyLight", skyLight));
            }

            levelTag.Add(new NbtList("Entities", NbtTagType.Compound));
            levelTag.Add(new NbtList("TileEntities", NbtTagType.Compound));
            levelTag.Add(new NbtList("TileTicks", NbtTagType.Compound));

            return nbt;
        }
예제 #42
0
        public void AddingAndRemoving()
        {
            var foo  = new NbtInt("Foo");
            var test = new NbtCompound {
                foo
            };

            // adding duplicate object
            Assert.Throws <ArgumentException>(() => test.Add(foo));

            // adding duplicate name
            Assert.Throws <ArgumentException>(() => test.Add(new NbtByte("Foo")));

            // adding unnamed tag
            Assert.Throws <ArgumentException>(() => test.Add(new NbtInt()));

            // adding null
            Assert.Throws <ArgumentNullException>(() => test.Add(null));

            // adding tag to self
            Assert.Throws <ArgumentException>(() => test.Add(test));

            // contains existing name/object
            Assert.IsTrue(test.Contains("Foo"));
            Assert.IsTrue(test.Contains(foo));
            Assert.Throws <ArgumentNullException>(() => test.Contains((string)null));
            Assert.Throws <ArgumentNullException>(() => test.Contains((NbtTag)null));

            // contains non-existent name
            Assert.IsFalse(test.Contains("Bar"));

            // contains existing name / different object
            Assert.IsFalse(test.Contains(new NbtInt("Foo")));

            // removing non-existent name
            Assert.Throws <ArgumentNullException>(() => test.Remove((string)null));
            Assert.IsFalse(test.Remove("Bar"));

            // removing existing name
            Assert.IsTrue(test.Remove("Foo"));

            // removing non-existent name
            Assert.IsFalse(test.Remove("Foo"));

            // re-adding object
            test.Add(foo);

            // removing existing object
            Assert.Throws <ArgumentNullException>(() => test.Remove((NbtTag)null));
            Assert.IsTrue(test.Remove(foo));
            Assert.IsFalse(test.Remove(foo));

            // clearing an empty NbtCompound
            Assert.AreEqual(0, test.Count);
            test.Clear();

            // re-adding after clearing
            test.Add(foo);
            Assert.AreEqual(1, test.Count);

            // clearing a non-empty NbtCompound
            test.Clear();
            Assert.AreEqual(0, test.Count);
        }
예제 #43
0
        private static NbtFile CreateNbtFromChunkColumn(ChunkColumn chunk, int yoffset)
        {
            var nbt = new NbtFile();

            NbtCompound levelTag = new NbtCompound("Level");
            nbt.RootTag.Add(levelTag);

            levelTag.Add(new NbtInt("xPos", chunk.x));
            levelTag.Add(new NbtInt("zPos", chunk.z));
            levelTag.Add(new NbtByteArray("Biomes", chunk.biomeId));

            NbtList sectionsTag = new NbtList("Sections");
            levelTag.Add(sectionsTag);

            for (int i = 0; i < 8; i++)
            {
                NbtCompound sectionTag = new NbtCompound();
                sectionsTag.Add(sectionTag);
                sectionTag.Add(new NbtByte("Y", (byte) i));
                int sy = i*16;

                byte[] blocks = new byte[4096];
                byte[] data = new byte[2048];
                byte[] blockLight = new byte[2048];
                byte[] skyLight = new byte[2048];

                for (int x = 0; x < 16; x++)
                {
                    for (int z = 0; z < 16; z++)
                    {
                        for (int y = 0; y < 16; y++)
                        {
                            int yi = sy + y;
                            if (yi < 0 || yi >= 256) continue; // ?

                            int anvilIndex = (y + yoffset)*16*16 + z*16 + x;
                            byte blockId = chunk.GetBlock(x, yi, z);

                            // PE to Anvil friendly converstion
                            if (blockId == 5) blockId = 125;
                            else if (blockId == 158) blockId = 126;
                            else if (blockId == 50) blockId = 75;
                            else if (blockId == 50) blockId = 76;
                            else if (blockId == 89) blockId = 123;
                            else if (blockId == 89) blockId = 124;
                            else if (blockId == 73) blockId = 152;

                            blocks[anvilIndex] = blockId;
                            SetNibble4(data, anvilIndex, chunk.GetMetadata(x, yi, z));
                            SetNibble4(blockLight, anvilIndex, chunk.GetBlocklight(x, yi, z));
                            SetNibble4(skyLight, anvilIndex, chunk.GetSkylight(x, yi, z));
                        }
                    }
                }

                sectionTag.Add(new NbtByteArray("Blocks", blocks));
                sectionTag.Add(new NbtByteArray("Data", data));
                sectionTag.Add(new NbtByteArray("BlockLight", blockLight));
                sectionTag.Add(new NbtByteArray("SkyLight", skyLight));
            }

            // TODO: Save entities
            NbtList entitiesTag = new NbtList("Entities", NbtTagType.Compound);
            levelTag.Add(entitiesTag);

            NbtList blockEntitiesTag = new NbtList("TileEntities", NbtTagType.Compound);
            levelTag.Add(blockEntitiesTag);
            foreach (NbtCompound blockEntityNbt in chunk.BlockEntities.Values)
            {
                NbtCompound nbtClone = (NbtCompound) blockEntityNbt.Clone();
                nbtClone.Name = null;
                blockEntitiesTag.Add(nbtClone);
            }

            levelTag.Add(new NbtList("TileTicks", NbtTagType.Compound));

            return nbt;
        }
예제 #44
0
파일: Item.cs 프로젝트: N3X15/MineEdit
 public override NbtCompound ToNBT()
 {
     NbtCompound c = new NbtCompound();
     Base2NBT(ref c, GetID());
     NbtCompound i = new NbtCompound("Item");
     i.Add(new NbtShort("id", ItemID));
     i.Add(new NbtShort("Damage", Damage));
     i.Add(new NbtByte("Count", Count));
     c.Add(i);
     c.Add(new NbtShort("Health", Health));
     c.Add(new NbtShort("Age", Age));
     return c;
 }
예제 #45
0
파일: Furnace.cs 프로젝트: N3X15/MineEdit
        public override NbtCompound ToNBT()
        {
            NbtCompound c = new NbtCompound();
            Base2NBT(ref c);
            c.Add(new NbtShort("BurnTime",BurnTime));
            c.Add(new NbtShort("CookTime",CookTime));
            NbtList Items = new NbtList("Items");
            for (int i = 0; i < 3; i++)
            {
                if (Slots[i].ID != 0x00)
                {
                    NbtCompound cc = new NbtCompound();

                    cc.Add(new NbtShort("id",Slots[i].ID));
                    cc.Add(new NbtShort("Damage",(short)Slots[i].Damage));
                    cc.Add(new NbtByte("Count",(byte)Slots[i].Count));
                    cc.Add(new NbtByte("Slot", (byte)i));

                    Items.Add(cc);
                }
            }
            c.Add(Items);
            return c;
        }
예제 #46
0
파일: ListTests.cs 프로젝트: fragmer/fNbt
        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);
            }
        }
예제 #47
0
        public void SetItem(Item item)
        {
            var newItem = new NbtCompound("Item")
            {
                new NbtShort("id", item.Id),
                new NbtShort("Damage", item.Metadata),
                new NbtByte("Count", 1)
            };

            if (item.ExtraData != null)
            {
                var newTag = (NbtTag) item.ExtraData.Clone();
                newTag.Name = "tag";
                newItem.Add(newTag);
            }

            var comp = new NbtCompound(string.Empty)
            {
                new NbtString("id", Id),
                new NbtInt("x", Coordinates.X),
                new NbtInt("y", Coordinates.Y),
                new NbtInt("z", Coordinates.Z),
            };

            comp["Item"] = newItem;
            Compound = comp;
        }
예제 #48
0
        public static 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;

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

            if (!File.Exists(filePath))
            {
                return(generator?.GenerateChunkColumn(coordinates));
                //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;

                int length = regionFile.ReadByte();

                if (offset == 0 || length == 0)
                {
                    return(generator?.GenerateChunkColumn(coordinates));
                    //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();

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

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

                // This will turn into a full chunk column
                foreach (NbtTag sectionTag in sections)
                {
                    int    sy      = sectionTag["Y"].ByteValue * 16;
                    byte[] blocks  = sectionTag["Blocks"].ByteArrayValue;
                    byte[] data    = sectionTag["Data"].ByteArrayValue;
                    NbtTag addTag  = sectionTag["Add"];
                    byte[] adddata = new byte[2048];
                    if (addTag != null)
                    {
                        adddata = addTag.ByteArrayValue;
                    }
                    byte[] blockLight = sectionTag["BlockLight"].ByteArrayValue;
                    byte[] skyLight   = sectionTag["SkyLight"].ByteArrayValue;

                    for (int x = 0; x < 16; x++)
                    {
                        for (int z = 0; z < 16; z++)
                        {
                            for (int y = 0; y < 16; y++)
                            {
                                int yi = sy + y - yoffset;
                                if (yi < 0 || yi >= 128)
                                {
                                    continue;
                                }

                                int anvilIndex = y * 16 * 16 + z * 16 + x;
                                int blockId    = blocks[anvilIndex] + (Nibble4(adddata, anvilIndex) << 8);

                                // Anvil to PE friendly converstion

                                Func <int, byte, byte> dataConverter = (i, b) => b;                                // Default no-op converter
                                if (Convert.ContainsKey(blockId))
                                {
                                    dataConverter = Convert[blockId].Item2;
                                    blockId       = Convert[blockId].Item1;
                                }

                                if (blockId > 255)
                                {
                                    blockId = 41;
                                }

                                //if (yi == 127 && blockId != 0) blockId = 30;
                                if (yi == 0 && (blockId == 8 || blockId == 9))
                                {
                                    blockId = 7;
                                }

                                chunk.SetBlock(x, yi, z, (byte)blockId);
                                byte metadata = Nibble4(data, anvilIndex);
                                metadata = dataConverter(blockId, metadata);

                                chunk.SetMetadata(x, yi, z, metadata);
                                chunk.SetBlocklight(x, yi, z, Nibble4(blockLight, anvilIndex));
                                chunk.SetSkylight(x, yi, z, Nibble4(skyLight, anvilIndex));

                                var block = BlockFactory.GetBlockById(chunk.GetBlock(x, yi, z));
                                if (block is BlockStairs || block is StoneSlab || block is WoodSlab)
                                {
                                    chunk.SetSkylight(x, yi, z, 0xff);
                                }

                                if (blockId == 43 && chunk.GetMetadata(x, yi, z) == 7)
                                {
                                    chunk.SetMetadata(x, yi, z, 6);
                                }
                                else if (blockId == 44 && chunk.GetMetadata(x, yi, z) == 7)
                                {
                                    chunk.SetMetadata(x, yi, z, 6);
                                }
                                else if (blockId == 44 && chunk.GetMetadata(x, yi, z) == 15)
                                {
                                    chunk.SetMetadata(x, yi, z, 14);
                                }
                                else if (blockId == 3 && chunk.GetMetadata(x, yi, z) == 1)
                                {
                                    // Dirt Course => (Grass Path)
                                    chunk.SetBlock(x, yi, z, 198);
                                    chunk.SetMetadata(x, yi, z, 0);
                                }
                                else if (blockId == 3 && chunk.GetMetadata(x, yi, z) == 2)
                                {
                                    // Dirt Podzol => (Podzol)
                                    chunk.SetBlock(x, yi, z, 243);
                                    chunk.SetMetadata(x, yi, z, 0);
                                }
                            }
                        }
                    }
                }

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

                        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"];

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

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

                chunk.isDirty = false;
                return(chunk);
            }
        }
예제 #49
0
파일: Sign.cs 프로젝트: N3X15/MineEdit
 public override NbtCompound ToNBT()
 {
     NbtCompound c = new NbtCompound();
     Base2NBT(ref c);
     for (int i = 0; i < 4; i++)
     {
         string tagID = string.Format("Text{0}", i + 1);
         c.Add(new NbtString(tagID, Text[i]));
     }
     return c;
 }
예제 #50
0
        /// <summary>
        /// Saves a command block chain to a structure file at the given path. Does not attempt to modify it (e.g. for conditionals on turns).
        /// The file argument will be overwritten with a GZip-compressed NBT format structure file.
        /// </summary>
        /// <param name="chainStart">The beginning of the command block chain.</param>
        /// <param name="savePath">The path to the structure file where this command chain will be saved.</param>
        public void Save(CommandChainEntry chainStart, string savePath)
        {
            CommandChainEntry[]   chain = chainStart.EnumerateChain().ToArray();
            CommandBlockDirection dir   = CommandBlockDirection.East;

            int rowFlat    = 0;
            int height     = 0;
            int columnFlat = 0;

            NbtFile file = new NbtFile();

            file.RootTag = new NbtCompound("")
            {
                new NbtList("size")
                {
                    // TODO calculate size dynamically
                    new NbtInt(32),
                    new NbtInt(32),
                    new NbtInt(32)
                },
                //new NbtList("entities") { },
                new NbtList("palette")
                {
                },
                new NbtList("blocks")
                {
                },
                new NbtString("author", "MCCBL Compiler"),
                new NbtInt("version", 1)
            };

            for (int i = 0; i < chain.Length; i++)
            {
                int state = -1;
                rowFlat    = i / 32;
                columnFlat = i % 32;
                dir        = rowFlat % 2 == 0 ? CommandBlockDirection.East : CommandBlockDirection.West;
                if (columnFlat == 31)
                {
                    dir = height % 2 == 0 ? CommandBlockDirection.South : CommandBlockDirection.North;
                }

                //foreach (NbtCompound paletteE in ((NbtList)file.RootTag.Get("palette")))
                //{
                //    if (paletteE == GetPaletteSignature(CommandBlockInfo.FromEnums(chain[i].Data, dir)))
                //    {
                //        alreadyInPalette = true;
                //        break;
                //    }
                //    state++;
                //}

                NbtCompound palSig      = GetPaletteSignature(CommandBlockInfo.FromEnums(chain[i].Data, dir));
                var         paletteList = file.RootTag.Get <NbtList>("palette");

                // TODO does NbtCompound implement value equality? If not, we may have to use the general purpose IndexOf with our own comparison interface
                // Tested and does not

                // state = paletteList.IndexOf(palSig);

                for (int j = 0; j < paletteList.Count; j++)
                {
                    NbtCompound curPal = paletteList[j] as NbtCompound;
                    if (curPal == null)
                    {
                        continue;
                    }

                    if (AreCompoundsEqual(curPal, palSig))
                    {
                        // We found an equivalent palette entry
                        state = j;
                        break;
                    }
                }

                if (state == -1)
                {
                    paletteList.Add(palSig);
                    // TODO is this needed?
                    // file.RootTag["palette"] = paletteList;
                    state = paletteList.Count - 1;
                }
                NbtCompound block = new NbtCompound();
                if (rowFlat % 2 == 0)
                {
                    block.Add(new NbtList("pos")
                    {
                        new NbtInt(columnFlat), new NbtInt(height), new NbtInt(rowFlat)
                    });
                }
                else
                {
                    block.Add(new NbtList("pos")
                    {
                        new NbtInt(31 - columnFlat), new NbtInt(height), new NbtInt(rowFlat)
                    });
                }
                block.Add(new NbtCompound("nbt")
                {
                    new NbtByte("auto", Convert.ToByte(chain[i].Data.HasFlag(CommandBlockFlags.AlwaysOn))),
                    new NbtString("Command", chain[i].Command),
                    new NbtString("id", "Control"),
                    new NbtString("CustomName", "@"),
                    new NbtByte("TrackOutput", 0),
                    new NbtByte("powered", 0),
                    new NbtByte("conditionMet", 1),
                    new NbtInt("SuccessCount", 0)
                });


                block.Add(new NbtInt("state", state));
                file.RootTag.Get <NbtList>("blocks").Add(block);
            }
            file.SaveToFile(savePath, NbtCompression.GZip);
        }
예제 #51
0
 public override NbtCompound writeToNbt(NbtCompound tag)
 {
     base.writeToNbt(tag);
     tag.Add(new NbtInt("length", this.length));
     return(tag);
 }
예제 #52
0
        internal static bool ReadTag(this NbtTag tag, NbtBinaryReader readStream)
        {
            while (true)
            {
                NbtTag     nbtTag = null;
                NbtTagType nbtTagType;                // = readStream.ReadTagType();
                do
                {
                    nbtTagType = readStream.ReadTagType();

                    switch (nbtTagType)
                    {
                    case NbtTagType.End:
                        break;

                    case NbtTagType.Byte:
                        nbtTag = (NbtTag) new NbtByte();
                        break;

                    case NbtTagType.Short:
                        nbtTag = (NbtTag) new NbtShort();
                        break;

                    case NbtTagType.Int:
                        nbtTag = (NbtTag) new NbtInt();
                        break;

                    case NbtTagType.Long:
                        nbtTag = (NbtTag) new NbtLong();
                        break;

                    case NbtTagType.Float:
                        nbtTag = (NbtTag) new NbtFloat();
                        break;

                    case NbtTagType.Double:
                        nbtTag = (NbtTag) new NbtDouble();
                        break;

                    case NbtTagType.ByteArray:
                        nbtTag = (NbtTag) new NbtByteArray();
                        break;

                    case NbtTagType.String:
                        nbtTag = (NbtTag) new NbtString();
                        break;

                    case NbtTagType.List:
                        nbtTag = (NbtTag) new NbtList();
                        break;

                    case NbtTagType.Compound:
                        nbtTag = (NbtTag) new NbtCompound();
                        break;

                    case NbtTagType.IntArray:
                        nbtTag = (NbtTag) new NbtIntArray();
                        break;

                    case NbtTagType.LongArray:
                        nbtTag = (NbtTag) new NbtLongArray();
                        break;

                    case NbtTagType.Unknown:
                        break;

                    default:
                        throw new FormatException("Unsupported tag type found in NBT_Compound: " + (object)nbtTagType);
                    }

                    if (nbtTag != null)
                    {
                        nbtTag.Name = readStream.ReadString();
                    }

                    //nbtTag.Parent = (NbtTag) this;
                    //nbtTag.Name = readStream.ReadString();
                }while (nbtTagType != NbtTagType.End && nbtTagType != NbtTagType.Unknown);

                switch (tag.TagType)
                {
                case NbtTagType.Compound:
                    NbtCompound compound = (NbtCompound)tag;
                    compound.Add(nbtTag);
                    break;

                case NbtTagType.List:
                    NbtList list = (NbtList)tag;
                    list.Add(nbtTag);
                    break;
                }
            }
        }
예제 #53
0
파일: Chest.cs 프로젝트: N3X15/MineEdit
 public override NbtCompound ToNBT()
 {
     NbtCompound c = new NbtCompound();
     Base2NBT(ref c);
     c.Add(Inventory.ToNBT());
     return c;
 }
예제 #54
0
 public NbtCompound ToNbt()
 {
     var c = new NbtCompound();
     c.Add(new NbtShort("id", Id));
     c.Add(new NbtShort("Damage", Metadata));
     c.Add(new NbtByte("Count", (byte)Count));
     c.Add(new NbtByte("Slot", (byte)Index));
     if (Nbt != null && Nbt.RootTag != null)
     {
         Nbt.RootTag = new NbtCompound("tag");
         c.Add(Nbt.RootTag);
     }
     return c;
 }
예제 #55
0
        public NbtCompound Save()
        {
            NbtCompound rtn = new NbtCompound();

            rtn.Add(new NbtString("name", name));

            NbtList ground = new NbtList("ground", NbtTagType.Compound);
            NbtList portal = new NbtList("portal", NbtTagType.Compound);
            NbtList decor = new NbtList("decor", NbtTagType.Compound);
            foreach(Point alpha in map.Keys) {
                if(map[alpha] is Platform) {
                    ground.Add(new NbtCompound(new NbtByte[] {
                        new NbtByte("x", (byte)alpha.X),
                        new NbtByte("y", (byte)alpha.Y)
                    }));
                } else if(map[alpha] is Portal) {
                    portal.Add(new NbtCompound(new NbtTag[] {
                        new NbtByte("x", (byte)alpha.X),
                        new NbtByte("y", (byte)alpha.Y),
                        new NbtString("linkTo", ((Portal)map[alpha]).Link.MyArea.Name),
                        new NbtByte("linkX", (byte)((Portal)map[alpha]).Link.Location.X),
                        new NbtByte("linkY", (byte)((Portal)map[alpha]).Link.Location.Y)
                    }));
                }
            }

            rtn.AddRange(new NbtList[] { ground, portal, decor });

            return rtn;
        }
예제 #56
0
        private NbtCompound ParseCompound()
        {
            bool        more        = true;
            NbtCompound compound    = new NbtCompound();
            NbtTag      current     = null;
            string      currentName = "";
            bool        afterName   = false;

            while (more)
            {
                char next;
                try
                {
                    next = NextChar();
                }
                catch (Exception)
                {
                    throw new Exception(@"Unexpected EOF, expected '}'");
                }
                switch (next)
                {
                case '}':
                    more = false;
                    goto case ',';     //f****n fall through.

                case ',':
                    if (current != null)
                    {
                        current.Name = currentName;
                        compound.Add(current);
                        afterName   = false;
                        current     = null;
                        currentName = "";
                    }
                    break;

                case ' ':
                case '\t':
                case '\r':
                case '\n':
                    break;

                case ':':
                    afterName = true;
                    break;

                default:
                    if (afterName)
                    {
                        Position--;
                        current = ParseTag();
                    }
                    else
                    {
                        currentName += next;
                    }
                    break;
                }
            }
            return(compound);
        }
        public void AddingAndRemoving()
        {
            var foo = new NbtInt("Foo");
            var test = new NbtCompound
            {
                foo
            };

            // adding duplicate object
            Assert.Throws<ArgumentException>(() => test.Add(foo));

            // adding duplicate name
            Assert.Throws<ArgumentException>(() => test.Add(new NbtByte("Foo")));

            // adding unnamed tag
            Assert.Throws<ArgumentException>(() => test.Add(new NbtInt()));

            // adding null
            Assert.Throws<ArgumentNullException>(() => test.Add(null));

            // adding tag to self
            Assert.Throws<ArgumentException>(() => test.Add(test));

            // contains existing name/object
            Assert.True(test.Contains("Foo"));
            Assert.True(test.Contains(foo));
            Assert.Throws<ArgumentNullException>(() => test.Contains((string) null));
            Assert.Throws<ArgumentNullException>(() => test.Contains((NbtTag) null));

            // contains non-existent name
            Assert.False(test.Contains("Bar"));

            // contains existing name / different object
            Assert.False(test.Contains(new NbtInt("Foo")));

            // removing non-existent name
            Assert.Throws<ArgumentNullException>(() => test.Remove((string) null));
            Assert.False(test.Remove("Bar"));

            // removing existing name
            Assert.True(test.Remove("Foo"));

            // removing non-existent name
            Assert.False(test.Remove("Foo"));

            // re-adding object
            test.Add(foo);

            // removing existing object
            Assert.Throws<ArgumentNullException>(() => test.Remove((NbtTag) null));
            Assert.True(test.Remove(foo));
            Assert.False(test.Remove(foo));

            // clearing an empty NbtCompound
            Assert.Equal(0, test.Count);
            test.Clear();

            // re-adding after clearing
            test.Add(foo);
            Assert.Equal(1, test.Count);

            // clearing a non-empty NbtCompound
            test.Clear();
            Assert.Equal(0, test.Count);
        }
        public void ReadAsTagTest3()
        {
            // read values as tags
            byte[] testData = new NbtFile(TestFiles.MakeValueTest()).SaveToBuffer(NbtCompression.None);
            var reader = new NbtReader(new MemoryStream(testData));
            var root = new NbtCompound("root");

            // skip root
            reader.ReadToFollowing();
            reader.ReadToFollowing();

            while (!reader.IsAtStreamEnd)
            {
                root.Add(reader.ReadAsTag());
            }

            TestFiles.AssertValueTest(new NbtFile(root));
        }
예제 #59
0
        public static void Save(this Player player, bool async = false)
        {
            NbtCompound namedTag = new NbtCompound("");

            namedTag.Add(player.GetNbtPos());
            namedTag.Add(player.GetNbtRotation());

            namedTag.Add(player.GetNbtHealth());
            namedTag.Add(player.GetNbtEffects());

            namedTag.Add(player.GetFoodNbt());
            namedTag.Add(player.GetNbtFoodExhaustionLevel());
            namedTag.Add(player.GetNbtFoodSaturationLevel());

            namedTag.Add(player.GetNbtXpLevel());
            namedTag.Add(player.GetNbtXpP());

            namedTag.Add(player.GetNbtInventory());
            namedTag.Add(player.GetNbtSelectedInventorySlot());

            namedTag.Add(player.GetNbtLevel());

            namedTag.Add(player.GetNbtPlayerGameType());

            player.GetServer().SaveOfflinePlayerData(player.PlayerInfo.Username, namedTag, async);
        }
예제 #60
-1
        public void GettersAndSetters()
        {
            NbtCompound parent = new NbtCompound( "Parent" );
            NbtCompound child = new NbtCompound( "Child" );
            NbtCompound nestedChild = new NbtCompound( "NestedChild" );
            NbtList childList = new NbtList( "ChildList" );
            NbtList nestedChildList = new NbtList( "NestedChildList" );
            NbtInt testInt = new NbtInt( 1 );
            childList.Add( testInt );
            nestedChildList.Add( testInt );
            parent.Add( child );
            parent.Add( childList );
            child.Add( nestedChild );
            child.Add( nestedChildList );

            // Accessing nested compound tags using indexers
            Assert.AreEqual( parent["Child"]["NestedChild"], nestedChild );
            Assert.AreEqual( parent["Child"]["NestedChildList"], nestedChildList );
            Assert.AreEqual( parent["Child"]["NestedChildList"][0], testInt );

            // Accessing nested compound tags using Get<T>
            Assert.AreEqual( parent.Get<NbtCompound>( "Child" ).Get<NbtCompound>( "NestedChild" ), nestedChild );
            Assert.AreEqual( parent.Get<NbtCompound>( "Child" ).Get<NbtList>( "NestedChildList" ), nestedChildList );
            Assert.AreEqual( parent.Get<NbtCompound>( "Child" ).Get<NbtList>( "NestedChildList" )[0], testInt );

            // Accessing with Get<T> and an invalid given type
            Assert.Throws<InvalidCastException>( () => parent.Get<NbtInt>( "Child" ) );

            // Trying to use integer indexers on non-NbtList tags
            Assert.Throws<InvalidOperationException>( () => parent[0] = testInt );
            Assert.Throws<InvalidOperationException>( () => testInt[0] = testInt );

            // Trying to use string indexers on non-NbtCompound tags
            Assert.Throws<InvalidOperationException>( () => childList["test"] = testInt );
            Assert.Throws<InvalidOperationException>( () => testInt["test"] = testInt );

            // Trying to get a non-existent element by name
            Assert.IsNull( parent.Get<NbtTag>( "NonExistentTag" ) );
            Assert.IsNull( parent["NonExistentTag"] );

            // Null indices on NbtCompound
            Assert.Throws<ArgumentNullException>( () => parent.Get<NbtTag>( null ) );
            Assert.Throws<ArgumentNullException>( () => parent[null] = testInt );
            Assert.Throws<ArgumentNullException>( () => testInt = (NbtInt)parent[null] );

            // Out-of-range indices on NbtList
            Assert.Throws<ArgumentOutOfRangeException>( () => testInt = (NbtInt)childList[-1] );
            Assert.Throws<ArgumentOutOfRangeException>( () => childList[-1] = testInt );
            Assert.Throws<ArgumentOutOfRangeException>( () => testInt = childList.Get<NbtInt>( -1 ) );
            Assert.Throws<ArgumentOutOfRangeException>( () => testInt = (NbtInt)childList[childList.Count] );
            Assert.Throws<ArgumentOutOfRangeException>( () => testInt = childList.Get<NbtInt>( childList.Count ) );
        }