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