/// <summary> /// Saves a <see cref="Map"/> object to disk as a standard compressed NBT stream. /// </summary> /// <returns>True if the map was saved; false otherwise.</returns> /// <exception cref="Exception">Thrown when an error is encountered writing out the level.</exception> public bool Save() { if (_world == null) { return(false); } try { string path = Path.Combine(_world.Path, _world.DataDirectory); NBTFile nf = new NBTFile(Path.Combine(path, "map_" + _id + ".dat")); Stream zipstr = nf.GetDataOutputStream(); if (zipstr == null) { NbtIOException nex = new NbtIOException("Failed to initialize compressed NBT stream for output"); nex.Data["Map"] = this; throw nex; } new NbtTree(BuildTree() as TagNodeCompound).WriteTo(zipstr); zipstr.Close(); return(true); } catch (Exception ex) { Exception mex = new Exception("Could not save map file.", ex); // TODO: Exception Type mex.Data["Map"] = this; throw mex; } }
public override bool Save() { if (_world == null) { return(false); } try { string path = Path.Combine(_world.Path, _world.DataDirectory); NBTFile nf = new NBTFile(Path.Combine(path, "idcounts.dat")); using (Stream zipstr = nf.GetDataOutputStream(CompressionType.None)) { if (zipstr == null) { NbtIOException nex = new NbtIOException("Failed to initialize uncompressed NBT stream for output"); nex.Data["DataManager"] = this; throw nex; } new NbtTree(BuildTree() as TagNodeCompound).WriteTo(zipstr); } return(true); } catch (Exception ex) { Exception lex = new Exception("Could not save idcounts.dat file.", ex); lex.Data["DataManager"] = this; throw lex; } }
public static bool SetBlock(this IBlockAccess world, int x, int y, int z, string blockName, params string[] args) { IBlock block = GameData.JavaEdition.GetBlock(blockName); if (args == null || args.Length == 0) { return(world.SetBlock(x, y, z, block.DefaultBlockSet)); } if (args.Length == 1) { TagCompound tag = NBTFile.FromJson(args[0]); return(world.SetBlock(x, y, z, new BlockSet(block, tag))); } else if ((args.Length & 1) == 0) { Dictionary <string, string> ps1 = PropertyConverter.From(args); foreach (string key in block.DefaultBlockSet.Properties.Keys) { if (!ps1.ContainsKey(key)) { ps1.Add(key, block.DefaultBlockSet.Properties[key]); } } return(world.SetBlock(x, y, z, new BlockSet(block, ps1))); } return(world.SetBlock(x, y, z, block.DefaultBlockSet)); }
/// <summary> /// Saves a <see cref="Level"/> object to disk as a standard compressed NBT stream. /// </summary> /// <returns>True if the level was saved; false otherwise.</returns> /// <exception cref="LevelIOException">Thrown when an error is encountered writing out the level.</exception> public bool Save() { if (_world == null) { return(false); } try { NBTFile nf = new NBTFile(Path.Combine(_world.Path, "level.dat")); using (Stream zipstr = nf.GetDataOutputStream()) { if (zipstr == null) { NbtIOException nex = new NbtIOException("Failed to initialize compressed NBT stream for output"); nex.Data["Level"] = this; throw nex; } new NbtTree(BuildTree() as TagNodeCompound).WriteTo(zipstr); } return(true); } catch (Exception ex) { LevelIOException lex = new LevelIOException("Could not save level file.", ex); lex.Data["Level"] = this; throw lex; } }
public static NbtMap Load(string filename) { var map = new NbtMap(); var nf = new NBTFile(filename); using (var nbtstr = nf.GetDataInputStream()) { var tree = new NbtTree(nbtstr); var root = tree.Root["map"]; var list = root.ToTagList(); foreach (var tag in list) { var k = tag.ToTagCompound()["k"].ToTagString(); var v = (short)tag.ToTagCompound()["v"].ToTagInt(); if (!map.ContainsKey(v)) { map.Add(v, k); } } return(map); } }
protected override void ExpandCore() { if (_tree == null) { NBTFile file = new NBTFile(_path); _tree = new NbtTree(); _tree.ReadFrom(file.GetDataInputStream(_compressionType)); if (_tree.Root != null) { _container = new CompoundTagContainer(_tree.Root); } } var list = new SortedList <TagKey, TagNode>(); foreach (var item in _tree.Root) { list.Add(new TagKey(item.Key, item.Value.GetTagType()), item.Value); } foreach (TagNode tag in list.Values) { TagDataNode node = TagDataNode.CreateFromTag(tag); if (node != null) { Nodes.Add(node); } } }
protected override void SaveCore() { var file = new NBTFile(_path); using (var str = file.GetDataOutputStream(_compressionType)) { _tree.WriteTo(str); } }
internal void SaveChunk(AnvilChunk chunk) { RegionFile f = FetchRegion(chunk.Coord.RegionCoord); TagCompound chunkTag = chunk.BuildTag(); using (Stream stream = f.WriteChunk(new ChunkCoord(chunk.Coord.X & 31, chunk.Coord.Z & 31))) { NBTFile.ToStream(stream, chunkTag); } }
public static TagNodeCompound GetLevelDat() { if (levelDat == null) { string path = Path.Combine(savePath, "level.dat"); levelFile = new NBTFile(path); levelTree = new NbtTree(); levelTree.ReadFrom(levelFile.GetDataInputStream()); levelDat = levelTree.Root["Data"] as TagNodeCompound; } return(levelDat); }
public static World Load(string filename) { var nf = new NBTFile(filename); using var nbtstr = nf.GetDataInputStream(); var tree = new NbtTree(nbtstr); var root = tree.Root["Data"].ToTagCompound(); var dataVersion = root["DataVersion"].ToTagInt().Data; return(new World(filename, dataVersion)); }
/// <summary> /// 从文件Ian /// </summary> /// <returns></returns> public static List <string> LoadServerUrlFromFile() { List <string> urls = new List <string>(); //获取newgui中的地址 try { var newGuiFile = ".minecraft/config/New Gui.cfg"; if (File.Exists(newGuiFile)) { using (FileStream fs = new FileStream(newGuiFile, FileMode.Open)) { using (StreamReader sr = new StreamReader(fs)) { string line = sr.ReadLine(); while (line != null) { if (line.Contains("S:Address1=")) { urls.Add(line.Replace("S:Address1=", "").Trim()); } if (line.Contains("S:Address2=")) { urls.Add(line.Replace("S:Address2=", "").Trim()); } line = sr.ReadLine(); } } } } } catch { } //获取server.data文件中的地址 try { string serverFilePath = ".minecraft/servers.dat"; if (File.Exists(serverFilePath)) { TagCompound tags = NBTFile.FromFile(serverFilePath); TagList servers = (TagList)tags["servers"]; foreach (TagCompound server in servers) { urls.Add(((TagString)server["ip"]).Value); } } } catch { } return(urls); }
/// <summary> /// 从nbt数据中获取salt /// </summary> /// <param name="data"></param> /// <param name="is112">是否是1.12版本, 如果是, 那么只需要处理一位数字</param> /// <returns></returns> public static string GetSaltFromNBTByteArray(byte[] data, bool is112) { MemoryStream ms = new MemoryStream(removeLength(data, is112)); TagCompound tag = NBTFile.FromStream(ms); byte[] saltarr = tag.GetByteArray("salt"); string salt = System.Text.Encoding.UTF8.GetString(saltarr); if (saltarr.Length > 100) { salt = ASACUtil.RSADecodeSalt(saltarr); } return(salt); }
private bool LoadLevel () { NBTFile nf = new NBTFile(IO.Path.Combine(Path, _levelFile)); Stream nbtstr = nf.GetDataInputStream(); if (nbtstr == null) { return false; } NbtTree tree = new NbtTree(nbtstr); _level = new Level(this); _level = _level.LoadTreeSafe(tree.Root); return _level != null; }
/// <summary> /// パスからフォルダを再帰的に読み込み、ツリーを生成 /// </summary> /// <param name="path">ファイルパス</param> /// <param name="node">ノード</param> /// <returns></returns> private static TreeNode RecursiveLoad(string path, TreeNode node = null) { var addNode = new TreeNode(); addNode.Text.Value = Path.GetFileName(path); // ディレクトリならそのまま再帰読込 // それ以外ならNBTファイルとして読込を試みる if (File.GetAttributes(path).HasFlag(FileAttributes.Directory)) { addNode.Icon.Value = "/Assets/Icons/Folder.png"; try { foreach (var child in Directory.GetFileSystemEntries(path)) { RecursiveLoad(child, addNode); } } catch (DirectoryNotFoundException) { } } else { try { var tag = NBTFile.FromFile(path); addNode.Icon.Value = "/Assets/Icons/Container.png"; addNode.Text.Value += $" [{tag.Count} entries]"; foreach (var child in tag) { addNode.Add(AddTag(child)); } } catch { // 例外を吐いた=NBTファイルではないという安直な考え return(node); } } if (node == null && !string.IsNullOrEmpty(addNode.Icon.Value)) { return(addNode); } node.Add(addNode); return(node); }
/// <inheritdoc /> public Structure Load(string filename) { var input = new NBTFile(filename); var nbt = new NbtTree(input.GetDataInputStream()).Root; var length = nbt["Length"].ToTagInt().Data; var width = nbt["Width"].ToTagInt().Data; var height = nbt["Height"].ToTagInt().Data; var palette = LoadPalette(nbt); var tiles = LoadTileEntities(nbt); var blocks = LoadBlocks(nbt, palette, length, width, tiles); var entities = LoadEntities(nbt); return(new SchematicStructure(blocks, entities, palette, width, height, length)); }
/// <summary> /// 保存ボタンクリックイベント /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void toolStrip_Save_Click(object sender, EventArgs e) { try { if (treeView1.Nodes.Count > 0) { var tag = (TagCompound)treeView1.Nodes[0].Tag; NBTFile.ToFile(Common.OpenFilePath, tag); } } catch (Exception ex) { MessageBox.Show("ファイルの保存に失敗しました\n" + ex.Message, "OrangeNBTEditor", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static FabricRegistry Load(string filename) { var nf = new NBTFile(filename); using var nbtstr = nf.GetDataInputStream(); var tree = new NbtTree(nbtstr); var version = tree.Root["version"].ToTagInt().Data; var registries = tree.Root["registries"].ToTagCompound(); var blockMap = CreateMap(registries["minecraft:block"]); var blockEntityTypeMap = CreateMap(registries["minecraft:block_entity_type"]); var itemMap = CreateMap(registries["minecraft:item"]); return(new FabricRegistry(version, blockMap, blockEntityTypeMap, itemMap)); }
public WorldData(string WorldPath) { _LoadedMods = new List <string>(); BlockIDs = new Dictionary <string, int>(); NBTFile LevelFile = new NBTFile(Path.Combine(WorldPath, "level.dat")); NbtTree LevelTree; using (Stream nbtstr = LevelFile.GetDataInputStream()) { LevelTree = new NbtTree(nbtstr); } _LoadedMods.Add("minecraft"); if (LevelTree.Root.ContainsKey("FML")) { TagNodeList IDList = (TagNodeList)(((TagNodeCompound)LevelTree.Root["FML"])["ItemData"]); TagNodeList ModList = (TagNodeList)(((TagNodeCompound)LevelTree.Root["FML"])["ModList"]); foreach (TagNodeCompound Entry in IDList) { string Key = ((TagNodeString)Entry["K"]).Data.Trim(' ', '', ''); // Non-visible control characters in those last two entries int Value = ((TagNodeInt)Entry["v"]).Data; BlockIDs.Add(Key, Value); } foreach (TagNodeCompound Entry in ModList) { _LoadedMods.Add(((TagNodeString)Entry["ModId"]).Data); } } else { // Load default vanilla stuff here StreamReader TR = new StreamReader(Properties.Resources.BaseIDs); string[] Line; while (!TR.EndOfStream) { Line = TR.ReadLine().Split(' '); BlockIDs.Add(Line[1], int.Parse(Line[0])); } } }
NbtTree LoadLevelTree(string path) { NBTFile nf = new NBTFile(path); NbtTree tree = null; using (Stream nbtstr = nf.GetDataInputStream()) { if (nbtstr == null) { return(null); } tree = new NbtTree(nbtstr); } return(tree); }
public NBTTagCompound ImageConvert(Bitmap bmp, bool IsSchematic, ref BackgroundWorker bw) { var schema = new SilverNBTLibrary.Structure.Schematic(bmp.Width, 1, bmp.Height); var mapbyte = new byte[16384]; var compound = new NBTTagCompound(); int i = 0; using (BitmapAccessor accessor = new BitmapAccessor(bmp)) { for (int y = 0; y < bmp.Height; y++) { for (int x = 0; x < bmp.Width; x++) { Color bitmapRGB = accessor.GetPixel(x, y); var block = IsSchematic ? RGBToBlockColor(bitmapRGB) : RGBToMapColor(bitmapRGB); if (IsSchematic) { schema.SetBlock(x, 0, y, block.ID, block.Meta); } else { mapbyte[i] = (byte)block.ID; i++; } } bw.ReportProgress(y); } } if (IsSchematic) { compound = schema.SaveToNBT(); } else { var map = new NBTTagByteArray("colors", mapbyte); compound = NBTFile.LoadFromFile(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\data\MapTemplate.dat"); var data = (NBTTagCompound)compound.GetTag("data"); data.Add(map); } bmp.Dispose(); return(compound); }
static void Main(string[] args) { Console.WriteLine("ワールドのフォルダのパスを入力して下さい"); Console.WriteLine("Windows10の場合はここにワールドのフォルダをドラッグ&ドロップすると楽です"); string folderPath = Console.ReadLine(); Console.WriteLine("ワールドの読み込みを開始します"); Console.WriteLine(); var sb = new StringBuilder(); sb.Append("X,Y,Z,ディメンションID,タイルエンティティID\n"); using (World world = World.FromDirectory(folderPath)) { foreach (var dim in world.Worlds) { var tileEntities = dim.GetAllTileEntities(); foreach (var tileEntity in tileEntities) { var nbt = tileEntity.NBTData; if (nbt.ContainsKey("Items") || nbt.ContainsKey("RecordItem")) { sb.AppendFormat("{0},{1},{2},{3},{4}\n", tileEntity.XCoord, tileEntity.YCoord, tileEntity.ZCoord, dim.DimensionID, tileEntity.Id); Console.WriteLine(NBTFile.ToJson(tileEntity.NBTData)); } } } } Console.WriteLine(); Console.WriteLine("全てのタイルエンティティの検査が終了しました"); Console.WriteLine("CSV形式のテキストファイルに出力します"); string file = Path.Combine(Directory.GetCurrentDirectory(), "result.txt"); System.IO.File.WriteAllText(file, sb.ToString(), System.Text.Encoding.UTF8); Console.WriteLine(file + "に出力しました"); Console.WriteLine("終了するにはなにかキーを押して下さい"); Console.ReadKey(); }
/// <summary> /// 判断是否需要rsa加密 /// 只有1.0.6及以下需要 /// </summary> /// <param name="md5Data"></param> /// <returns></returns> public static bool IsNeedRSA(byte[] md5Data, bool is112) { bool isRsa = false; MemoryStream ms = new MemoryStream(removeLength(md5Data, is112)); TagCompound tag = NBTFile.FromStream(ms); TagList taglist = (TagList)tag["md5s"]; foreach (TagByteArray br in taglist) { byte[] bytes = br.Value; if (bytes.Length > 100) { isRsa = true; break; } } return(isRsa); }
private static NbtFileDataNode TryCreateFrom(string path, CompressionType compressionType) { try { var file = new NBTFile(path); var tree = new NbtTree(); tree.ReadFrom(file.GetDataInputStream(compressionType)); if (tree.Root == null) return null; return new NbtFileDataNode(path, compressionType); } catch { return null; } }
/// <summary> /// NBTファイルを開く /// </summary> /// <param name="filePath"></param> public void FileOpen(string filePath) { treeView1.Nodes.Clear(); try { var tag = NBTFile.FromFile(filePath); var node = new TreeNode(); AddTag(tag, node); node.Nodes[0].Text = Path.GetFileName(filePath) ?? throw new InvalidOperationException(); treeView1.Nodes.Add(node.Nodes[0]); treeView1.Sort(); } catch (Exception ex) { MessageBox.Show("サポートされているファイルではありません\n" + ex.Message, "OrangeNBTEditor", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void btnNew_Click(object sender, EventArgs e) { saveFileDialog1.AddExtension = true; saveFileDialog1.DefaultExt = "nbt"; DialogResult dr = saveFileDialog1.ShowDialog(); if (dr == DialogResult.OK) { NBTFile nbtfile = new NBTFile(); path = saveFileDialog1.FileName; nbtfile.Compression = NBT.IO.Compression.NBTCompressionType.Uncompressed; nbtfile.RootTagName = "File Store"; nbtfile.RootTag.Add("CompressionType", new TagString("Uncompressed")); nbtfile.Save(path); tb_path.Text = path; btn_select.Enabled = true; } }
/// <inheritdoc /> public Structure Load(string filename) { var input = new NBTFile(filename); var nbt = new NbtTree(input.GetDataInputStream()).Root; var dataVersion = nbt["DataVersion"].ToTagInt().Data; var author = nbt.ContainsKey("author") ? nbt["author"].ToTagString().Data : null; var size = nbt["size"].ToTagList().Select(node => node.ToTagInt().Data).ToArray(); var width = size[0]; var height = size[1]; var length = size[2]; var palette = LoadPalette(nbt); var blocks = LoadBlocks(nbt, palette); var entities = LoadEntities(nbt); return(new StructureBlockStructure(author, width, height, length, blocks, entities)); }
private AnvilChunk LoadChunk(ChunkCoord coord) { RegionFile f = FetchRegion(coord.RegionCoord); TagCompound chunkTag = null; using (Stream stream = f.ReadChunk(new ChunkCoord(coord.X & 31, coord.Z & 31))) { if (stream != null) { chunkTag = NBTFile.FromStream(stream, false); } } if (chunkTag == null) { return(null); } return(AnvilChunkImproved.Load(this, chunkTag)); }
private bool LoadLevel() { NBTFile nf = new NBTFile(IO.Path.Combine(Path, _levelFile)); NbtTree tree; using (Stream nbtstr = nf.GetDataInputStream()) { if (nbtstr == null) { return(false); } tree = new NbtTree(nbtstr); } _level = new Level(this); _level = _level.LoadTreeSafe(tree.Root); return(_level != null); }
public MinecraftServer(IPAddress address, int port) : base(address, port) { using (Stream stream = RMSManager.Get().GetStream(Properties.Resources.dimension_codec)) { DimensionCodec = new NBTFile().Read(stream); } using (Stream stream = RMSManager.Get().GetStream(Properties.Resources.overworld)) { OverworldDimension = new NBTFile().Read(stream); } using (Stream stream = RMSManager.Get().GetStream(Properties.Resources.nether)) { NetherDimension = new NBTFile().Read(stream); } using (Stream stream = RMSManager.Get().GetStream(Properties.Resources.the_end)) { TheEndDimension = new NBTFile().Read(stream); } Configuration = new ServerConfiguration { ViewDistance = 12, CompressionThreshold = 128, OnlineMode = false }; Http = new System.Net.Http.HttpClient(); #region encryption RsaKeyPairGenerator rsa = new(); rsa.Init(new KeyGenerationParameters(new SecureRandom(), 1024)); KeyPair = rsa.GenerateKeyPair(); Decryptor = new Pkcs1Encoding(new RsaEngine()); Decryptor.Init(false, KeyPair.Private); Encryptor = new Pkcs1Encoding(new RsaEngine()); Encryptor.Init(true, KeyPair.Public); #endregion World = new World(this, "world", new FlatWorldGenerator()); }
public void ToSchematic(string file) { var loadtag = NBTFile.LoadFromFile(file); var structure = SilverNBTLibrary.Structure.StructureTemplate.LoadFromNBT(loadtag); var schema = new SilverNBTLibrary.Structure.Schematic(structure.Width, structure.Height, structure.Length); form.Invoke((MethodInvoker) delegate() { pgb.Maximum = structure.Width * structure.Height * structure.Length; pgb.Value = 0; }); for (int x = 0; x < structure.Width; x++) { for (int y = 0; y < structure.Height; y++) { for (int z = 0; z < structure.Length; z++) { var id = structure.GetBlockId(x, y, z); var meta = structure.GetBlockMetadata(x, y, z); schema.SetBlock(x, y, z, id, meta); var te = structure.GetTileEntityTag(x, y, z); if (te != null) { schema.AddTileEntityTag(x, y, z, te); } form.Invoke((MethodInvoker) delegate() { pgb.Value++; }); } } } foreach (NBTTagCompound entity in structure.Entities) { schema.Entities.Add(entity); } var nbt = schema.SaveToNBT(); NBTFile.SaveToFile(Path.GetDirectoryName(file) + @"\" + Path.GetFileNameWithoutExtension(file) + ".schematic", nbt); }