Re-add jungles, apple trees
[oweals/minetest.git] / src / camera.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "camera.h"
21 #include "debug.h"
22 #include "client.h"
23 #include "main.h" // for g_settings
24 #include "map.h"
25 #include "clientmap.h" // MapDrawControl
26 #include "mesh.h"
27 #include "player.h"
28 #include "tile.h"
29 #include <cmath>
30 #include "settings.h"
31 #include "itemdef.h" // For wield visualization
32 #include "noise.h" // easeCurve
33 #include "gamedef.h"
34 #include "sound.h"
35 #include "event.h"
36 #include "util/numeric.h"
37 #include "util/mathconstants.h"
38
39 Camera::Camera(scene::ISceneManager* smgr, MapDrawControl& draw_control,
40                 IGameDef *gamedef):
41         m_smgr(smgr),
42         m_playernode(NULL),
43         m_headnode(NULL),
44         m_cameranode(NULL),
45
46         m_wieldmgr(NULL),
47         m_wieldnode(NULL),
48         m_wieldlight(0),
49
50         m_draw_control(draw_control),
51         m_gamedef(gamedef),
52
53         m_camera_position(0,0,0),
54         m_camera_direction(0,0,0),
55
56         m_aspect(1.0),
57         m_fov_x(1.0),
58         m_fov_y(1.0),
59
60         m_added_frametime(0),
61         m_added_frames(0),
62         m_range_old(0),
63         m_frametime_old(0),
64         m_frametime_counter(0),
65         m_time_per_range(30. / 50), // a sane default of 30ms per 50 nodes of range
66
67         m_view_bobbing_anim(0),
68         m_view_bobbing_state(0),
69         m_view_bobbing_speed(0),
70
71         m_digging_anim(0),
72         m_digging_button(-1)
73 {
74         //dstream<<__FUNCTION_NAME<<std::endl;
75
76         // note: making the camera node a child of the player node
77         // would lead to unexpected behaviour, so we don't do that.
78         m_playernode = smgr->addEmptySceneNode(smgr->getRootSceneNode());
79         m_headnode = smgr->addEmptySceneNode(m_playernode);
80         m_cameranode = smgr->addCameraSceneNode(smgr->getRootSceneNode());
81         m_cameranode->bindTargetAndRotation(true);
82
83         // This needs to be in its own scene manager. It is drawn after
84         // all other 3D scene nodes and before the GUI.
85         m_wieldmgr = smgr->createNewSceneManager();
86         m_wieldmgr->addCameraSceneNode();
87         m_wieldnode = m_wieldmgr->addMeshSceneNode(createCubeMesh(v3f(1,1,1)), NULL);  // need a dummy mesh
88 }
89
90 Camera::~Camera()
91 {
92         m_wieldnode->setMesh(NULL);
93         m_wieldmgr->drop();
94 }
95
96 bool Camera::successfullyCreated(std::wstring& error_message)
97 {
98         if (m_playernode == NULL)
99         {
100                 error_message = L"Failed to create the player scene node";
101                 return false;
102         }
103         if (m_headnode == NULL)
104         {
105                 error_message = L"Failed to create the head scene node";
106                 return false;
107         }
108         if (m_cameranode == NULL)
109         {
110                 error_message = L"Failed to create the camera scene node";
111                 return false;
112         }
113         if (m_wieldmgr == NULL)
114         {
115                 error_message = L"Failed to create the wielded item scene manager";
116                 return false;
117         }
118         if (m_wieldnode == NULL)
119         {
120                 error_message = L"Failed to create the wielded item scene node";
121                 return false;
122         }
123         return true;
124 }
125
126 // Returns the fractional part of x
127 inline f32 my_modf(f32 x)
128 {
129         double dummy;
130         return modf(x, &dummy);
131 }
132
133 void Camera::step(f32 dtime)
134 {
135         if (m_view_bobbing_state != 0)
136         {
137                 //f32 offset = dtime * m_view_bobbing_speed * 0.035;
138                 f32 offset = dtime * m_view_bobbing_speed * 0.030;
139                 if (m_view_bobbing_state == 2)
140                 {
141 #if 0
142                         // Animation is getting turned off
143                         if (m_view_bobbing_anim < 0.5)
144                                 m_view_bobbing_anim -= offset;
145                         else
146                                 m_view_bobbing_anim += offset;
147                         if (m_view_bobbing_anim <= 0 || m_view_bobbing_anim >= 1)
148                         {
149                                 m_view_bobbing_anim = 0;
150                                 m_view_bobbing_state = 0;
151                         }
152 #endif
153 #if 1
154                         // Animation is getting turned off
155                         if(m_view_bobbing_anim < 0.25){
156                                 m_view_bobbing_anim -= offset;
157                         } else if(m_view_bobbing_anim > 0.75){
158                                 m_view_bobbing_anim += offset;
159                         } if(m_view_bobbing_anim < 0.5){
160                                 m_view_bobbing_anim += offset;
161                                 if(m_view_bobbing_anim > 0.5)
162                                         m_view_bobbing_anim = 0.5;
163                         } else {
164                                 m_view_bobbing_anim -= offset;
165                                 if(m_view_bobbing_anim < 0.5)
166                                         m_view_bobbing_anim = 0.5;
167                         }
168                         if(m_view_bobbing_anim <= 0 || m_view_bobbing_anim >= 1 ||
169                                         fabs(m_view_bobbing_anim - 0.5) < 0.01)
170                         {
171                                 m_view_bobbing_anim = 0;
172                                 m_view_bobbing_state = 0;
173                         }
174 #endif
175                 }
176                 else
177                 {
178                         float was = m_view_bobbing_anim;
179                         m_view_bobbing_anim = my_modf(m_view_bobbing_anim + offset);
180                         bool step = (was == 0 ||
181                                         (was < 0.5f && m_view_bobbing_anim >= 0.5f) ||
182                                         (was > 0.5f && m_view_bobbing_anim <= 0.5f));
183                         if(step){
184                                 MtEvent *e = new SimpleTriggerEvent("ViewBobbingStep");
185                                 m_gamedef->event()->put(e);
186                         }
187                 }
188         }
189
190         if (m_digging_button != -1)
191         {
192                 f32 offset = dtime * 3.5;
193                 float m_digging_anim_was = m_digging_anim;
194                 m_digging_anim += offset;
195                 if (m_digging_anim >= 1)
196                 {
197                         m_digging_anim = 0;
198                         m_digging_button = -1;
199                 }
200                 float lim = 0.15;
201                 if(m_digging_anim_was < lim && m_digging_anim >= lim)
202                 {
203                         if(m_digging_button == 0){
204                                 MtEvent *e = new SimpleTriggerEvent("CameraPunchLeft");
205                                 m_gamedef->event()->put(e);
206                         } else if(m_digging_button == 1){
207                                 MtEvent *e = new SimpleTriggerEvent("CameraPunchRight");
208                                 m_gamedef->event()->put(e);
209                         }
210                 }
211         }
212 }
213
214 void Camera::update(LocalPlayer* player, f32 frametime, v2u32 screensize,
215                 f32 tool_reload_ratio)
216 {
217         // Get player position
218         // Smooth the movement when walking up stairs
219         v3f old_player_position = m_playernode->getPosition();
220         v3f player_position = player->getPosition();
221         //if(player->touching_ground && player_position.Y > old_player_position.Y)
222         if(player->touching_ground &&
223                         player_position.Y > old_player_position.Y)
224         {
225                 f32 oldy = old_player_position.Y;
226                 f32 newy = player_position.Y;
227                 f32 t = exp(-23*frametime);
228                 player_position.Y = oldy * t + newy * (1-t);
229         }
230
231         // Set player node transformation
232         m_playernode->setPosition(player_position);
233         m_playernode->setRotation(v3f(0, -1 * player->getYaw(), 0));
234         m_playernode->updateAbsolutePosition();
235
236         //Get camera tilt timer (hurt animation)
237         float cameratilt = fabs(fabs(player->hurt_tilt_timer-0.75)-0.75);
238
239         // Set head node transformation
240         m_headnode->setPosition(player->getEyeOffset()+v3f(0,cameratilt*-player->hurt_tilt_strength,0));
241         m_headnode->setRotation(v3f(player->getPitch(), 0, cameratilt*player->hurt_tilt_strength));
242         m_headnode->updateAbsolutePosition();
243
244         // Compute relative camera position and target
245         v3f rel_cam_pos = v3f(0,0,0);
246         v3f rel_cam_target = v3f(0,0,1);
247         v3f rel_cam_up = v3f(0,1,0);
248
249         if (m_view_bobbing_anim != 0)
250         {
251                 f32 bobfrac = my_modf(m_view_bobbing_anim * 2);
252                 f32 bobdir = (m_view_bobbing_anim < 0.5) ? 1.0 : -1.0;
253
254                 #if 1
255                 f32 bobknob = 1.2;
256                 f32 bobtmp = sin(pow(bobfrac, bobknob) * M_PI);
257                 //f32 bobtmp2 = cos(pow(bobfrac, bobknob) * M_PI);
258
259                 v3f bobvec = v3f(
260                         0.3 * bobdir * sin(bobfrac * M_PI),
261                         -0.28 * bobtmp * bobtmp,
262                         0.);
263
264                 //rel_cam_pos += 0.2 * bobvec;
265                 //rel_cam_target += 0.03 * bobvec;
266                 //rel_cam_up.rotateXYBy(0.02 * bobdir * bobtmp * M_PI);
267                 float f = 1.0;
268                 f *= g_settings->getFloat("view_bobbing_amount");
269                 rel_cam_pos += bobvec * f;
270                 //rel_cam_target += 0.995 * bobvec * f;
271                 rel_cam_target += bobvec * f;
272                 rel_cam_target.Z -= 0.005 * bobvec.Z * f;
273                 //rel_cam_target.X -= 0.005 * bobvec.X * f;
274                 //rel_cam_target.Y -= 0.005 * bobvec.Y * f;
275                 rel_cam_up.rotateXYBy(-0.03 * bobdir * bobtmp * M_PI * f);
276                 #else
277                 f32 angle_deg = 1 * bobdir * sin(bobfrac * M_PI);
278                 f32 angle_rad = angle_deg * M_PI / 180;
279                 f32 r = 0.05;
280                 v3f off = v3f(
281                         r * sin(angle_rad),
282                         r * (cos(angle_rad) - 1),
283                         0);
284                 rel_cam_pos += off;
285                 //rel_cam_target += off;
286                 rel_cam_up.rotateXYBy(angle_deg);
287                 #endif
288
289         }
290
291         // Compute absolute camera position and target
292         m_headnode->getAbsoluteTransformation().transformVect(m_camera_position, rel_cam_pos);
293         m_headnode->getAbsoluteTransformation().rotateVect(m_camera_direction, rel_cam_target - rel_cam_pos);
294
295         v3f abs_cam_up;
296         m_headnode->getAbsoluteTransformation().rotateVect(abs_cam_up, rel_cam_up);
297
298         // Set camera node transformation
299         m_cameranode->setPosition(m_camera_position);
300         m_cameranode->setUpVector(abs_cam_up);
301         // *100.0 helps in large map coordinates
302         m_cameranode->setTarget(m_camera_position + 100 * m_camera_direction);
303
304         // Get FOV setting
305         f32 fov_degrees = g_settings->getFloat("fov");
306         fov_degrees = MYMAX(fov_degrees, 10.0);
307         fov_degrees = MYMIN(fov_degrees, 170.0);
308
309         // FOV and aspect ratio
310         m_aspect = (f32)screensize.X / (f32) screensize.Y;
311         m_fov_y = fov_degrees * M_PI / 180.0;
312         // Increase vertical FOV on lower aspect ratios (<16:10)
313         m_fov_y *= MYMAX(1.0, MYMIN(1.4, sqrt(16./10. / m_aspect)));
314         // WTF is this? It can't be right
315         m_fov_x = 2 * atan(0.5 * m_aspect * tan(m_fov_y));
316         m_cameranode->setAspectRatio(m_aspect);
317         m_cameranode->setFOV(m_fov_y);
318
319         // Position the wielded item
320         //v3f wield_position = v3f(45, -35, 65);
321         v3f wield_position = v3f(55, -35, 65);
322         //v3f wield_rotation = v3f(-100, 120, -100);
323         v3f wield_rotation = v3f(-100, 120, -100);
324         if(m_digging_anim < 0.05 || m_digging_anim > 0.5){
325                 f32 frac = 1.0;
326                 if(m_digging_anim > 0.5)
327                         frac = 2.0 * (m_digging_anim - 0.5);
328                 // This value starts from 1 and settles to 0
329                 f32 ratiothing = pow((1.0f - tool_reload_ratio), 0.5f);
330                 //f32 ratiothing2 = pow(ratiothing, 0.5f);
331                 f32 ratiothing2 = (easeCurve(ratiothing*0.5))*2.0;
332                 wield_position.Y -= frac * 25.0 * pow(ratiothing2, 1.7f);
333                 //wield_position.Z += frac * 5.0 * ratiothing2;
334                 wield_position.X -= frac * 35.0 * pow(ratiothing2, 1.1f);
335                 wield_rotation.Y += frac * 70.0 * pow(ratiothing2, 1.4f);
336                 //wield_rotation.X -= frac * 15.0 * pow(ratiothing2, 1.4f);
337                 //wield_rotation.Z += frac * 15.0 * pow(ratiothing2, 1.0f);
338         }
339         if (m_digging_button != -1)
340         {
341                 f32 digfrac = m_digging_anim;
342                 wield_position.X -= 50 * sin(pow(digfrac, 0.8f) * M_PI);
343                 wield_position.Y += 24 * sin(digfrac * 1.8 * M_PI);
344                 wield_position.Z += 25 * 0.5;
345         
346                 // Euler angles are PURE EVIL, so why not use quaternions?
347                 core::quaternion quat_begin(wield_rotation * core::DEGTORAD);
348                 core::quaternion quat_end(v3f(80, 30, 100) * core::DEGTORAD);
349                 core::quaternion quat_slerp;
350                 quat_slerp.slerp(quat_begin, quat_end, sin(digfrac * M_PI));
351                 quat_slerp.toEuler(wield_rotation);
352                 wield_rotation *= core::RADTODEG;
353         }
354         else {
355                 f32 bobfrac = my_modf(m_view_bobbing_anim);
356                 wield_position.X -= sin(bobfrac*M_PI*2.0) * 3.0;
357                 wield_position.Y += sin(my_modf(bobfrac*2.0)*M_PI) * 3.0;
358         }
359         m_wieldnode->setPosition(wield_position);
360         m_wieldnode->setRotation(wield_rotation);
361         m_wieldlight = player->light;
362
363         // Render distance feedback loop
364         updateViewingRange(frametime);
365
366         // If the player seems to be walking on solid ground,
367         // view bobbing is enabled and free_move is off,
368         // start (or continue) the view bobbing animation.
369         v3f speed = player->getSpeed();
370         if ((hypot(speed.X, speed.Z) > BS) &&
371                 (player->touching_ground) &&
372                 (g_settings->getBool("view_bobbing") == true) &&
373                 (g_settings->getBool("free_move") == false ||
374                                 !m_gamedef->checkLocalPrivilege("fly")))
375         {
376                 // Start animation
377                 m_view_bobbing_state = 1;
378                 m_view_bobbing_speed = MYMIN(speed.getLength(), 40);
379         }
380         else if (m_view_bobbing_state == 1)
381         {
382                 // Stop animation
383                 m_view_bobbing_state = 2;
384                 m_view_bobbing_speed = 60;
385         }
386 }
387
388 void Camera::updateViewingRange(f32 frametime_in)
389 {
390         if (m_draw_control.range_all)
391                 return;
392
393         m_added_frametime += frametime_in;
394         m_added_frames += 1;
395
396         // Actually this counter kind of sucks because frametime is busytime
397         m_frametime_counter -= frametime_in;
398         if (m_frametime_counter > 0)
399                 return;
400         m_frametime_counter = 0.2;
401
402         /*dstream<<__FUNCTION_NAME
403                         <<": Collected "<<m_added_frames<<" frames, total of "
404                         <<m_added_frametime<<"s."<<std::endl;
405
406         dstream<<"m_draw_control.blocks_drawn="
407                         <<m_draw_control.blocks_drawn
408                         <<", m_draw_control.blocks_would_have_drawn="
409                         <<m_draw_control.blocks_would_have_drawn
410                         <<std::endl;*/
411
412         // Get current viewing range and FPS settings
413         f32 viewing_range_min = g_settings->getS16("viewing_range_nodes_min");
414         viewing_range_min = MYMAX(5.0, viewing_range_min);
415
416         f32 viewing_range_max = g_settings->getS16("viewing_range_nodes_max");
417         viewing_range_max = MYMAX(viewing_range_min, viewing_range_max);
418         
419         // Immediately apply hard limits
420         if(m_draw_control.wanted_range < viewing_range_min)
421                 m_draw_control.wanted_range = viewing_range_min;
422         if(m_draw_control.wanted_range > viewing_range_max)
423                 m_draw_control.wanted_range = viewing_range_max;
424
425         // Just so big a value that everything rendered is visible
426         // Some more allowance than viewing_range_max * BS because of clouds,
427         // active objects, etc.
428         if(viewing_range_max < 200*BS)
429                 m_cameranode->setFarValue(200 * BS * 10);
430         else
431                 m_cameranode->setFarValue(viewing_range_max * BS * 10);
432
433         f32 wanted_fps = g_settings->getFloat("wanted_fps");
434         wanted_fps = MYMAX(wanted_fps, 1.0);
435         f32 wanted_frametime = 1.0 / wanted_fps;
436
437         m_draw_control.wanted_min_range = viewing_range_min;
438         m_draw_control.wanted_max_blocks = (2.0*m_draw_control.blocks_would_have_drawn)+1;
439         if (m_draw_control.wanted_max_blocks < 10)
440                 m_draw_control.wanted_max_blocks = 10;
441
442         f32 block_draw_ratio = 1.0;
443         if (m_draw_control.blocks_would_have_drawn != 0)
444         {
445                 block_draw_ratio = (f32)m_draw_control.blocks_drawn
446                         / (f32)m_draw_control.blocks_would_have_drawn;
447         }
448
449         // Calculate the average frametime in the case that all wanted
450         // blocks had been drawn
451         f32 frametime = m_added_frametime / m_added_frames / block_draw_ratio;
452
453         m_added_frametime = 0.0;
454         m_added_frames = 0;
455
456         f32 wanted_frametime_change = wanted_frametime - frametime;
457         //dstream<<"wanted_frametime_change="<<wanted_frametime_change<<std::endl;
458
459         // If needed frametime change is small, just return
460         // This value was 0.4 for many months until 2011-10-18 by c55;
461         // Let's see how this works out.
462         if (fabs(wanted_frametime_change) < wanted_frametime*0.33)
463         {
464                 //dstream<<"ignoring small wanted_frametime_change"<<std::endl;
465                 return;
466         }
467
468         f32 range = m_draw_control.wanted_range;
469         f32 new_range = range;
470
471         f32 d_range = range - m_range_old;
472         f32 d_frametime = frametime - m_frametime_old;
473         if (d_range != 0)
474         {
475                 m_time_per_range = d_frametime / d_range;
476         }
477
478         // The minimum allowed calculated frametime-range derivative:
479         // Practically this sets the maximum speed of changing the range.
480         // The lower this value, the higher the maximum changing speed.
481         // A low value here results in wobbly range (0.001)
482         // A high value here results in slow changing range (0.0025)
483         // SUGG: This could be dynamically adjusted so that when
484         //       the camera is turning, this is lower
485         //f32 min_time_per_range = 0.0015;
486         f32 min_time_per_range = 0.0010;
487         //f32 min_time_per_range = 0.05 / range;
488         if(m_time_per_range < min_time_per_range)
489         {
490                 m_time_per_range = min_time_per_range;
491                 //dstream<<"m_time_per_range="<<m_time_per_range<<" (min)"<<std::endl;
492         }
493         else
494         {
495                 //dstream<<"m_time_per_range="<<m_time_per_range<<std::endl;
496         }
497
498         f32 wanted_range_change = wanted_frametime_change / m_time_per_range;
499         // Dampen the change a bit to kill oscillations
500         //wanted_range_change *= 0.9;
501         //wanted_range_change *= 0.75;
502         wanted_range_change *= 0.5;
503         //dstream<<"wanted_range_change="<<wanted_range_change<<std::endl;
504
505         // If needed range change is very small, just return
506         if(fabs(wanted_range_change) < 0.001)
507         {
508                 //dstream<<"ignoring small wanted_range_change"<<std::endl;
509                 return;
510         }
511
512         new_range += wanted_range_change;
513         
514         //f32 new_range_unclamped = new_range;
515         new_range = MYMAX(new_range, viewing_range_min);
516         new_range = MYMIN(new_range, viewing_range_max);
517         /*dstream<<"new_range="<<new_range_unclamped
518                         <<", clamped to "<<new_range<<std::endl;*/
519
520         m_draw_control.wanted_range = new_range;
521
522         m_range_old = new_range;
523         m_frametime_old = frametime;
524 }
525
526 void Camera::setDigging(s32 button)
527 {
528         if (m_digging_button == -1)
529                 m_digging_button = button;
530 }
531
532 void Camera::wield(const ItemStack &item)
533 {
534         IItemDefManager *idef = m_gamedef->idef();
535         scene::IMesh *wield_mesh = idef->getWieldMesh(item.getDefinition(idef).name, m_gamedef);
536         if(wield_mesh)
537         {
538                 m_wieldnode->setMesh(wield_mesh);
539                 m_wieldnode->setVisible(true);
540         }
541         else
542         {
543                 m_wieldnode->setVisible(false);
544         }
545 }
546
547 void Camera::drawWieldedTool()
548 {
549         // Set vertex colors of wield mesh according to light level
550         u8 li = m_wieldlight;
551         video::SColor color(255,li,li,li);
552         setMeshColor(m_wieldnode->getMesh(), color);
553
554         // Clear Z buffer
555         m_wieldmgr->getVideoDriver()->clearZBuffer();
556
557         // Draw the wielded node (in a separate scene manager)
558         scene::ICameraSceneNode* cam = m_wieldmgr->getActiveCamera();
559         cam->setAspectRatio(m_cameranode->getAspectRatio());
560         cam->setFOV(72.0*M_PI/180.0);
561         cam->setNearValue(0.1);
562         cam->setFarValue(100);
563         m_wieldmgr->drawAll();
564 }