dungeon_crawler

view prototype/src/tileset.cc @ 80:a373b36ffc17

better
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 27 Oct 2012 01:59:39 +0300
parents aa9e28670ae2
children
line source
1 #include <stdio.h>
2 #ifndef _MSC_VER
3 #include <alloca.h>
4 #else
5 #include <malloc.h>
6 #endif
7 #include "tileset.h"
8 #include "datapath.h"
10 static char *strip_space(char *ptr);
12 static TileSet *active_tileset;
14 TileSet::TileSet()
15 : texset(load_texture, destroy_texture),
16 sampleset(load_audio_sample, destroy_audio_sample)
17 {
18 }
20 TileSet::~TileSet()
21 {
22 for(auto iter : tiles) {
23 delete iter.second;
24 }
25 }
27 bool TileSet::load(const char *fname)
28 {
29 FILE *fp;
30 if(!(fp = fopen(fname, "r"))) {
31 fprintf(stderr, "failed to open tileset: %s\n", fname);
32 return false;
33 }
34 char *tmp = (char*)alloca(strlen(fname) + 1);
35 strcpy(tmp, fname);
36 fname = tmp;
38 int linenum = 0;
39 char buf[512];
40 while(fgets(buf, sizeof buf, fp)) {
41 linenum++;
43 char *line = strip_space(buf);
44 if(!*line || *line == '#') {
45 continue;
46 }
48 char *tilefile = strchr(line, ':');
49 if(!tilefile) {
50 fprintf(stderr, "error parsing tileset %s, line %d: %s\n", fname,
51 linenum, line);
52 fclose(fp);
53 return false;
54 }
55 *tilefile++ = 0;
57 printf("Tileset %s, loading tile \"%s\" -> %s\n", fname, line, tilefile);
58 Tile *tile = new Tile(this);
59 if(!tile->load(datafile_path(tilefile).c_str())) {
60 fprintf(stderr, "failed to load tile: %s\n", tilefile);
61 delete tile;
62 continue;
63 }
65 tiles[line] = tile;
66 }
68 fclose(fp);
69 return true;
70 }
72 TextureSet *TileSet::get_textures()
73 {
74 return &texset;
75 }
77 const TextureSet *TileSet::get_textures() const
78 {
79 return &texset;
80 }
82 SampleSet *TileSet::get_samples()
83 {
84 return &sampleset;
85 }
87 const SampleSet *TileSet::get_samples() const
88 {
89 return &sampleset;
90 }
92 Tile *TileSet::get_tile(const char *name) const
93 {
94 auto res = tiles.find(name);
95 return res != tiles.end() ? res->second : 0;
96 }
98 void TileSet::update_tiles(unsigned long msec)
99 {
100 for(auto tilepair : tiles) {
101 tilepair.second->update(msec, 0.0f);
102 }
103 }
105 void set_active_tileset(TileSet *set)
106 {
107 active_tileset = set;
108 }
110 TileSet *get_active_tileset()
111 {
112 return active_tileset;
113 }
115 static char *strip_space(char *ptr)
116 {
117 while(isspace(*ptr)) {
118 ptr++;
119 }
121 char *nl = strrchr(ptr, '\n');
122 if(nl) *nl = 0;
123 char *cr = strrchr(ptr, '\r');
124 if(cr) *cr = 0;
126 return ptr;
127 }