d4feaafd5c72847f65dd9594c3ee99f0b8fa3eb4
[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 <stdexcept>
22 #include <sstream>
23 #include <cmath>
24
25 #include "lisp/lisp.hpp"
26 #include "lisp/writer.hpp"
27 #include "lisp/list_iterator.hpp"
28 #include "lisp/parser.hpp"
29 #include "scripting/camera.hpp"
30 #include "scripting/squirrel_util.hpp"
31 #include "camera.hpp"
32 #include "player.hpp"
33 #include "tilemap.hpp"
34 #include "game_session.hpp"
35 #include "sector.hpp"
36 #include "main.hpp"
37 #include "object_factory.hpp"
38 #include "log.hpp"
39 #include "path.hpp"
40 #include "path_walker.hpp"
41
42 class CameraConfig
43 {
44 public:
45   // 0 = No, 1 = Fix, 2 = Mario/Yoshi, 3 = Kirby, 4 = inverse rubber
46   int ymode;
47   int xmode;
48   float kirby_rectsize_x;
49   float kirby_rectsize_y;
50   // where to fix the player (used for Yoshi and Fix camera)
51   float target_y;
52   float target_x;
53   // maximum scrolling speed in Y direction
54   float max_speed_y;
55   float max_speed_x;
56   // factor to dynamically increase max_speed_x based on player speed
57   float dynamic_max_speed_x;
58
59   // time the player has to face into the other direction before we assume a
60   // changed direction
61   float dirchange_time;
62   // edge_x
63   float edge_x;
64   // when too change from noscroll mode back to lookahead left/right mode
65   // set to <= 0 to disable noscroll mode
66   float sensitive_x;
67
68   float clamp_y;
69   float clamp_x;
70
71   CameraConfig() {
72     xmode = 1;
73     ymode = 1;
74     target_x = .5f;
75     target_y = 2.f/3.f;
76     max_speed_y = 140;
77     max_speed_x = 130;
78     clamp_x = 1.f/6.f;
79     clamp_y = 1.f/6.f;
80     kirby_rectsize_x = 0.2f;
81     kirby_rectsize_y = 0.34f;
82     edge_x = 1.f/3.f;
83     sensitive_x = 1.f/4.f;
84     dynamic_max_speed_x = 1.0;
85     dirchange_time = 0.2f;
86   }
87
88   void load(const std::string& filename)
89   {
90     lisp::Parser parser;
91     const lisp::Lisp* root = parser.parse(filename);
92     const lisp::Lisp* camconfig = root->get_lisp("camera-config");
93     if(camconfig == NULL)
94       throw std::runtime_error("file is not a camera config file.");
95
96     camconfig->get("xmode", xmode);
97     camconfig->get("ymode", ymode);
98     camconfig->get("target-x", target_x);
99     camconfig->get("target-y", target_y);
100     camconfig->get("max-speed-x", max_speed_x);
101     camconfig->get("max-speed-y", max_speed_y);
102     camconfig->get("dynamic-max-speed-x", dynamic_max_speed_x);
103     camconfig->get("dirchange-time", dirchange_time);
104     camconfig->get("clamp-x", clamp_x);
105     camconfig->get("clamp-y", clamp_y);
106     camconfig->get("kirby-rectsize-x", kirby_rectsize_x);
107     camconfig->get("kirby-rectsize-y", kirby_rectsize_y);
108     camconfig->get("edge-x", edge_x);
109     camconfig->get("sensitive-x", sensitive_x);
110   }
111 };
112
113 Camera::Camera(Sector* newsector, std::string name)
114   : mode(NORMAL), sector(newsector), lookahead_mode(LOOKAHEAD_NONE)
115 {
116   this->name = name;
117   config = new CameraConfig();
118   reload_config();
119 }
120
121 Camera::~Camera()
122 {
123   delete config;
124 }
125
126 void
127 Camera::expose(HSQUIRRELVM vm, SQInteger table_idx)
128 {
129   if(name.empty()) return;
130   Scripting::Camera* interface = new Scripting::Camera(this);
131   expose_object(vm, table_idx, interface, name, true);
132 }
133
134 void
135 Camera::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
136 {
137   if(name.empty()) return;
138   Scripting::unexpose_object(vm, table_idx, name);
139 }
140
141 void
142 Camera::draw(DrawingContext& )
143 {
144 }
145
146 const Vector&
147 Camera::get_translation() const
148 {
149   return translation;
150 }
151
152 void
153 Camera::parse(const lisp::Lisp& reader)
154 {
155   std::string modename;
156
157   reader.get("mode", modename);
158   if(modename == "normal") {
159     mode = NORMAL;
160   } else if(modename == "autoscroll") {
161     mode = AUTOSCROLL;
162
163     const lisp::Lisp* pathLisp = reader.get_lisp("path");
164     if(pathLisp == NULL)
165       throw std::runtime_error("No path specified in autoscroll camera.");
166
167     autoscroll_path.reset(new Path());
168     autoscroll_path->read(*pathLisp);
169     autoscroll_walker.reset(new PathWalker(autoscroll_path.get()));
170   } else if(modename == "manual") {
171     mode = MANUAL;
172   } else {
173     std::stringstream str;
174     str << "invalid camera mode '" << modename << "'found in worldfile.";
175     throw std::runtime_error(str.str());
176   }
177 }
178
179 void
180 Camera::write(lisp::Writer& writer)
181 {
182   writer.start_list("camera");
183
184   if(mode == NORMAL) {
185     writer.write_string("mode", "normal");
186   } else if(mode == AUTOSCROLL) {
187     writer.write_string("mode", "autoscroll");
188     autoscroll_path->write(writer);
189   } else if(mode == MANUAL) {
190     writer.write_string("mode", "manual");
191   }
192
193   writer.end_list("camera");
194 }
195
196 void
197 Camera::reset(const Vector& tuxpos)
198 {
199   translation.x = tuxpos.x - SCREEN_WIDTH/3 * 2;
200   translation.y = tuxpos.y - SCREEN_HEIGHT/2;
201   shakespeed = 0;
202   shaketimer.stop();
203   keep_in_bounds(translation);
204 }
205
206 void
207 Camera::shake(float time, float x, float y)
208 {
209   shaketimer.start(time);
210   shakedepth_x = x;
211   shakedepth_y = y;
212   shakespeed = M_PI/2 / time;
213 }
214
215 void
216 Camera::scroll_to(const Vector& goal, float scrolltime)
217 {
218   scroll_from = translation;
219   scroll_goal = goal;
220   keep_in_bounds(scroll_goal);
221
222   scroll_to_pos = 0;
223   scrollspeed = 1.0 / scrolltime;
224   mode = SCROLLTO;
225 }
226
227 static const float EPSILON = .00001f;
228 static const float MAX_SPEED_Y = 140;
229
230 void
231 Camera::update(float elapsed_time)
232 {
233   switch(mode) {
234     case NORMAL:
235       update_scroll_normal(elapsed_time);
236       break;
237     case AUTOSCROLL:
238       update_scroll_autoscroll(elapsed_time);
239       break;
240     case SCROLLTO:
241       update_scroll_to(elapsed_time);
242       break;
243     default:
244       break;
245   }
246   shake();
247 }
248
249 void
250 Camera::reload_config()
251 {
252   config->load("camera.cfg");
253 }
254
255 float clamp(float val, float min, float max)
256 {
257   if(val < min)
258     return min;
259   if(val > max)
260     return max;
261
262   return val;
263 }
264
265 void
266 Camera::keep_in_bounds(Vector& translation)
267 {
268   float width = sector->get_width();
269   float height = sector->get_height();
270
271   // don't scroll before the start or after the level's end
272   translation.x = clamp(translation.x, 0, width - SCREEN_WIDTH);
273   translation.y = clamp(translation.y, 0, height - SCREEN_HEIGHT);
274
275   if (height < SCREEN_HEIGHT)
276     translation.y = height/2.0 - SCREEN_HEIGHT/2.0;
277   if (width < SCREEN_WIDTH)
278     translation.x = width/2.0 - SCREEN_WIDTH/2.0;
279 }
280
281 void
282 Camera::shake()
283 {
284   if(shaketimer.started()) {
285     translation.x -= sin(shaketimer.get_timegone() * shakespeed) * shakedepth_x;
286     translation.y -= sin(shaketimer.get_timegone() * shakespeed) * shakedepth_y;
287   }
288 }
289
290 void
291 Camera::update_scroll_normal(float elapsed_time)
292 {
293   const CameraConfig& config = *(this->config);
294   Player* player = sector->player;
295   const Vector& player_pos = player->get_bbox().get_middle();
296   static Vector last_player_pos = player_pos;
297   Vector player_delta = player_pos - last_player_pos;
298   last_player_pos = player_pos;
299
300   // check that we don't have division by zero later
301   if(elapsed_time < EPSILON)
302     return;
303
304   /****** Vertical Scrolling part ******/
305   int xmode = config.xmode;
306   int ymode = config.ymode;
307
308   if(player->is_dying() || sector->get_height() == 19*32) {
309     ymode = 0;
310   }
311   if(player->is_dying())
312     xmode = 0;
313
314   if(ymode == 1) {
315     translation.y = player_pos.y - SCREEN_HEIGHT * config.target_y;
316   }
317   if(ymode == 2) {
318     // target_y is the high we target our scrolling at. This is not always the
319     // high of the player, but if he is jumping upwards we should use the
320     // position where he last touched the ground. (this probably needs
321     // exceptions for trampolines and similar things in the future)
322     float target_y;
323 #if 0
324     if(player->fall_mode == Player::JUMPING)
325       target_y = player->last_ground_y + player->get_bbox().get_height();
326     else
327       target_y = player->get_bbox().p2.y;
328 #endif
329     target_y = player->last_ground_y;
330
331     target_y -= SCREEN_HEIGHT * config.target_y;
332
333     // delta_y is the distance we'd have to travel to directly reach target_y
334     float delta_y = translation.y - target_y;
335     // speed is the speed the camera would need to reach target_y in this frame
336     float speed_y = delta_y / elapsed_time;
337
338     // limit the camera speed when jumping upwards
339     if(player->fall_mode != Player::FALLING
340         && player->fall_mode != Player::TRAMPOLINE_JUMP) {
341       speed_y = clamp(speed_y, -config.max_speed_y, config.max_speed_y);
342     }
343
344     // scroll with calculated speed
345     translation.y -= speed_y * elapsed_time;
346   }
347   if(ymode == 3) {
348     float halfsize = config.kirby_rectsize_y * 0.5f;
349     translation.y = clamp(translation.y,
350         player_pos.y - SCREEN_HEIGHT * (0.5f + halfsize),
351         player_pos.y - SCREEN_HEIGHT * (0.5f - halfsize));
352   }
353   if(ymode == 4) {
354     // TODO...
355   }
356
357   if(ymode != 0 && config.clamp_y > 0) {
358     translation.y = clamp(translation.y,
359         player_pos.y - SCREEN_HEIGHT * (1-config.clamp_y),
360         player_pos.y - SCREEN_HEIGHT * config.clamp_y);
361   }
362
363   /****** Horizontal scrolling part *******/
364
365   if(xmode == 1) {
366     translation.x = player_pos.x - SCREEN_WIDTH * config.target_x;
367   }
368   if(xmode == 2) {
369     // our camera is either in leftscrolling, rightscrolling or
370     // nonscrollingmode.
371     //
372     // when suddenly changing directions while scrolling into the other
373     // direction abort scrolling, since tux might be going left/right at a
374     // relatively small part of the map (like when jumping upwards)
375
376     // Find out direction in which the player moves
377     LookaheadMode walkDirection;
378     if (player_delta.x < -EPSILON) walkDirection = LOOKAHEAD_LEFT;
379     else if (player_delta.x > EPSILON) walkDirection = LOOKAHEAD_RIGHT;
380     else if (player->dir == ::LEFT) walkDirection = LOOKAHEAD_LEFT;
381     else walkDirection = LOOKAHEAD_RIGHT;
382
383     float LEFTEND, RIGHTEND;
384     if(config.sensitive_x > 0) {
385       LEFTEND = SCREEN_WIDTH * config.sensitive_x;
386       RIGHTEND = SCREEN_WIDTH * (1-config.sensitive_x);
387     } else {
388       LEFTEND = SCREEN_WIDTH;
389       RIGHTEND = 0;
390     }
391
392     if(lookahead_mode == LOOKAHEAD_NONE) {
393       /* if we're undecided then look if we crossed the left or right
394        * "sensitive" area */
395       if(player_pos.x < translation.x + LEFTEND) {
396         lookahead_mode = LOOKAHEAD_LEFT;
397       } else if(player_pos.x > translation.x + RIGHTEND) {
398         lookahead_mode = LOOKAHEAD_RIGHT;
399       }
400       /* at the ends of a level it's obvious which way we will go */
401       if(player_pos.x < SCREEN_WIDTH*0.5) {
402         lookahead_mode = LOOKAHEAD_RIGHT;
403       } else if(player_pos.x >= sector->get_width() - SCREEN_WIDTH*0.5) {
404         lookahead_mode = LOOKAHEAD_LEFT;
405       }
406
407       changetime = -1;
408     } else if(lookahead_mode != walkDirection) {
409       /* player changed direction while camera was scrolling...
410        * he has to do this for a certain time to add robustness against
411        * sudden changes */
412       if(changetime < 0) {
413         changetime = game_time;
414       } else if(game_time - changetime > config.dirchange_time) {
415         if(lookahead_mode == LOOKAHEAD_LEFT &&
416            player_pos.x > translation.x + RIGHTEND) {
417           lookahead_mode = LOOKAHEAD_RIGHT;
418         } else if(lookahead_mode == LOOKAHEAD_RIGHT &&
419                   player_pos.x < translation.x + LEFTEND) {
420           lookahead_mode = LOOKAHEAD_LEFT;
421         } else {
422           lookahead_mode = LOOKAHEAD_NONE;
423         }
424       }
425     } else {
426       changetime = -1;
427     }
428
429     LEFTEND = SCREEN_WIDTH * config.edge_x;
430     RIGHTEND = SCREEN_WIDTH * (1-config.edge_x);
431
432     // calculate our scroll target depending on scroll mode
433     float target_x;
434     if(lookahead_mode == LOOKAHEAD_LEFT)
435       target_x = player_pos.x - RIGHTEND;
436     else if(lookahead_mode == LOOKAHEAD_RIGHT)
437       target_x = player_pos.x - LEFTEND;
438     else
439       target_x = translation.x;
440
441     // that's the distance we would have to travel to reach target_x
442     float delta_x = translation.x - target_x;
443     // the speed we'd need to travel to reach target_x in this frame
444     float speed_x = delta_x / elapsed_time;
445
446     // limit our speed
447     float player_speed_x = player_delta.x / elapsed_time;
448     float maxv = config.max_speed_x + (fabsf(player_speed_x * config.dynamic_max_speed_x));
449     speed_x = clamp(speed_x, -maxv, maxv);
450
451     // If player is peeking scroll in that direction. Fast.
452     if(player->peeking_direction() == ::LEFT) {
453       speed_x = config.max_speed_x;
454     }
455     if(player->peeking_direction() == ::RIGHT) {
456       speed_x = -config.max_speed_x;
457     }
458
459     // apply scrolling
460     translation.x -= speed_x * elapsed_time;
461   }
462   if(mode == 3) {
463     float halfsize = config.kirby_rectsize_x * 0.5f;
464     translation.x = clamp(translation.x,
465         player_pos.x - SCREEN_WIDTH * (0.5f + halfsize),
466         player_pos.x - SCREEN_WIDTH * (0.5f - halfsize));
467   }
468   if(xmode == 4) {
469     // TODO...
470   }
471
472   if(xmode != 0 && config.clamp_x > 0) {
473     translation.x = clamp(translation.x,
474         player_pos.x - SCREEN_WIDTH * (1-config.clamp_x),
475         player_pos.x - SCREEN_WIDTH * config.clamp_x);
476   }
477
478   keep_in_bounds(translation);
479 }
480
481 void
482 Camera::update_scroll_autoscroll(float elapsed_time)
483 {
484   Player* player = sector->player;
485   if(player->is_dying())
486     return;
487
488   translation = autoscroll_walker->advance(elapsed_time);
489
490   keep_in_bounds(translation);
491 }
492
493 void
494 Camera::update_scroll_to(float elapsed_time)
495 {
496   scroll_to_pos += elapsed_time * scrollspeed;
497   if(scroll_to_pos >= 1.0) {
498     mode = MANUAL;
499     translation = scroll_goal;
500     return;
501   }
502
503   translation = scroll_from + (scroll_goal - scroll_from) * scroll_to_pos;
504 }