Represents a complete NBT file.
Ejemplo n.º 1
0
        public Map()
        {
            if(File.Exists("mapfile.nbt")) {
                NbtFile saveFile = new NbtFile("mapfile.nbt");

                NbtCompound root = saveFile.RootTag;
                if(root.Get<NbtString>("fileType").StringValue.Equals("map")) {
                    NbtList aList = root.Get<NbtList>("areas");
                    foreach(NbtCompound alpha in aList) {
                        areas.Add(new Area(alpha));
                    }
                }
                foreach(Area alpha in areas) {
                    if(alpha.Name.Equals("safehouse", StringComparison.OrdinalIgnoreCase)) {
                        currArea = alpha;
                        break;
                    }
                }
                foreach(Area alpha in portalsToProcess.Keys) {
                    List<Portal> newPortals = new List<Portal>();
                    foreach(NbtCompound beta in portalsToProcess[alpha]) {
                        foreach(Area charlie in areas) {
                            if(charlie.Name == beta.Get<NbtString>("linkTo").StringValue) {
                                newPortals.Add(new Portal(new Microsoft.Xna.Framework.Rectangle(beta.Get<NbtByte>("x").IntValue * 32 + 4, beta.Get<NbtByte>("y").IntValue * 32 + 8, 25, 24),
                                    charlie, beta.Get<NbtByte>("linkX").IntValue * 32, beta.Get<NbtByte>("linkY").IntValue * 32));
                            }
                        }
                    }
                    alpha.AddPortals(newPortals);
                }
                portalsToProcess.Clear();
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Load a map file into memory and display information
 /// </summary>
 /// <param name="fi">The map file to load</param>
 private void Load(FileInfo fi)
 {
     NbtFile f = new NbtFile();
     fullName = fi.FullName;
     shortName = fi.Name;
     try
     {
         f.LoadFromFile(fullName);
     }
     catch (Exception ex)
     {
         string s = string.Format("Error loading {0}: {1}", fi.Name, ex.Message);
         MessageBox.Show(s);
         return;
     }
     try
     {
         var dataTag = f.RootTag["data"];
         Scale = dataTag["scale"].ByteValue;
         xCenter = dataTag["xCenter"].IntValue;
         zCenter = dataTag["zCenter"].IntValue;
         Height = dataTag["height"].IntValue;
         Width = dataTag["width"].IntValue;
         Dimension = dataTag["dimension"].ByteValue;
         Colors = dataTag["colors"].ByteArrayValue;
         MCMapToBitmap();
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Ejemplo n.º 3
0
        public void Load(string path)
        {
            //load nbt file
            var file = new NbtFile(path);

            //loop the data tag
            foreach (var i in ((NbtCompound) file.RootTag.First()))
            {
                //cast to dynamic
                dynamic val = i;
                //is it the gamerules tag
                if (i.Name == "GameRules")
                {//yes, loop all data in game rule tag
                    foreach (var x in ((NbtCompound) i))
                    {
                        dynamic valx = x;
                        SetValue(UppercaseFirst(x.Name), valx.Value, MapData.GameRules);//set value
                    }
                }
                else
                {//no, greate just set the value
                    SetValue(UppercaseFirst(i.Name), val.Value, MapData);//set value
                }
            }
        }
Ejemplo n.º 4
0
 public void Export(string path, NbtTag root)
 {
     if (Snbt)
     {
         File.WriteAllText(path, root.ToSnbt(CreateOptions()));
     }
     else
     {
         var file = new fNbt.NbtFile();
         file.BigEndian = BigEndian;
         file.RootTag   = root;
         using (var writer = File.Create(path))
         {
             if (BedrockHeader)
             {
                 writer.Seek(8, SeekOrigin.Begin);
             }
             long size = file.SaveToStream(writer, Compression);
             if (BedrockHeader)
             {
                 // bedrock level.dat files start with a header containing a magic number and then the little-endian size of the data
                 writer.Seek(0, SeekOrigin.Begin);
                 writer.Write(new byte[] { 8, 0, 0, 0 }, 0, 4);
                 writer.Write(DataUtils.GetBytes((int)size, little_endian: !BigEndian), 0, 4);
             }
         }
     }
 }
Ejemplo n.º 5
0
        public Map Load( string fileName ) {
            if( fileName == null ) throw new ArgumentNullException( "fileName" );
            NbtFile file = new NbtFile( fileName );
            if( file.RootTag == null ) throw new MapFormatException( "No root tag" );

            NbtCompound mapTag = file.RootTag.Get<NbtCompound>( "Map" );
            if( mapTag == null ) throw new MapFormatException( "No Map tag" );

            // ReSharper disable UseObjectOrCollectionInitializer
            Map map = new Map( null,
                               mapTag["Width"].ShortValue,
                               mapTag["Length"].ShortValue,
                               mapTag["Height"].ShortValue,
                               false );
            map.Spawn = new Position {
                X = mapTag["Spawn"][0].ShortValue,
                Z = mapTag["Spawn"][1].ShortValue,
                Y = mapTag["Spawn"][2].ShortValue
            };
            // ReSharper restore UseObjectOrCollectionInitializer

            map.Blocks = mapTag["Blocks"].ByteArrayValue;
            map.RemoveUnknownBlocktypes();

            return map;
        }
Ejemplo n.º 6
0
 public Map LoadHeader( string fileName ) {
     if( fileName == null ) throw new ArgumentNullException( "fileName" );
     NbtFile file = new NbtFile();
     file.LoadFromFile( fileName, NbtCompression.None, HeaderTagSelector );
     NbtCompound root = file.RootTag;
     return LoadHeaderInternal( root );
 }
Ejemplo n.º 7
0
        public static void Test()
        {
            fNbt.NbtFile test = new fNbt.NbtFile(TestPath + "level.dat");
            long         Seed;

            Seed = test.RootTag.Get("Data")["RandomSeed"].LongValue;
        }
Ejemplo n.º 8
0
        public void Save()
        {
            //Create nbt file
            var file = new NbtFile();
            var data = new NbtCompound() {Name = "Data"};

           
            file.RootTag.Add(data);
        }
Ejemplo n.º 9
0
 public Map Load( string fileName ) {
     if( fileName == null ) throw new ArgumentNullException( "fileName" );
     NbtFile file = new NbtFile();
     file.LoadFromFile( fileName, NbtCompression.None, null );
     NbtCompound root = file.RootTag;
     Map map = LoadHeaderInternal( root );
     map.Blocks = root["MapData"]["Blocks"].ByteArrayValue;
     return map;
 }
Ejemplo n.º 10
0
		public static void SaveLevel(LevelInfo level)
		{
			if (!Directory.Exists(_basePath))
				Directory.CreateDirectory(_basePath);

			NbtFile file = new NbtFile();
			NbtTag dataTag = file.RootTag["Data"] = new NbtCompound("Data");
			level.SaveToNbt(dataTag);
			file.SaveToFile(Path.Combine(_basePath, "level.dat"), NbtCompression.ZLib);
		}
Ejemplo n.º 11
0
 // TODO: Attempt to move these into Level proper
 public static void LoadPlayer(this Level level, RemoteClient client)
 {
     if (string.IsNullOrEmpty(level.BaseDirectory))
     {
         CreateNewPlayer(level, client);
         return;
     }
     Directory.CreateDirectory(Path.Combine(level.BaseDirectory, "players"));
     if (File.Exists(Path.Combine(level.BaseDirectory, "players", client.Username + ".dat")))
     {
         try
         {
             var file = new NbtFile(Path.Combine(level.BaseDirectory, "players", client.Username + ".dat"));
             // TODO: Consder trying to serialize this, maybe use AutoMapper?
             client.Entity = new PlayerEntity(client.Username);
             client.GameMode = (GameMode)file.RootTag["playerGameType"].IntValue;
             client.Entity.SelectedSlot = file.RootTag["SelectedItemSlot"].ShortValue;
             client.Entity.SpawnPoint = new Vector3(
                 file.RootTag["SpawnX"].IntValue,
                 file.RootTag["SpawnY"].IntValue,
                 file.RootTag["SpawnZ"].IntValue);
             client.Entity.Food = (short)file.RootTag["foodLevel"].IntValue;
             client.Entity.FoodExhaustion = file.RootTag["foodExhaustionLevel"].FloatValue;
             client.Entity.FoodSaturation = file.RootTag["foodSaturationLevel"].FloatValue;
             client.Entity.Health = file.RootTag["Health"].ShortValue;
             foreach (var tag in (NbtList)file.RootTag["Inventory"])
             {
                 client.Entity.Inventory[Level.DataSlotToNetworkSlot(tag["Slot"].ByteValue)] = 
                     new ItemStack(
                         tag["id"].ShortValue,
                         (sbyte)tag["Count"].ByteValue,
                         tag["Damage"].ShortValue,
                         tag["tag"] as NbtCompound);
             }
             client.Entity.Position = new Vector3(
                 file.RootTag["Pos"][0].DoubleValue,
                 file.RootTag["Pos"][1].DoubleValue,
                 file.RootTag["Pos"][2].DoubleValue);
             client.Entity.Yaw = file.RootTag["Rotation"][0].FloatValue;
             client.Entity.Pitch = file.RootTag["Rotation"][1].FloatValue;
             client.Entity.Velocity = new Vector3(
                 file.RootTag["Motion"][0].DoubleValue,
                 file.RootTag["Motion"][1].DoubleValue,
                 file.RootTag["Motion"][2].DoubleValue);
         }
         catch
         {
             CreateNewPlayer(level, client);
         }
     }
     else
         CreateNewPlayer(level, client);
 }
Ejemplo n.º 12
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);
 }
Ejemplo n.º 13
0
 public static void SavePlayer(this Level level, RemoteClient client)
 {
     if (string.IsNullOrEmpty(level.BaseDirectory))
         return;
     try
     {
         Directory.CreateDirectory(Path.Combine(level.BaseDirectory, "players"));
         var file = new NbtFile();
         file.RootTag.Add(new NbtInt("playerGameType", (int)client.GameMode));
         file.RootTag.Add(new NbtShort("SelectedItemSlot", client.Entity.SelectedSlot));
         file.RootTag.Add(new NbtInt("SpawnX", (int)client.Entity.SpawnPoint.X));
         file.RootTag.Add(new NbtInt("SpawnY", (int)client.Entity.SpawnPoint.Y));
         file.RootTag.Add(new NbtInt("SpawnZ", (int)client.Entity.SpawnPoint.Z));
         file.RootTag.Add(new NbtInt("foodLevel", client.Entity.Food));
         file.RootTag.Add(new NbtFloat("foodExhaustionLevel", client.Entity.FoodExhaustion));
         file.RootTag.Add(new NbtFloat("foodSaturationLevel", client.Entity.FoodSaturation));
         file.RootTag.Add(new NbtShort("Health", client.Entity.Health));
         var inventory = new NbtList("Inventory", NbtTagType.Compound);
         var slots = client.Entity.Inventory.GetSlots();
         for (int i = 0; i < slots.Length; i++)
         {
             var slot = (ItemStack)slots[i].Clone();
             slot.Index = Level.NetworkSlotToDataSlot(i);
             if (!slot.Empty)
                 inventory.Add(slot.ToNbt());
         }
         file.RootTag.Add(inventory);
         var position = new NbtList("Pos", NbtTagType.Double);
         position.Add(new NbtDouble(client.Entity.Position.X));
         position.Add(new NbtDouble(client.Entity.Position.Y));
         position.Add(new NbtDouble(client.Entity.Position.Z));
         file.RootTag.Add(position);
         var rotation = new NbtList("Rotation", NbtTagType.Float);
         rotation.Add(new NbtFloat(client.Entity.Yaw));
         rotation.Add(new NbtFloat(client.Entity.Pitch));
         file.RootTag.Add(rotation);
         var velocity = new NbtList("Motion", NbtTagType.Double);
         velocity.Add(new NbtDouble(client.Entity.Velocity.X));
         velocity.Add(new NbtDouble(client.Entity.Velocity.Y));
         velocity.Add(new NbtDouble(client.Entity.Velocity.Z));
         file.RootTag.Add(velocity);
         file.SaveToFile(Path.Combine(level.BaseDirectory, "players", client.Username + ".dat"), NbtCompression.None);
     }
     catch { } // If exceptions happen here, the entire server dies
 }
Ejemplo n.º 14
0
 public override void WriteTo(MinecraftStream stream, byte index)
 {
     stream.WriteUInt8(GetKey(index));
     stream.WriteInt16(Value.Id);
     if (Value.Id != -1)
     {
         stream.WriteInt8(Value.Count);
         stream.WriteInt16(Value.Metadata);
         if (Value.Nbt != null)
         {
             var file = new NbtFile(Value.Nbt);
             var data = file.SaveToBuffer(NbtCompression.GZip);
             stream.WriteInt16((short)data.Length);
             stream.WriteUInt8Array(data);
         }
         else
             stream.WriteInt16(-1);
     }
 }
Ejemplo n.º 15
0
 public static ServerList LoadFrom(string file)
 {
     var list = new ServerList();
     var nbt = new NbtFile(file);
     foreach (NbtCompound server in nbt.RootTag["servers"] as NbtList)
     {
         var entry = new Server();
         if (server.Contains("name"))
             entry.Name = server["name"].StringValue;
         if (server.Contains("ip"))
             entry.Ip = server["ip"].StringValue;
         if (server.Contains("hideAddress"))
             entry.HideAddress = server["hideAddress"].ByteValue == 1;
         if (server.Contains("acceptTextures"))
             entry.AcceptTextures = server["acceptTextures"].ByteValue == 1;
         list.Servers.Add(entry);
     }
     return list;
 }
Ejemplo n.º 16
0
        public NbtWrapper ReadNBT()
        {
            if (!this.ReadBoolean())
            {
                return null;
            }

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

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

            return new NbtWrapper { OriginalData = nbt, RootTag = rootTag };
        }
Ejemplo n.º 17
0
        public byte[] SaveBytes()
        {
            if (IsExternal)
            {
                var data = new byte[Size + 5];
                var size = DataUtils.GetBytes(1);
                Array.Copy(size, data, 4);
                data[4] = ExternalCompression;
                return(data);
            }
            if (!IsLoaded)
            {
                var stream = Region.GetStream();
                stream.Seek(Offset, SeekOrigin.Begin);
                byte[] result = new byte[Size];
                stream.Read(result, 0, Size);
                stream.Dispose();
                return(result);
            }
            if (IsCorrupt)
            {
                return(new byte[0]);
            }
            var file        = new fNbt.NbtFile(Data);
            var bytes       = file.SaveToBuffer(Compression);
            var with_header = new byte[bytes.Length + 5];

            Array.Copy(bytes, 0, with_header, 5, bytes.Length);
            var length = DataUtils.GetBytes(bytes.Length);

            Array.Copy(length, with_header, 4);
            if (Compression == NbtCompression.GZip)
            {
                with_header[4] = 1;
            }
            else if (Compression == NbtCompression.ZLib)
            {
                with_header[4] = 2;
            }
            HasUnsavedChanges = false;
            return(with_header);
        }
Ejemplo n.º 18
0
        public void Load()
        {
            if (IsCorrupt || IsExternal)
            {
                return;
            }
            var stream = Region.GetStream();

            stream.Seek(Offset + 4, SeekOrigin.Begin);
            int compression = stream.ReadByte();

            if (compression == -1)
            {
                IsCorrupt = true;
                Remove();
            }
            else
            {
                if ((compression & (1 << 7)) != 0)
                {
                    IsExternal          = true;
                    ExternalCompression = (byte)compression;
                }
                else
                {
                    var file = new fNbt.NbtFile();
                    try
                    {
                        file.LoadFromStream(stream, NbtCompression.AutoDetect);
                        Compression = file.FileCompression;
                        SetData(file.GetRootTag <NbtCompound>());
                    }
                    catch
                    {
                        IsCorrupt = true;
                        Remove();
                    }
                }
            }
            stream.Dispose();
            OnLoaded?.Invoke(this, EventArgs.Empty);
        }
Ejemplo n.º 19
0
        public void Save(Map mapToSave, string path) {
            NbtCompound rootTag = new NbtCompound("Schematic") {
                new NbtShort("Width", (short)mapToSave.Width),
                new NbtShort("Height", (short)mapToSave.Height),
                new NbtShort("Length", (short)mapToSave.Length),
                new NbtString("Materials", "Classic"),
                new NbtByteArray("Blocks", mapToSave.Blocks),

                // set to 0 unless converted in overloaded DoConversion
                new NbtByteArray("Data", new byte[mapToSave.Volume]),

                // these two lists are empty, but required for compatibility
                new NbtList("Entities", NbtTagType.Compound),
                new NbtList("TileEntities", NbtTagType.Compound),
            };
            DoConversion(rootTag);
            NbtFile file = new NbtFile(rootTag);
            file.SaveToFile(path, NbtCompression.GZip);
            File.WriteAllText("debug.txt", file.RootTag.ToString("    "));
        }
Ejemplo n.º 20
0
        private void Walk(DirectoryInfo folder)
        {
            foreach (FileInfo file in folder.GetFiles("level.dat"))
            {
                try
                {
                    var nbt = new NbtFile();
                    nbt.LoadFromFile(file.FullName);

                    var data = nbt.RootTag["Data"];
                    this.Worlds[data["LevelName"].StringValue] = folder;
                }
                catch
                {
                    // ignore any load problems...
                }
            }

            foreach (DirectoryInfo child in folder.GetDirectories())
                this.Walk(child);
        }
Ejemplo n.º 21
0
        public Map Load(string fileName) {
            if (fileName == null) throw new ArgumentNullException("fileName");
            NbtFile file = new NbtFile(fileName);

            NbtCompound mapTag = file.RootTag;

            Map map = new Map(null,
                              mapTag["Width"].ShortValue,
                              mapTag["Length"].ShortValue,
                              mapTag["Height"].ShortValue,
                              false);

            map.Spawn = new Position(mapTag["Spawn"][0].ShortValue,
                                     mapTag["Spawn"][2].ShortValue,
                                     mapTag["Spawn"][1].ShortValue);

            map.Blocks = mapTag["Blocks"].ByteArrayValue;
            map.RemoveUnknownBlockTypes();

            return map;
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Read the information from a file and load it into Node.  The file is expected to hold Minecraft map data in NBT format.
 /// </summary>
 /// <param name="fi">Object that holds File information</param>
 public void GetFileInfo(FileInfo fi)
 {
     NbtFile f = null;
     try
     {
         f = new NbtFile();
         f.LoadFromFile(fi.FullName);
         var dataTag = f.RootTag["data"];
         if (dataTag != null)
         {
             mapLevel = dataTag["scale"] == null ? -1 : dataTag["scale"].ByteValue; ;
             xCenter = dataTag["xCenter"] == null ? -1 : dataTag["xCenter"].IntValue;
             zCenter = dataTag["zCenter"] == null ? -1 : dataTag["zCenter"].IntValue;
         }
         Debug.WriteLine(string.Format("{0} {1}", fi.Name, dataTag["scale"] == null ? -1 : dataTag["scale"].ByteValue));
     }
     catch (Exception ex)
     {
         string s = string.Format("{0} error: {1}", fi.Name, ex.Message);
         throw new Exception(s);
     }
 }
Ejemplo n.º 23
0
        public void Load()
        {
            if(File.Exists("mapfile.nbt")) {
                NbtFile saveFile = new NbtFile("mapfile.nbt");

                NbtCompound root = saveFile.RootTag;
                if(root.Get<NbtString>("fileType").StringValue.Equals("map")) {
                    NbtList aList = root.Get<NbtList>("areas");
                    foreach(NbtCompound alpha in aList) {
                        areas.Add(new Area(alpha));
                    }
                }

                foreach(Portal alpha in Portal.portalsToProcess.Keys) {
                    NbtCompound portDef = Portal.portalsToProcess[alpha];
                    foreach(Area beta in areas) {
                        if(portDef["linkTo"].StringValue.Equals(beta.Name)) {
                            alpha.MakeLink(beta.GetPortal(portDef["linkX"].IntValue, portDef["linkY"].IntValue));
                            break;
                        }
                    }
                }
            }
        }
Ejemplo n.º 24
0
		private byte[] GetNbtData(NbtCompound nbtCompound)
		{
			nbtCompound.Name = string.Empty;
			var file = new NbtFile(nbtCompound);
			file.BigEndian = false;

			return file.SaveToBuffer(NbtCompression.None);
		}
Ejemplo n.º 25
0
 public void ReadPacket(MinecraftStream stream)
 {
     X = stream.ReadInt32();
     Y = stream.ReadInt16();
     Z = stream.ReadInt32();
     Action = stream.ReadUInt8();
     var length = stream.ReadInt16();
     var data = stream.ReadUInt8Array(length);
     Nbt = new NbtFile();
     Nbt.LoadFromBuffer(data, 0, length, NbtCompression.GZip, null);
 }
Ejemplo n.º 26
0
 public UpdateTileEntityPacket(int x, short y, int z,
     byte action, NbtFile nbt)
 {
     X = x;
     Y = y;
     Z = z;
     Action = action;
     Nbt = nbt;
 }
Ejemplo n.º 27
0
 public NetworkMode ReadPacket(MinecraftStream stream, NetworkMode mode, PacketDirection direction)
 {
     X = stream.ReadInt32();
     Y = stream.ReadInt16();
     Z = stream.ReadInt32();
     Action = stream.ReadUInt8();
     var length = stream.ReadInt16();
     var data = stream.ReadUInt8Array(length);
     Nbt = new NbtFile();
     Nbt.LoadFromBuffer(data, 0, length, NbtCompression.GZip, null);
     return mode;
 }
Ejemplo n.º 28
0
        public Map Load(string path) {
            NbtFile file = new NbtFile(path);
            NbtCompound root = file.RootTag;

            int formatVersion = root["FormatVersion"].ByteValue;
            if (formatVersion != 1) {
                throw new MapFormatException("Unsupported format version: " + formatVersion);
            }

            // Read dimensions and create the map
            Map map = new Map(null,
                              root["X"].ShortValue,
                              root["Z"].ShortValue,
                              root["Y"].ShortValue,
                              false);

            // read spawn coordinates
            NbtCompound spawn = (NbtCompound)root["Spawn"];
            map.Spawn = new Position(spawn["X"].ShortValue,
                                     spawn["Z"].ShortValue,
                                     spawn["Y"].ShortValue,
                                     spawn["H"].ByteValue,
                                     spawn["P"].ByteValue);

            // read UUID
            map.Guid = new Guid(root["UUID"].ByteArrayValue);

            // read creation/modification dates of the file (for fallback)
            DateTime fileCreationDate = File.GetCreationTime(path);
            DateTime fileModTime = File.GetCreationTime(path);

            // try to read embedded creation date
            NbtLong creationDate = root.Get<NbtLong>("TimeCreated");
            if (creationDate != null) {
                map.DateCreated = DateTimeUtil.ToDateTime(creationDate.Value);
            } else {
                // for fallback, pick the older of two filesystem dates
                map.DateCreated = (fileModTime > fileCreationDate) ? fileCreationDate : fileModTime;
            }

            // try to read embedded modification date
            NbtLong modTime = root.Get<NbtLong>("LastModified");
            if (modTime != null) {
                map.DateModified = DateTimeUtil.ToDateTime(modTime.Value);
            } else {
                // for fallback, use file modification date
                map.DateModified = fileModTime;
            }

            // TODO: LastAccessed

            // TODO: read CreatedBy and MapGenerator

            // read blocks
            map.Blocks = root["BlockArray"].ByteArrayValue;

            // TODO: CPE CustomBlock conversion

            // read metadata, if present
            NbtCompound metadata = root.Get<NbtCompound>("Metadata");
            if (metadata == null) return map;

            NbtCompound fCraftMetadata = metadata.Get<NbtCompound>("fCraft");
            if (fCraftMetadata != null) {
                foreach (NbtCompound groupTag in fCraftMetadata) {
                    string groupName = groupTag.Name;
                    foreach (NbtString keyValueTag in groupTag) {
                        // ReSharper disable AssignNullToNotNullAttribute // names are never null within compound
                        map.Metadata.Add(groupName, keyValueTag.Name, keyValueTag.Value);
                        // ReSharper restore AssignNullToNotNullAttribute
                    }
                }
            }

            // read CPE settings
            NbtCompound cpeMetadata = metadata.Get<NbtCompound>("CPE");
            if (cpeMetadata != null) {
                // TODO: CPE metadata
            }

            // preserve foreign metadata, if needed
            if (MapUtility.PreserveForeignMetadata) {
                metadata.Remove("fCraft");
                metadata.Remove("CPE");
                map.ForeignMetadata = metadata;
            }

            return map;
        }
Ejemplo n.º 29
0
 public bool Load()
 {
     var path = Path.Combine(Directory.GetCurrentDirectory(), "players", Username + ".nbt");
     if (Program.ServerConfiguration.Singleplayer)
         path = Path.Combine(((World)World).BaseDirectory, "player.nbt");
     if (!File.Exists(path))
         return false;
     try
     {
         var nbt = new NbtFile(path);
         Entity.Position = new Vector3(
             nbt.RootTag["position"][0].DoubleValue,
             nbt.RootTag["position"][1].DoubleValue,
             nbt.RootTag["position"][2].DoubleValue);
         Inventory.SetSlots(((NbtList)nbt.RootTag["inventory"]).Select(t => ItemStack.FromNbt(t as NbtCompound)).ToArray());
         (Entity as PlayerEntity).Health = nbt.RootTag["health"].ShortValue;
         Entity.Yaw = nbt.RootTag["yaw"].FloatValue;
         Entity.Pitch = nbt.RootTag["pitch"].FloatValue;
     }
     catch { /* Who cares */ }
     return true;
 }
Ejemplo n.º 30
0
 public void Save()
 {
     var path = Path.Combine(Directory.GetCurrentDirectory(), "players", Username + ".nbt");
     if (Program.ServerConfiguration.Singleplayer)
         path = Path.Combine(((World)World).BaseDirectory, "player.nbt");
     if (!Directory.Exists(Path.GetDirectoryName(path)))
         Directory.CreateDirectory(Path.GetDirectoryName(path));
     if (Entity == null) // I didn't think this could happen but null reference exceptions have been repoted here
         return;
     var nbt = new NbtFile(new NbtCompound("player", new NbtTag[]
         {
             new NbtString("username", Username),
             new NbtList("position", new[]
             {
                 new NbtDouble(Entity.Position.X),
                 new NbtDouble(Entity.Position.Y),
                 new NbtDouble(Entity.Position.Z)
             }),
             new NbtList("inventory", Inventory.GetSlots().Select(s => s.ToNbt())),
             new NbtShort("health", (Entity as PlayerEntity).Health),
             new NbtFloat("yaw", Entity.Yaw),
             new NbtFloat("pitch", Entity.Pitch),
         }
     ));
     nbt.SaveToFile(path, NbtCompression.ZLib);
 }
Ejemplo n.º 31
0
        // страшная вещь
        static void GetData(string from, string to) {
            // эту функцию не следует вообще смотреть
            // страшный, одноразовый, write-only код, задача которого 1 раз распарсить mca файл и самоуничтожиться
            // однако, последняя функция не сработала, поэтому он всё ещё здесь
            var file = File.ReadAllBytes(from);
            for (var chx = 0; chx < 16; chx++) {
                for (var chz = 0; chz < 24; chz++) {
                    var index = SwapEndian(BitConverter.ToUInt32(file, 4 * (32 * chz + chx)));

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

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

                        if (chz < 16) {
                            continue;
                        }

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

                            }
                        }

                    }

                }
            }

            File.WriteAllBytes(to + "1.bin", chunks);
        }
