Random stuff that I should have committed ages ago.
[supertux.git] / src / object / camera.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 #include <config.h>
20
21 #include "camera.hpp"
22
23 #include <stdexcept>
24 #include <sstream>
25 #include <cmath>
26 #include <physfs.h>
27
28 #include "lisp/lisp.hpp"
29 #include "lisp/writer.hpp"
30 #include "lisp/list_iterator.hpp"
31 #include "lisp/parser.hpp"
32 #include "scripting/camera.hpp"
33 #include "scripting/squirrel_util.hpp"
34 #include "player.hpp"
35 #include "tilemap.hpp"
36 #include "game_session.hpp"
37 #include "sector.hpp"
38 #include "main.hpp"
39 #include "object_factory.hpp"
40 #include "log.hpp"
41 #include "path.hpp"
42 #include "path_walker.hpp"
43
44 /* this is the fractional distance toward the peek
45    position to move each frame; lower is slower,
46    0 is never get there, 1 is instant */
47 static const float PEEK_ARRIVE_RATIO = 0.1;
48
49 class CameraConfig
50 {
51 public:
52   // 0 = No, 1 = Fix, 2 = Mario/Yoshi, 3 = Kirby
53   int ymode;
54   // as above, 4 = super metroid like
55   int xmode;
56   float kirby_rectsize_x;
57   float kirby_rectsize_y;
58   // where to fix the player (used for Yoshi and Fix camera)
59   float target_y;
60   float target_x;
61   // maximum scrolling speed in Y direction
62   float max_speed_y;
63   float max_speed_x;
64   // factor to dynamically increase max_speed_x based on player speed
65   float dynamic_max_speed_x;
66
67   // time the player has to face into the other direction before we assume a
68   // changed direction
69   float dirchange_time;
70   // edge_x
71   float edge_x;
72   // when too change from noscroll mode back to lookahead left/right mode
73   // set to <= 0 to disable noscroll mode
74   float sensitive_x;
75
76   float clamp_y;
77   float clamp_x;
78
79   float dynamic_speed_sm;
80
81   CameraConfig() {
82     xmode = 4;
83     ymode = 3;
84     target_x = .5f;
85     target_y = .5f;
86     max_speed_y = 100;
87     max_speed_x = 100;
88     clamp_x = 0.1666f;
89     clamp_y = 0.3f;
90     kirby_rectsize_x = 0.2f;
91     kirby_rectsize_y = 0.34f;
92     edge_x = 0.4f;
93     sensitive_x = -1;
94     dynamic_max_speed_x = 1.0;
95     dirchange_time = 0.2f;
96     dynamic_speed_sm = 0.8f;
97   }
98
99   void load(const std::string& filename)
100   {
101     lisp::Parser parser;
102     const lisp::Lisp* root = parser.parse(filename);
103     const lisp::Lisp* camconfig = root->get_lisp("camera-config");
104     if(camconfig == NULL)
105       throw std::runtime_error("file is not a camera config file.");
106
107     camconfig->get("xmode", xmode);
108     camconfig->get("ymode", ymode);
109     camconfig->get("target-x", target_x);
110     camconfig->get("target-y", target_y);
111     camconfig->get("max-speed-x", max_speed_x);
112     camconfig->get("max-speed-y", max_speed_y);
113     camconfig->get("dynamic-max-speed-x", dynamic_max_speed_x);
114     camconfig->get("dirchange-time", dirchange_time);
115     camconfig->get("clamp-x", clamp_x);
116     camconfig->get("clamp-y", clamp_y);
117     camconfig->get("kirby-rectsize-x", kirby_rectsize_x);
118     camconfig->get("kirby-rectsize-y", kirby_rectsize_y);
119     camconfig->get("edge-x", edge_x);
120     camconfig->get("sensitive-x", sensitive_x);
121     camconfig->get("dynamic-speed-sm", dynamic_speed_sm);
122   }
123 };
124
125 Camera::Camera(Sector* newsector, std::string name)
126   : mode(NORMAL), sector(newsector), lookahead_mode(LOOKAHEAD_NONE)
127 {
128   this->name = name;
129   config = new CameraConfig();
130   reload_config();
131 }
132
133 Camera::~Camera()
134 {
135   delete config;
136 }
137
138 void
139 Camera::expose(HSQUIRRELVM vm, SQInteger table_idx)
140 {
141   if(name.empty()) return;
142   Scripting::Camera* interface = new Scripting::Camera(this);
143   expose_object(vm, table_idx, interface, name, true);
144 }
145
146 void
147 Camera::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
148 {
149   if(name.empty()) return;
150   Scripting::unexpose_object(vm, table_idx, name);
151 }
152
153 void
154 Camera::draw(DrawingContext& )
155 {
156 }
157
158 const Vector&
159 Camera::get_translation() const
160 {
161   return translation;
162 }
163
164 void
165 Camera::parse(const lisp::Lisp& reader)
166 {
167   std::string modename;
168
169   reader.get("mode", modename);
170   if(modename == "normal") {
171     mode = NORMAL;
172   } else if(modename == "autoscroll") {
173     mode = AUTOSCROLL;
174
175     const lisp::Lisp* pathLisp = reader.get_lisp("path");
176     if(pathLisp == NULL)
177       throw std::runtime_error("No path specified in autoscroll camera.");
178
179     autoscroll_path.reset(new Path());
180     autoscroll_path->read(*pathLisp);
181     autoscroll_walker.reset(new PathWalker(autoscroll_path.get()));
182   } else if(modename == "manual") {
183     mode = MANUAL;
184   } else {
185     std::stringstream str;
186     str << "invalid camera mode '" << modename << "'found in worldfile.";
187     throw std::runtime_error(str.str());
188   }
189 }
190
191 void
192 Camera::write(lisp::Writer& writer)
193 {
194   writer.start_list("camera");
195
196   if(mode == NORMAL) {
197     writer.write("mode", "normal");
198   } else if(mode == AUTOSCROLL) {
199     writer.write("mode", "autoscroll");
200     autoscroll_path->write(writer);
201   } else if(mode == MANUAL) {
202     writer.write("mode", "manual");
203   }
204
205   writer.end_list("camera");
206 }
207
208 void
209 Camera::reset(const Vector& tuxpos)
210 {
211   translation.x = tuxpos.x - SCREEN_WIDTH/2;
212   translation.y = tuxpos.y - SCREEN_HEIGHT/2;
213
214   shakespeed = 0;
215   shaketimer.stop();
216   keep_in_bounds(translation);
217
218   cached_translation = translation;
219 }
220
221 void
222 Camera::shake(float time, float x, float y)
223 {
224   shaketimer.start(time);
225   shakedepth_x = x;
226   shakedepth_y = y;
227   shakespeed = M_PI/2 / time;
228 }
229
230 void
231 Camera::scroll_to(const Vector& goal, float scrolltime)
232 {
233   scroll_from = translation;
234   scroll_goal = goal;
235   keep_in_bounds(scroll_goal);
236
237   scroll_to_pos = 0;
238   scrollspeed = 1.0 / scrolltime;
239   mode = SCROLLTO;
240 }
241
242 static const float EPSILON = .00001f;
243 static const float MAX_SPEED_Y = 140;
244
245 void
246 Camera::update(float elapsed_time)
247 {
248   switch(mode) {
249     case NORMAL:
250       update_scroll_normal(elapsed_time);
251       break;
252     case AUTOSCROLL:
253       update_scroll_autoscroll(elapsed_time);
254       break;
255     case SCROLLTO:
256       update_scroll_to(elapsed_time);
257       break;
258     default:
259       break;
260   }
261   shake();
262 }
263
264 void
265 Camera::reload_config()
266 {
267   if(PHYSFS_exists("camera.cfg")) {
268     try {
269       config->load("camera.cfg");
270       log_info << "Loaded camera.cfg." << std::endl;
271     } catch(std::exception &e) {
272       log_debug << "Couldn't load camera.cfg, using defaults ("
273         << e.what() << ")" << std::endl;
274     }
275   }
276 }
277
278 float clamp(float val, float min, float max)
279 {
280   if(val < min)
281     return min;
282   if(val > max)
283     return max;
284
285   return val;
286 }
287
288 void
289 Camera::keep_in_bounds(Vector& translation)
290 {
291   float width = sector->get_width();
292   float height = sector->get_height();
293
294   // don't scroll before the start or after the level's end
295   translation.x = clamp(translation.x, 0, width - SCREEN_WIDTH);
296   translation.y = clamp(translation.y, 0, height - SCREEN_HEIGHT);
297
298   if (height < SCREEN_HEIGHT)
299     translation.y = height/2.0 - SCREEN_HEIGHT/2.0;
300   if (width < SCREEN_WIDTH)
301     translation.x = width/2.0 - SCREEN_WIDTH/2.0;
302 }
303
304 void
305 Camera::shake()
306 {
307   if(shaketimer.started()) {
308     translation.x -= sin(shaketimer.get_timegone() * shakespeed) * shakedepth_x;
309     translation.y -= sin(shaketimer.get_timegone() * shakespeed) * shakedepth_y;
310   }
311 }
312
313 void
314 Camera::update_scroll_normal(float elapsed_time)
315 {
316   const CameraConfig& config = *(this->config);
317   Player* player = sector->player;
318   const Vector& player_pos = Vector(player->get_bbox().get_middle().x,
319                                     player->get_bbox().get_bottom());
320   static Vector last_player_pos = player_pos;
321   Vector player_delta = player_pos - last_player_pos;
322   last_player_pos = player_pos;
323
324   // check that we don't have division by zero later
325   if(elapsed_time < EPSILON)
326     return;
327
328   /****** Vertical Scrolling part ******/
329   int xmode = config.xmode;
330   int ymode = config.ymode;
331
332   if(player->is_dying() || sector->get_height() == 19*32) {
333     ymode = 0;
334   }
335   if(player->is_dying())
336     xmode = 0;
337
338   if(ymode == 1) {
339     cached_translation.y = player_pos.y - SCREEN_HEIGHT * config.target_y;
340   }
341   if(ymode == 2) {
342     // target_y is the high we target our scrolling at. This is not always the
343     // high of the player, but if he is jumping upwards we should use the
344     // position where he last touched the ground. (this probably needs
345     // exceptions for trampolines and similar things in the future)
346     float target_y;
347     if(player->fall_mode == Player::JUMPING)
348       target_y = player->last_ground_y + player->get_bbox().get_height();
349     else
350       target_y = player->get_bbox().p2.y;
351     target_y -= SCREEN_HEIGHT * config.target_y;
352
353     // delta_y is the distance we'd have to travel to directly reach target_y
354     float delta_y = cached_translation.y - target_y;
355     // speed is the speed the camera would need to reach target_y in this frame
356     float speed_y = delta_y / elapsed_time;
357
358     // limit the camera speed when jumping upwards
359     if(player->fall_mode != Player::FALLING
360         && player->fall_mode != Player::TRAMPOLINE_JUMP) {
361       speed_y = clamp(speed_y, -config.max_speed_y, config.max_speed_y);
362     }
363
364     // scroll with calculated speed
365     cached_translation.y -= speed_y * elapsed_time;
366   }
367   if(ymode == 3) {
368     float halfsize = config.kirby_rectsize_y * 0.5f;
369     cached_translation.y = clamp(cached_translation.y,
370         player_pos.y - SCREEN_HEIGHT * (0.5f + halfsize),
371         player_pos.y - SCREEN_HEIGHT * (0.5f - halfsize));
372   }
373   if(ymode == 4) {
374     float upperend = SCREEN_HEIGHT * config.edge_x;
375     float lowerend = SCREEN_HEIGHT * (1 - config.edge_x);
376
377     if (player_delta.y < -EPSILON) {
378       // walking left
379       lookahead_pos.y -= player_delta.y * config.dynamic_speed_sm;
380
381       if(lookahead_pos.y > lowerend) {
382         lookahead_pos.y = lowerend;
383       }
384     } else if (player_delta.y > EPSILON) {
385       // walking right
386       lookahead_pos.y -= player_delta.y * config.dynamic_speed_sm;
387       if(lookahead_pos.y < upperend) {
388         lookahead_pos.y = upperend;
389       }
390     }
391
392     // adjust for level ends
393     if (player_pos.y < upperend) {
394       lookahead_pos.y = upperend;
395     }
396     if (player_pos.y > sector->get_width() - upperend) {
397       lookahead_pos.y = lowerend;
398     }
399
400     cached_translation.y = player_pos.y - lookahead_pos.y;
401   }
402
403   translation.y = cached_translation.y;
404
405   if(ymode != 0) {
406     float top_edge, bottom_edge;
407     if(config.clamp_y <= 0) {
408       top_edge = 0;
409       bottom_edge = SCREEN_HEIGHT;
410     } else {
411       top_edge = SCREEN_HEIGHT*config.clamp_y;
412       bottom_edge = SCREEN_HEIGHT*(1-config.clamp_y);
413     }
414
415     float peek_to = 0;
416     float translation_compensation = player_pos.y - translation.y;
417
418     if(player->peeking_direction_y() == ::UP) {
419       peek_to = bottom_edge - translation_compensation;
420     } else if(player->peeking_direction_y() == ::DOWN) {
421       peek_to = top_edge - translation_compensation;
422     }
423
424     float peek_move = (peek_to - peek_pos.y) * PEEK_ARRIVE_RATIO;
425     if(fabs(peek_move) < 1.0) {
426       peek_move = 0.0;
427     }
428
429     peek_pos.y += peek_move;
430
431     translation.y -= peek_pos.y;
432
433     if(config.clamp_y > 0) {
434       translation.y = clamp(translation.y,
435                             player_pos.y - SCREEN_HEIGHT * (1-config.clamp_y),
436                             player_pos.y - SCREEN_HEIGHT * config.clamp_y);
437       cached_translation.y = clamp(cached_translation.y,
438                                    player_pos.y - SCREEN_HEIGHT * (1-config.clamp_y),
439                                    player_pos.y - SCREEN_HEIGHT * config.clamp_y);
440     }
441   }
442
443   /****** Horizontal scrolling part *******/
444
445   if(xmode == 1) {
446     cached_translation.x = player_pos.x - SCREEN_WIDTH * config.target_x;
447   }
448   if(xmode == 2) {
449     // our camera is either in leftscrolling, rightscrolling or
450     // nonscrollingmode.
451     //
452     // when suddenly changing directions while scrolling into the other
453     // direction abort scrolling, since tux might be going left/right at a
454     // relatively small part of the map (like when jumping upwards)
455
456     // Find out direction in which the player moves
457     LookaheadMode walkDirection;
458     if (player_delta.x < -EPSILON) walkDirection = LOOKAHEAD_LEFT;
459     else if (player_delta.x > EPSILON) walkDirection = LOOKAHEAD_RIGHT;
460     else if (player->dir == ::LEFT) walkDirection = LOOKAHEAD_LEFT;
461     else walkDirection = LOOKAHEAD_RIGHT;
462
463     float LEFTEND, RIGHTEND;
464     if(config.sensitive_x > 0) {
465       LEFTEND = SCREEN_WIDTH * config.sensitive_x;
466       RIGHTEND = SCREEN_WIDTH * (1-config.sensitive_x);
467     } else {
468       LEFTEND = SCREEN_WIDTH;
469       RIGHTEND = 0;
470     }
471
472     if(lookahead_mode == LOOKAHEAD_NONE) {
473       /* if we're undecided then look if we crossed the left or right
474        * "sensitive" area */
475       if(player_pos.x < cached_translation.x + LEFTEND) {
476         lookahead_mode = LOOKAHEAD_LEFT;
477       } else if(player_pos.x > cached_translation.x + RIGHTEND) {
478         lookahead_mode = LOOKAHEAD_RIGHT;
479       }
480       /* at the ends of a level it's obvious which way we will go */
481       if(player_pos.x < SCREEN_WIDTH*0.5) {
482         lookahead_mode = LOOKAHEAD_RIGHT;
483       } else if(player_pos.x >= sector->get_width() - SCREEN_WIDTH*0.5) {
484         lookahead_mode = LOOKAHEAD_LEFT;
485       }
486
487       changetime = -1;
488     } else if(lookahead_mode != walkDirection) {
489       /* player changed direction while camera was scrolling...
490        * he has to do this for a certain time to add robustness against
491        * sudden changes */
492       if(changetime < 0) {
493         changetime = game_time;
494       } else if(game_time - changetime > config.dirchange_time) {
495         if(lookahead_mode == LOOKAHEAD_LEFT &&
496            player_pos.x > cached_translation.x + RIGHTEND) {
497           lookahead_mode = LOOKAHEAD_RIGHT;
498         } else if(lookahead_mode == LOOKAHEAD_RIGHT &&
499                   player_pos.x < cached_translation.x + LEFTEND) {
500           lookahead_mode = LOOKAHEAD_LEFT;
501         } else {
502           lookahead_mode = LOOKAHEAD_NONE;
503         }
504       }
505     } else {
506       changetime = -1;
507     }
508
509     LEFTEND = SCREEN_WIDTH * config.edge_x;
510     RIGHTEND = SCREEN_WIDTH * (1-config.edge_x);
511
512     // calculate our scroll target depending on scroll mode
513     float target_x;
514     if(lookahead_mode == LOOKAHEAD_LEFT)
515       target_x = player_pos.x - RIGHTEND;
516     else if(lookahead_mode == LOOKAHEAD_RIGHT)
517       target_x = player_pos.x - LEFTEND;
518     else
519       target_x = cached_translation.x;
520
521     // that's the distance we would have to travel to reach target_x
522     float delta_x = cached_translation.x - target_x;
523     // the speed we'd need to travel to reach target_x in this frame
524     float speed_x = delta_x / elapsed_time;
525
526     // limit our speed
527     float player_speed_x = player_delta.x / elapsed_time;
528     float maxv = config.max_speed_x + (fabsf(player_speed_x * config.dynamic_max_speed_x));
529     speed_x = clamp(speed_x, -maxv, maxv);
530
531     // apply scrolling
532     cached_translation.x -= speed_x * elapsed_time;
533   }
534   if(xmode == 3) {
535     float halfsize = config.kirby_rectsize_x * 0.5f;
536     cached_translation.x = clamp(cached_translation.x,
537         player_pos.x - SCREEN_WIDTH * (0.5f + halfsize),
538         player_pos.x - SCREEN_WIDTH * (0.5f - halfsize));
539   }
540   if(xmode == 4) {
541     float LEFTEND = SCREEN_WIDTH * config.edge_x;
542     float RIGHTEND = SCREEN_WIDTH * (1 - config.edge_x);
543
544     if (player_delta.x < -EPSILON) {
545       // walking left
546       lookahead_pos.x -= player_delta.x * config.dynamic_speed_sm;
547       if(lookahead_pos.x > RIGHTEND) {
548         lookahead_pos.x = RIGHTEND;
549       }
550
551     } else if (player_delta.x > EPSILON) {
552       // walking right
553       lookahead_pos.x -= player_delta.x * config.dynamic_speed_sm;
554       if(lookahead_pos.x < LEFTEND) {
555           lookahead_pos.x = LEFTEND;
556       }
557     }
558
559     // adjust for level ends
560     if (player_pos.x < LEFTEND) {
561       lookahead_pos.x = LEFTEND;
562     }
563     if (player_pos.x > sector->get_width() - LEFTEND) {
564       lookahead_pos.x = RIGHTEND;
565     }
566
567     cached_translation.x = player_pos.x - lookahead_pos.x;
568   }
569
570   translation.x = cached_translation.x;
571
572   if(xmode != 0) {
573     float left_edge, right_edge;
574     if(config.clamp_x <= 0) {
575       left_edge = 0;
576       right_edge = SCREEN_WIDTH;
577     } else {
578       left_edge = SCREEN_WIDTH*config.clamp_x;
579       right_edge = SCREEN_WIDTH*(1-config.clamp_x);
580     }
581
582     float peek_to = 0;
583     float translation_compensation = player_pos.x - translation.x;
584
585     if(player->peeking_direction_x() == ::LEFT) {
586       peek_to = right_edge - translation_compensation;
587     } else if(player->peeking_direction_x() == ::RIGHT) {
588       peek_to = left_edge - translation_compensation;
589     }
590
591     float peek_move = (peek_to - peek_pos.x) * PEEK_ARRIVE_RATIO;
592     if(fabs(peek_move) < 1.0) {
593       peek_move = 0.0;
594     }
595
596     peek_pos.x += peek_move;
597
598     translation.x -= peek_pos.x;
599
600     if(config.clamp_x > 0) {
601       translation.x = clamp(translation.x,
602                             player_pos.x - SCREEN_WIDTH * (1-config.clamp_x),
603                             player_pos.x - SCREEN_WIDTH * config.clamp_x);
604
605       cached_translation.x = clamp(cached_translation.x,
606                                    player_pos.x - SCREEN_WIDTH * (1-config.clamp_x),
607                                    player_pos.x - SCREEN_WIDTH * config.clamp_x);
608     }
609   }
610
611   keep_in_bounds(translation);
612   keep_in_bounds(cached_translation);
613 }
614
615 void
616 Camera::update_scroll_autoscroll(float elapsed_time)
617 {
618   Player* player = sector->player;
619   if(player->is_dying())
620     return;
621
622   translation = autoscroll_walker->advance(elapsed_time);
623
624   keep_in_bounds(translation);
625 }
626
627 void
628 Camera::update_scroll_to(float elapsed_time)
629 {
630   scroll_to_pos += elapsed_time * scrollspeed;
631   if(scroll_to_pos >= 1.0) {
632     mode = MANUAL;
633     translation = scroll_goal;
634     return;
635   }
636
637   translation = scroll_from + (scroll_goal - scroll_from) * scroll_to_pos;
638 }
639
640 Vector
641 Camera::get_center() const {
642   return translation + Vector(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2);
643 }
644