Building a Command Line Tool to View Minecraft Data


This week''s post will focus on creating a command line tool to view Minecraft NBT files. You will be taught:



Named Binary Tag (NBT), files store details about Minecraft using a basic binary file format. To know more about the details of the NBT format read these documents:



"NBT format" via Minecraft Wiki. "NBT" via Minecraft.vg. "Named Binary Tag specification” via Minecraft.net (WebArchive).



Script source code



view-nbt



Utilize the script to see an NBT-file



I have an NBT file, level.dat, that contains information about the Minecraft level that I play on:



To see the data in a readable format I use view-nbt.



(level.dat files can be compressed so I use --gzip.



How the script works



NBT files are tagged with many different kinds so I chose to use an enum.Enum, Tag, to represent the tags.



To aid in the parsing process, I created several auxiliary data structures:



Scalar_fmt is a method to map certain Tag objects to form strings that can be used by struct module. This is intended to be used for "simple" tags, such as Tag.Int or Tag.Byte. array_fmt is an array which maps some Tag objects into format strings that can be used by the struct module (but missing a length prefix). This is for simple array tags, such as Tag.Int_Array. The dictionary byte_tag maps bytes to the appropriate tags. This information was drawn from the NBT file format specification.



The parser makes use of the struct module in order to break up binary data into various numbers (like int double, int).



The parser is recursive.



It directly parses Tag.String and the tags in scalar_fmt as well as array_fmt. It parses Tag.List, Tag.Compound recursively.



The parsing creates a Node object, which is a collections.namedtuple that holds:



- The tag type. Optional: The name of the tag. The value of the tag.



To improve the readability of the data I have a function called json_friendly, that turns Node objects into data structures which, to my mind will make the JSON easier to read.



I employ Python''s gzip module to offer support for compressed NBT files.
Alusky''s Blog



To convert the JSON-friendly data into a string I use JSON function from Python.



Let''s close...



This week''s post will show you how to create a command-line tool to examine Minecraft NBT files. What you learned:



- How to unpack binary data using the struct module. - How to write a recursive parser that works with the NBT file format. How to transform the parsed data into JSON-friendly file format



My challenge to you is:



Create a tool, view-region which converts Region files into JSON that is readable.



If you enjoyed this week''s post, please share it with your friends and keep an eye out for the next post. We''ll see you next week!