camera can move now
[supertux.git] / src / object / camera.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2004 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 "camera.hpp"
29 #include "player.hpp"
30 #include "tilemap.hpp"
31 #include "game_session.hpp"
32 #include "sector.hpp"
33 #include "main.hpp"
34 #include "object_factory.hpp"
35
36 Camera::Camera(Sector* newsector)
37   : sector(newsector), do_backscrolling(true), scrollchange(NONE),
38     auto_idx(0), auto_t(0)
39 {
40   mode = NORMAL;
41 }
42
43 Camera::~Camera()
44 {
45 }
46
47 const Vector&
48 Camera::get_translation() const
49 {
50   return translation;
51 }
52
53 void
54 Camera::parse(const lisp::Lisp& reader)
55 {
56   std::string modename;
57   
58   reader.get("mode", modename);
59   if(modename == "normal") {
60     mode = NORMAL;
61
62     do_backscrolling = true;
63     reader.get("backscrolling", do_backscrolling);
64   } else if(modename == "autoscroll") {
65     printf("autoscroll.\n");
66     mode = AUTOSCROLL;
67     
68     const lisp::Lisp* path_lisp = reader.get_lisp("path");
69     if(!path_lisp)
70       throw std::runtime_error("No path specified in autoscroll camera.");
71
72     lisp::ListIterator iter(path_lisp);
73     float speed = .5;
74     while(iter.next()) {
75       if(iter.item() != "point") {
76         std::cerr << "Warning: unknown token '" << iter.item() 
77           << "' in camera path.\n";
78         continue;
79       }
80       const lisp::Lisp* point_lisp = iter.lisp();
81
82       ScrollPoint point;
83       if(!point_lisp->get("x", point.position.x) ||
84          !point_lisp->get("y", point.position.y)) {
85         throw std::runtime_error("x and y missing in point of camerapath");
86       }
87       point_lisp->get("speed", speed);
88       point.speed = speed;
89       scrollpoints.push_back(point);
90     }
91   } else if(modename == "manual") {
92     mode = MANUAL;
93   } else {
94     std::stringstream str;
95     str << "invalid camera mode '" << modename << "'found in worldfile.";
96     throw std::runtime_error(str.str());
97   }
98 }
99
100 void
101 Camera::write(lisp::Writer& writer)
102 {
103   writer.start_list("camera");
104   
105   if(mode == NORMAL) {
106     writer.write_string("mode", "normal");
107     writer.write_bool("backscrolling", do_backscrolling);
108   } else if(mode == AUTOSCROLL) {
109     writer.write_string("mode", "autoscroll");
110     writer.start_list("path");
111     for(std::vector<ScrollPoint>::iterator i = scrollpoints.begin();
112         i != scrollpoints.end(); ++i) {
113       writer.start_list("point");
114       writer.write_float("x", i->position.x);
115       writer.write_float("y", i->position.y);
116       writer.write_float("speed", i->speed);
117       writer.end_list("point");
118     }
119
120     writer.end_list("path");
121   } else if(mode == MANUAL) {
122     writer.write_string("mode", "manual");
123   }
124                      
125   writer.end_list("camera");
126 }
127
128 void
129 Camera::reset(const Vector& tuxpos)
130 {
131   translation.x = tuxpos.x - SCREEN_WIDTH/3 * 2;
132   translation.y = tuxpos.y - SCREEN_HEIGHT/2;
133   shakespeed = 0;
134   shaketimer.stop();
135   keep_in_bounds(translation);
136 }
137
138 void
139 Camera::shake(float time, float x, float y)
140 {
141   shaketimer.start(time);
142   shakedepth_x = x;
143   shakedepth_y = y;
144   shakespeed = M_PI/2 / time;
145 }
146
147 void
148 Camera::scroll_to(const Vector& goal, float scrolltime)
149 {
150   scroll_from = translation;
151   scroll_goal = goal;
152   keep_in_bounds(scroll_goal);
153
154   scroll_to_pos = 0;
155   scrollspeed = 1.0 / scrolltime;
156   mode = SCROLLTO;
157 }
158
159 static const float EPSILON = .00001;
160 static const float max_speed_y = 140;
161
162 void
163 Camera::update(float elapsed_time)
164 {
165   switch(mode) {
166     case NORMAL:
167       update_scroll_normal(elapsed_time);
168       break;
169     case AUTOSCROLL:
170       update_scroll_autoscroll(elapsed_time);
171       break;
172     case SCROLLTO:
173       update_scroll_to(elapsed_time);
174       break;
175     default:
176       break;
177   }
178 }
179
180 void
181 Camera::keep_in_bounds(Vector& translation)
182 {
183   float width = sector->solids->get_width() * 32;
184   float height = sector->solids->get_height() * 32;
185
186   // don't scroll before the start or after the level's end
187   if(translation.y > height - SCREEN_HEIGHT)
188     translation.y = height - SCREEN_HEIGHT;
189   if(translation.y < 0)                                      
190     translation.y = 0; 
191   if(translation.x > width - SCREEN_WIDTH)
192     translation.x = width - SCREEN_WIDTH;
193   if(translation.x < 0)
194     translation.x = 0;                                         
195 }
196
197 void
198 Camera::shake()
199 {
200   if(shaketimer.started()) {
201     translation.x -= sin(shaketimer.get_timegone() * shakespeed) * shakedepth_x;
202     translation.y -= sin(shaketimer.get_timegone() * shakespeed) * shakedepth_y;
203   }
204 }
205
206 void
207 Camera::update_scroll_normal(float elapsed_time)
208 {
209   assert(sector != 0);
210   Player* player = sector->player;
211   
212   // check that we don't have division by zero later
213   if(elapsed_time < EPSILON)
214     return;
215
216   /****** Vertical Scrolling part ******/
217   bool do_y_scrolling = true;
218
219   if(player->is_dying() || sector->solids->get_height() == 19)
220     do_y_scrolling = false;
221
222   if(do_y_scrolling) {
223     // target_y is the high we target our scrolling at. This is not always the
224     // high of the player, but if he is jumping upwards we should use the
225     // position where he last touched the ground. (this probably needs
226     // exceptions for trampolines and similar things in the future)
227     float target_y;
228     if(player->fall_mode == Player::JUMPING)
229       target_y = player->last_ground_y + player->get_bbox().get_height();
230     else
231       target_y = player->get_bbox().p2.y;
232
233     // delta_y is the distance we'd have to travel to directly reach target_y
234     float delta_y = translation.y - (target_y - SCREEN_HEIGHT*2/3);
235     // speed is the speed the camera would need to reach target_y in this frame
236     float speed_y = delta_y / elapsed_time;
237
238     // limit the camera speed when jumping upwards
239     if(player->fall_mode != Player::FALLING 
240         && player->fall_mode != Player::TRAMPOLINE_JUMP) {
241       if(speed_y > max_speed_y)
242         speed_y = max_speed_y;
243       else if(speed_y < -max_speed_y)
244         speed_y = -max_speed_y;
245     }
246
247     // finally scroll with calculated speed
248     translation.y -= speed_y * elapsed_time;
249   }
250
251   /****** Horizontal scrolling part *******/
252
253   // our camera is either in leftscrolling, rightscrolling or nonscrollingmode.
254   
255   // when suddenly changing directions while scrolling into the other direction.
256   // abort scrolling, since tux might be going left/right at a relatively small
257   // part of the map (like when jumping upwards)
258   if((player->dir == ::LEFT && scrollchange == RIGHT)
259       || (player->dir == ::RIGHT && scrollchange == LEFT))
260     scrollchange = NONE;
261   // when in left 1/3rd of screen scroll left
262   if(player->get_bbox().get_middle().x < translation.x + SCREEN_WIDTH/3 - 16
263       && do_backscrolling)
264     scrollchange = LEFT;
265   // scroll right when in right 1/3rd of screen
266   else if(player->get_bbox().get_middle().x > translation.x + SCREEN_WIDTH/3*2+16)
267     scrollchange = RIGHT;
268
269   // calculate our scroll target depending on scroll mode
270   float target_x;
271   if(scrollchange == LEFT)
272     target_x = player->get_bbox().get_middle().x - SCREEN_WIDTH/3*2;
273   else if(scrollchange == RIGHT)
274     target_x = player->get_bbox().get_middle().x - SCREEN_WIDTH/3;
275   else
276     target_x = translation.x;
277
278   // that's the distance we would have to travel to reach target_x
279   float delta_x = translation.x - target_x;
280   // the speed we'd need to travel to reach target_x in this frame
281   float speed_x = delta_x / elapsed_time;
282
283   // limit our speed
284   float maxv = 130 + (fabsf(player->physic.get_velocity_x() * 1.3));
285   if(speed_x > maxv)
286     speed_x = maxv;
287   else if(speed_x < -maxv)
288     speed_x = -maxv;
289  
290   // apply scrolling
291   translation.x -= speed_x * elapsed_time;
292
293   keep_in_bounds(translation);
294   shake();
295 }
296
297 void
298 Camera::update_scroll_autoscroll(float elapsed_time)
299 {
300   Player* player = sector->player;
301   
302   if(player->is_dying())
303     return;
304
305   if(auto_t - elapsed_time >= 0) {
306     translation += current_dir * elapsed_time;
307     auto_t -= elapsed_time;
308   } else {
309     // do the rest of the old movement
310     translation += current_dir * auto_t;
311     elapsed_time -= auto_t;
312     auto_t = 0;
313
314     // construct path for next point
315     if(auto_idx+1 >= scrollpoints.size()) {
316       keep_in_bounds(translation);
317       return;
318     }
319     Vector distance = scrollpoints[auto_idx+1].position 
320                       - scrollpoints[auto_idx].position;
321     current_dir = distance.unit() * scrollpoints[auto_idx].speed;
322     auto_t = distance.norm() / scrollpoints[auto_idx].speed;
323
324     // do movement for the remaining time
325     translation += current_dir * elapsed_time;
326     auto_t -= elapsed_time;
327     auto_idx++;
328   }
329
330   keep_in_bounds(translation);
331   shake();
332 }
333
334 void
335 Camera::update_scroll_to(float elapsed_time)
336 {
337   scroll_to_pos += elapsed_time * scrollspeed;
338   if(scroll_to_pos >= 1.0) {
339     mode = MANUAL;
340     translation = scroll_goal;
341     return;
342   }
343
344   translation = (scroll_goal - scroll_from) * scroll_to_pos;
345 }
346