Fix for coverity #29401
[supertux.git] / src / object / tilemap.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //
4 //  This program is free software: you can redistribute it and/or modify
5 //  it under the terms of the GNU General Public License as published by
6 //  the Free Software Foundation, either version 3 of the License, or
7 //  (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 #include <math.h>
18
19 #include "object/tilemap.hpp"
20 #include "scripting/squirrel_util.hpp"
21 #include "scripting/tilemap.hpp"
22 #include "supertux/globals.hpp"
23 #include "supertux/object_factory.hpp"
24 #include "supertux/tile_manager.hpp"
25 #include "supertux/tile_set.hpp"
26 #include "util/reader.hpp"
27
28 TileMap::TileMap(const TileSet *new_tileset) :
29   tileset(new_tileset),
30   tiles(),
31   real_solid(false),
32   effective_solid(false),
33   speed_x(1),
34   speed_y(1),
35   width(0),
36   height(0),
37   z_pos(0),
38   offset(Vector(0,0)),
39   movement(0,0),
40   drawing_effect(NO_EFFECT),
41   alpha(1.0),
42   current_alpha(1.0),
43   remaining_fade_time(0),
44   path(),
45   walker(),
46   draw_target(DrawingContext::NORMAL)
47 {
48 }
49
50 TileMap::TileMap(const Reader& reader) :
51   tileset(),
52   tiles(),
53   real_solid(false),
54   effective_solid(false),
55   speed_x(1),
56   speed_y(1),
57   width(-1),
58   height(-1),
59   z_pos(0),
60   offset(Vector(0,0)),
61   movement(Vector(0,0)),
62   drawing_effect(NO_EFFECT),
63   alpha(1.0),
64   current_alpha(1.0),
65   remaining_fade_time(0),
66   path(),
67   walker(),
68   draw_target(DrawingContext::NORMAL)
69 {
70   tileset = current_tileset;
71   assert(tileset != NULL);
72
73   reader.get("name",   name);
74   reader.get("solid",  real_solid);
75   reader.get("speed",  speed_x);
76   reader.get("speed-y", speed_y);
77
78   z_pos = reader_get_layer (reader, /* default = */ 0);
79
80   if(real_solid && ((speed_x != 1) || (speed_y != 1))) {
81     log_warning << "Speed of solid tilemap is not 1. fixing" << std::endl;
82     speed_x = 1;
83     speed_y = 1;
84   }
85
86   const lisp::Lisp* pathLisp = reader.get_lisp("path");
87   if (pathLisp) {
88     path.reset(new Path());
89     path->read(*pathLisp);
90     walker.reset(new PathWalker(path.get(), /*running*/false));
91     Vector v = path->get_base();
92     set_offset(v);
93   }
94
95   std::string draw_target_s = "normal";
96   reader.get("draw-target", draw_target_s);
97   if (draw_target_s == "normal") draw_target = DrawingContext::NORMAL;
98   if (draw_target_s == "lightmap") draw_target = DrawingContext::LIGHTMAP;
99
100   if (reader.get("alpha", alpha)) {
101     current_alpha = alpha;
102   }
103
104   /* Initialize effective_solid based on real_solid and current_alpha. */
105   effective_solid = real_solid;
106   update_effective_solid ();
107
108   reader.get("width", width);
109   reader.get("height", height);
110   if(width < 0 || height < 0)
111     throw std::runtime_error("Invalid/No width/height specified in tilemap.");
112
113   if(!reader.get("tiles", tiles))
114     throw std::runtime_error("No tiles in tilemap.");
115
116   if(int(tiles.size()) != width*height) {
117     throw std::runtime_error("wrong number of tiles in tilemap.");
118   }
119
120   bool empty = true;
121
122   // make sure all tiles used on the tilemap are loaded and tilemap isn't empty
123   for(Tiles::iterator i = tiles.begin(); i != tiles.end(); ++i) {
124     if(*i != 0) {
125       empty = false;
126     }
127
128     tileset->get(*i);
129   }
130
131   if(empty)
132   {
133     log_info << "Tilemap '" << name << "', z-pos '" << z_pos << "' is empty." << std::endl;
134   }
135 }
136
137 TileMap::TileMap(const TileSet *new_tileset, std::string name_, int z_pos_,
138                  bool solid, size_t width_, size_t height_) :
139   tileset(new_tileset),
140   tiles(),
141   real_solid(solid),
142   effective_solid(solid),
143   speed_x(1),
144   speed_y(1),
145   width(0),
146   height(0),
147   z_pos(z_pos_),
148   offset(Vector(0,0)),
149   movement(Vector(0,0)),
150   drawing_effect(NO_EFFECT),
151   alpha(1.0),
152   current_alpha(1.0),
153   remaining_fade_time(0),
154   path(),
155   walker(),
156   draw_target(DrawingContext::NORMAL)
157 {
158   this->name = name_;
159
160   if (this->z_pos > (LAYER_GUI - 100))
161     this->z_pos = LAYER_GUI - 100;
162
163   resize(width_, height_);
164 }
165
166 TileMap::~TileMap()
167 {
168 }
169
170 void
171 TileMap::update(float elapsed_time)
172 {
173   // handle tilemap fading
174   if (current_alpha != alpha) {
175     remaining_fade_time = std::max(0.0f, remaining_fade_time - elapsed_time);
176     if (remaining_fade_time == 0.0f) {
177       current_alpha = alpha;
178     } else {
179       float amt = (alpha - current_alpha) / (remaining_fade_time / elapsed_time);
180       if (amt > 0) current_alpha = std::min(current_alpha + amt, alpha);
181       if (amt < 0) current_alpha = std::max(current_alpha + amt, alpha);
182     }
183     update_effective_solid ();
184   }
185
186   movement = Vector(0,0);
187   // if we have a path to follow, follow it
188   if (walker.get()) {
189     Vector v = walker->advance(elapsed_time);
190     movement = v - get_offset();
191     set_offset(v);
192   }
193 }
194
195 void
196 TileMap::draw(DrawingContext& context)
197 {
198   // skip draw if current opacity is 0.0
199   if (current_alpha == 0.0) return;
200
201   context.push_transform();
202   if(draw_target != DrawingContext::NORMAL) {
203     context.push_target();
204     context.set_target(draw_target);
205   }
206
207   if(drawing_effect != 0) context.set_drawing_effect(drawing_effect);
208   if(current_alpha != 1.0) context.set_alpha(current_alpha);
209
210   /* Force the translation to be an integer so that the tiles appear sharper.
211    * For consistency (i.e., to avoid 1-pixel gaps), this needs to be done even
212    * for solid tilemaps that are guaranteed to have speed 1.
213    * FIXME Force integer translation for all graphics, not just tilemaps. */
214   float trans_x = roundf(context.get_translation().x);
215   float trans_y = roundf(context.get_translation().y);
216   context.set_translation(Vector(int(trans_x * speed_x),
217                                  int(trans_y * speed_y)));
218
219   Rectf draw_rect = Rectf(context.get_translation(),
220         context.get_translation() + Vector(SCREEN_WIDTH, SCREEN_HEIGHT));
221   Rect t_draw_rect = get_tiles_overlapping(draw_rect);
222   Vector start = get_tile_position(t_draw_rect.left, t_draw_rect.top);
223
224   Vector pos;
225   int tx, ty;
226
227   for(pos.x = start.x, tx = t_draw_rect.left; tx < t_draw_rect.right; pos.x += 32, ++tx) {
228     for(pos.y = start.y, ty = t_draw_rect.top; ty < t_draw_rect.bottom; pos.y += 32, ++ty) {
229       int index = ty*width + tx;
230       assert (index >= 0);
231       assert (index < (width * height));
232
233       if (tiles[index] == 0) continue;
234       const Tile* tile = tileset->get(tiles[index]);
235       assert(tile != 0);
236       tile->draw(context, pos, z_pos);
237     } /* for (pos y) */
238   } /* for (pos x) */
239
240   if(draw_target != DrawingContext::NORMAL) {
241     context.pop_target();
242   }
243   context.pop_transform();
244 }
245
246 void
247 TileMap::goto_node(int node_no)
248 {
249   if (!walker.get()) return;
250   walker->goto_node(node_no);
251 }
252
253 void
254 TileMap::start_moving()
255 {
256   if (!walker.get()) return;
257   walker->start_moving();
258 }
259
260 void
261 TileMap::stop_moving()
262 {
263   if (!walker.get()) return;
264   walker->stop_moving();
265 }
266
267 void
268 TileMap::expose(HSQUIRRELVM vm, SQInteger table_idx)
269 {
270   if (name.empty()) return;
271   scripting::TileMap* _this = new scripting::TileMap(this);
272   expose_object(vm, table_idx, _this, name, true);
273 }
274
275 void
276 TileMap::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
277 {
278   if (name.empty()) return;
279   scripting::unexpose_object(vm, table_idx, name);
280 }
281
282 void
283 TileMap::set(int newwidth, int newheight, const std::vector<unsigned int>&newt,
284              int new_z_pos, bool newsolid)
285 {
286   if(int(newt.size()) != newwidth * newheight)
287     throw std::runtime_error("Wrong tilecount count.");
288
289   width  = newwidth;
290   height = newheight;
291
292   tiles.resize(newt.size());
293   tiles = newt;
294
295   if (new_z_pos > (LAYER_GUI - 100))
296     z_pos = LAYER_GUI - 100;
297   else
298     z_pos  = new_z_pos;
299   real_solid  = newsolid;
300   update_effective_solid ();
301
302   // make sure all tiles are loaded
303   for(Tiles::iterator i = tiles.begin(); i != tiles.end(); ++i)
304     tileset->get(*i);
305 }
306
307 void
308 TileMap::resize(int new_width, int new_height, int fill_id)
309 {
310   if(new_width < width) {
311     // remap tiles for new width
312     for(int y = 0; y < height && y < new_height; ++y) {
313       for(int x = 0; x < new_width; ++x) {
314         tiles[y * new_width + x] = tiles[y * width + x];
315       }
316     }
317   }
318
319   tiles.resize(new_width * new_height, fill_id);
320
321   if(new_width > width) {
322     // remap tiles
323     for(int y = std::min(height, new_height)-1; y >= 0; --y) {
324       for(int x = new_width-1; x >= 0; --x) {
325         if(x >= width) {
326           tiles[y * new_width + x] = fill_id;
327           continue;
328         }
329
330         tiles[y * new_width + x] = tiles[y * width + x];
331       }
332     }
333   }
334
335   height = new_height;
336   width = new_width;
337 }
338
339 Rect
340 TileMap::get_tiles_overlapping(const Rectf &rect) const
341 {
342   Rectf rect2 = rect;
343   rect2.move(-offset);
344
345   int t_left   = std::max(0     , int(floorf(rect2.get_left  () / 32)));
346   int t_right  = std::min(width , int(ceilf (rect2.get_right () / 32)));
347   int t_top    = std::max(0     , int(floorf(rect2.get_top   () / 32)));
348   int t_bottom = std::min(height, int(ceilf (rect2.get_bottom() / 32)));
349   return Rect(t_left, t_top, t_right, t_bottom);
350 }
351
352 void
353 TileMap::set_solid(bool solid)
354 {
355   this->real_solid = solid;
356   update_effective_solid ();
357 }
358
359 uint32_t
360 TileMap::get_tile_id(int x, int y) const
361 {
362   if(x < 0 || x >= width || y < 0 || y >= height) {
363     //log_warning << "tile outside tilemap requested" << std::endl;
364     return 0;
365   }
366
367   return tiles[y*width + x];
368 }
369
370 const Tile*
371 TileMap::get_tile(int x, int y) const
372 {
373   uint32_t id = get_tile_id(x, y);
374   return tileset->get(id);
375 }
376
377 uint32_t
378 TileMap::get_tile_id_at(const Vector& pos) const
379 {
380   Vector xy = (pos - offset) / 32;
381   return get_tile_id(int(xy.x), int(xy.y));
382 }
383
384 const Tile*
385 TileMap::get_tile_at(const Vector& pos) const
386 {
387   uint32_t id = get_tile_id_at(pos);
388   return tileset->get(id);
389 }
390
391 void
392 TileMap::change(int x, int y, uint32_t newtile)
393 {
394   assert(x >= 0 && x < width && y >= 0 && y < height);
395   tiles[y*width + x] = newtile;
396 }
397
398 void
399 TileMap::change_at(const Vector& pos, uint32_t newtile)
400 {
401   Vector xy = (pos - offset) / 32;
402   change(int(xy.x), int(xy.y), newtile);
403 }
404
405 void
406 TileMap::change_all(uint32_t oldtile, uint32_t newtile)
407 {
408   for (size_t x = 0; x < get_width(); x++) {
409     for (size_t y = 0; y < get_height(); y++) {
410       if (get_tile_id(x,y) != oldtile)
411         continue;
412
413       change(x,y,newtile);
414     }
415   }
416 }
417
418 void
419 TileMap::fade(float alpha_, float seconds)
420 {
421   this->alpha = alpha_;
422   this->remaining_fade_time = seconds;
423 }
424
425 void
426 TileMap::set_alpha(float alpha_)
427 {
428   this->alpha = alpha_;
429   this->current_alpha = alpha;
430   this->remaining_fade_time = 0;
431   update_effective_solid ();
432 }
433
434 float
435 TileMap::get_alpha()
436 {
437   return this->current_alpha;
438 }
439
440 /*
441  * Private methods
442  */
443 void
444 TileMap::update_effective_solid (void)
445 {
446   if (!real_solid)
447     effective_solid = false;
448   else if (effective_solid && (current_alpha < .25))
449     effective_solid = false;
450   else if (!effective_solid && (current_alpha >= .75))
451     effective_solid = true;
452 }
453
454 /* EOF */