view src/xmlmap.d @ 3:a9af6ec19195

working map and tileset loading
author fred@reichbier.de
date Thu, 17 Jul 2008 21:34:53 +0200
parents fc2f936a961c
children
line wrap: on
line source

module xmlmap;

import tileset;
import tilemap;

import tango.text.xml.Document;
import tango.text.convert.Integer;
import tango.io.Stdout; // TODO
import tools;
import imagecache;
import dsfml.system.all;
import Text = tango.text.Util;


alias XmlPath!(char).NodeSet NodeSet;
alias Document!(char).Node NodeImpl;
private char[] get_attribute(NodeSet node, char[] name) {
    return node.attribute(name).nodes[0].value;
}

Tileset parse_tileset(Cache cache, char[] content) {
    auto tileset = new Tileset(cache);

    auto doc = new Document!(char);
    doc.parse(content);
    auto root = doc.query["tileset"];   
    auto nodes = root.child.nodes;
    foreach(NodeImpl tiles_node; nodes) {
	tileset.add_tile(Integer.parse(tiles_node.getAttribute("id").value), tiles_node.getAttribute("filename").value);
    }
    return tileset;
}

Tilemap parse_map(Cache cache, char[] content) {
    auto doc = new Document!(char);
    doc.parse(content);
    auto root = doc.query["map"];
    int width = Integer.parse(get_attribute(root, "width"));
    int height = Integer.parse(get_attribute(root, "height"));
    Stdout.formatln("Width: {}, Height: {}", width, height);
    auto tiles_node = root.child.nodes[0];
    char[] tileset_file = tiles_node.getAttribute("tileset").value;
    auto tilemap = new Tilemap(parse_tileset(cache, read_file_contents(tileset_file)), width, height, 32, 32); // TODO: variable tile size
    int layer_id=0;
    foreach(NodeImpl layer_node; tiles_node.query["layer"].nodes) {
	int tile_width = Integer.parse(layer_node.getAttribute("tilewidth").value);
	int tile_height = Integer.parse(layer_node.getAttribute("tileheight").value);
	tilemap.layer_tsizes[layer_id] = Vector2i(tile_width, tile_height);
	char[][] content_ = Text.delimit(Text.trim(layer_node.value), ",");
	int i=0;
	for(int x=0; x < width; x++) {
	    for(int y=0; y < height; y++) {
		tilemap.map[layer_id][x][y] = Integer.parse(content_[i]);
		i++;
	    }
	}
	layer_id++;
    }
    return tilemap;
}