Ejemplo n.º 32
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);
        }
Ejemplo n.º 33
0
 /// <summary>
 /// Loads a level from the given level.dat file.
 /// </summary>
 public static Level Load(string file)
 {
     if (!Path.IsPathRooted(file))
         file = Path.Combine(Directory.GetCurrentDirectory(), file);
     var serializer = new NbtSerializer(typeof(Level));
     var nbtFile = new NbtFile(file);
     var level = (Level)serializer.Deserialize(nbtFile.RootTag["Data"]);
     level.DatFile = file;
     level.BaseDirectory = Path.GetDirectoryName(file);
     level.WorldGenerator = GetGenerator(level.GeneratorName);
     level.WorldGenerator.Initialize(level);
     var worlds = Directory.GetDirectories(level.BaseDirectory).Where(
         d => Directory.GetFiles(d).Any(f => f.EndsWith(".mca") || f.EndsWith(".mcr")));
     foreach (var world in worlds)
     {
         var w = World.LoadWorld(world);
         w.WorldGenerator = level.WorldGenerator;
         level.AddWorld(w);
     }
     return level;
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Saves this level. This will not work with an in-memory world.
 /// </summary>
 public void Save()
 {
     if (DatFile == null)
         throw new InvalidOperationException("This level exists only in memory. Use Save(string).");
     LastPlayed = DateTime.UtcNow.Ticks;
     var serializer = new NbtSerializer(typeof(Level));
     var tag = serializer.Serialize(this, "Data") as NbtCompound;
     var file = new NbtFile();
     file.RootTag.Add(tag);
     file.SaveToFile(DatFile, NbtCompression.GZip);
     // Save worlds
     foreach (var world in Worlds)
     {
         if (world.BaseDirectory == null)
             world.Save(Path.Combine(BaseDirectory, world.Name));
         else
             world.Save();
     }
 }