fix cr/lfs and remove trailing whitespaces...
[supertux.git] / src / sprite / sprite_manager.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 #include <config.h>
21
22 #include <iostream>
23 #include <sstream>
24 #include <stdexcept>
25
26 #include "sprite_manager.hpp"
27 #include "sprite_data.hpp"
28 #include "sprite.hpp"
29 #include "lisp/lisp.hpp"
30 #include "lisp/parser.hpp"
31 #include "lisp/list_iterator.hpp"
32 #include "file_system.hpp"
33 #include "log.hpp"
34
35 SpriteManager* sprite_manager = NULL;
36
37 SpriteManager::SpriteManager()
38 {
39 }
40
41 SpriteManager::~SpriteManager()
42 {
43   for(Sprites::iterator i = sprites.begin(); i != sprites.end(); ++i) {
44     delete i->second;
45   }
46 }
47
48 Sprite*
49 SpriteManager::create(const std::string& name)
50 {
51   Sprites::iterator i = sprites.find(name);
52   SpriteData* data;
53   if(i == sprites.end()) {
54     // try loading the spritefile
55     data = load(name);
56     if(data == NULL) {
57       std::stringstream msg;
58       msg << "Sprite '" << name << "' not found.";
59       throw std::runtime_error(msg.str());
60     }
61   } else {
62     data = i->second;
63   }
64
65   return new Sprite(*data);
66 }
67
68 SpriteData*
69 SpriteManager::load(const std::string& filename)
70 {
71   lisp::Parser parser;
72   std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
73
74   const lisp::Lisp* sprite = root->get_lisp("supertux-sprite");
75   if(!sprite) {
76     std::ostringstream msg;
77     msg << "'" << filename << "' is not a supertux-sprite file";
78     throw std::runtime_error(msg.str());
79   }
80
81   std::auto_ptr<SpriteData> data (
82       new SpriteData(sprite, FileSystem::dirname(filename)) );
83   sprites[filename] = data.release();
84
85   return sprites[filename];
86 }