Serializable::inspect
to show more useful information
serialization :: serialization_core
Abstract services to serialize Nit objects to different formatscore :: union_find
union–find algorithm using an efficient disjoint-set data structure
# Tool to parse XML texture atlas and generated Nit code to access subtextures
module texture_atlas_parser
import dom
import gen_nit
import opts
# Command line options
var opts = new OptionContext
var opt_name = new OptionString("Name of the module to generate", "--name", "-n")
var opt_dir = new OptionString("Folder where to write the generated module", "--dir")
opts.add_option(opt_name, opt_dir)
opts.parse
var rest = opts.rest
if opts.errors.not_empty then
print_error opts.errors
exit 1
end
if rest.is_empty then
print_error "Error: Expected the path to the XML file as argument"
exit 2
end
# Prepare to read XML file and gather the attributes
var xml_file = rest.first
var attributes = new Array[String]
# Insert the first attribute, to load the root texture
var png_file = "images" / xml_file.basename("xml") + "png"
attributes.add """
var root_texture = new TextureAsset("{{{png_file}}}")"""
# Read XML file
var content = xml_file.to_path.read_all
var xml = content.to_xml
if xml isa XMLError then
print_error "RSS Parse Error: {xml.message}:{xml.location or else "null"}"
exit 3
end
var items = xml["TextureAtlas"].first.children
for item in items do if item isa XMLOnelinerTag then
var x = null
var y = null
var width = null
var height = null
var name = null
for attr in item.attributes do if attr isa XMLStringAttr then
if attr.name == "x" then
x = attr.value.to_i
else if attr.name == "y" then
y = attr.value.to_i
else if attr.name == "width" then
width = attr.value.to_i
else if attr.name == "height" then
height = attr.value.to_i
else if attr.name == "name" then
name = attr.value
end
end
if x != null and y != null and width != null and height != null and name != null then
name = name.strip_extension(".png").to_snake_case
var coords = "{x}, {y}, {width}, {height}"
attributes.add """
var {{{name}}}: Texture = root_texture.subtexture({{{coords}}})"""
else
print_error "Error on {item}"
end
end
var module_name = opt_name.value
if module_name == null then module_name = "spritesheet"
var class_name = module_name.capitalized.to_camel_case
# Generate Nit code
var nit_module = new NitModule(module_name)
nit_module.header = """
# This file is generated by texture_atlas_parser
"""
nit_module.content.add """
import gamnit::display
import gamnit::textures
class {{{class_name}}}
"""
for a in attributes do nit_module.content.add a
nit_module.content.add """
end"""
var dir = opt_dir.value
if dir != null then
var out_path = dir / module_name + ".nit"
nit_module.write_to_file out_path
else
printn nit_module.write_to_string
end
lib/gamnit/texture_atlas_parser.nit:15,1--117,3