]> git.lizzy.rs Git - minetest.git/blob - src/client/camera.cpp
GUIScene: Clear depth buffer + replace deprecated clearZBuffer calls
[minetest.git] / src / client / 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 "config.h"
24 #include "map.h"
25 #include "clientmap.h"     // MapDrawControl
26 #include "player.h"
27 #include <cmath>
28 #include "client/renderingengine.h"
29 #include "settings.h"
30 #include "wieldmesh.h"
31 #include "noise.h"         // easeCurve
32 #include "sound.h"
33 #include "mtevent.h"
34 #include "nodedef.h"
35 #include "util/numeric.h"
36 #include "constants.h"
37 #include "fontengine.h"
38 #include "script/scripting_client.h"
39
40 #define CAMERA_OFFSET_STEP 200
41 #define WIELDMESH_OFFSET_X 55.0f
42 #define WIELDMESH_OFFSET_Y -35.0f
43 #define WIELDMESH_AMPLITUDE_X 7.0f
44 #define WIELDMESH_AMPLITUDE_Y 10.0f
45
46 Camera::Camera(MapDrawControl &draw_control, Client *client):
47         m_draw_control(draw_control),
48         m_client(client)
49 {
50         scene::ISceneManager *smgr = RenderingEngine::get_scene_manager();
51         // note: making the camera node a child of the player node
52         // would lead to unexpected behaviour, so we don't do that.
53         m_playernode = smgr->addEmptySceneNode(smgr->getRootSceneNode());
54         m_headnode = smgr->addEmptySceneNode(m_playernode);
55         m_cameranode = smgr->addCameraSceneNode(smgr->getRootSceneNode());
56         m_cameranode->bindTargetAndRotation(true);
57
58         // This needs to be in its own scene manager. It is drawn after
59         // all other 3D scene nodes and before the GUI.
60         m_wieldmgr = smgr->createNewSceneManager();
61         m_wieldmgr->addCameraSceneNode();
62         m_wieldnode = new WieldMeshSceneNode(m_wieldmgr, -1, false);
63         m_wieldnode->setItem(ItemStack(), m_client);
64         m_wieldnode->drop(); // m_wieldmgr grabbed it
65
66         /* TODO: Add a callback function so these can be updated when a setting
67          *       changes.  At this point in time it doesn't matter (e.g. /set
68          *       is documented to change server settings only)
69          *
70          * TODO: Local caching of settings is not optimal and should at some stage
71          *       be updated to use a global settings object for getting thse values
72          *       (as opposed to the this local caching). This can be addressed in
73          *       a later release.
74          */
75         m_cache_fall_bobbing_amount = g_settings->getFloat("fall_bobbing_amount");
76         m_cache_view_bobbing_amount = g_settings->getFloat("view_bobbing_amount");
77         // 45 degrees is the lowest FOV that doesn't cause the server to treat this
78         // as a zoom FOV and load world beyond the set server limits.
79         m_cache_fov                 = std::fmax(g_settings->getFloat("fov"), 45.0f);
80         m_arm_inertia               = g_settings->getBool("arm_inertia");
81         m_nametags.clear();
82         m_show_nametag_backgrounds  = g_settings->getBool("show_nametag_backgrounds");
83 }
84
85 Camera::~Camera()
86 {
87         m_wieldmgr->drop();
88 }
89
90 void Camera::notifyFovChange()
91 {
92         LocalPlayer *player = m_client->getEnv().getLocalPlayer();
93         assert(player);
94
95         PlayerFovSpec spec = player->getFov();
96
97         /*
98          * Update m_old_fov_degrees first - it serves as the starting point of the
99          * upcoming transition.
100          *
101          * If an FOV transition is already active, mark current FOV as the start of
102          * the new transition. If not, set it to the previous transition's target FOV.
103          */
104         if (m_fov_transition_active)
105                 m_old_fov_degrees = m_curr_fov_degrees;
106         else
107                 m_old_fov_degrees = m_server_sent_fov ? m_target_fov_degrees : m_cache_fov;
108
109         /*
110          * Update m_server_sent_fov next - it corresponds to the target FOV of the
111          * upcoming transition.
112          *
113          * Set it to m_cache_fov, if server-sent FOV is 0. Otherwise check if
114          * server-sent FOV is a multiplier, and multiply it with m_cache_fov instead
115          * of overriding.
116          */
117         if (spec.fov == 0.0f) {
118                 m_server_sent_fov = false;
119                 m_target_fov_degrees = m_cache_fov;
120         } else {
121                 m_server_sent_fov = true;
122                 m_target_fov_degrees = spec.is_multiplier ? m_cache_fov * spec.fov : spec.fov;
123         }
124
125         if (spec.transition_time > 0.0f)
126                 m_fov_transition_active = true;
127
128         // If FOV smooth transition is active, initialize required variables
129         if (m_fov_transition_active) {
130                 m_transition_time = spec.transition_time;
131                 m_fov_diff = m_target_fov_degrees - m_old_fov_degrees;
132         }
133 }
134
135 bool Camera::successfullyCreated(std::string &error_message)
136 {
137         if (!m_playernode) {
138                 error_message = "Failed to create the player scene node";
139         } else if (!m_headnode) {
140                 error_message = "Failed to create the head scene node";
141         } else if (!m_cameranode) {
142                 error_message = "Failed to create the camera scene node";
143         } else if (!m_wieldmgr) {
144                 error_message = "Failed to create the wielded item scene manager";
145         } else if (!m_wieldnode) {
146                 error_message = "Failed to create the wielded item scene node";
147         } else {
148                 error_message.clear();
149         }
150
151         if (m_client->modsLoaded())
152                 m_client->getScript()->on_camera_ready(this);
153
154         return error_message.empty();
155 }
156
157 // Returns the fractional part of x
158 inline f32 my_modf(f32 x)
159 {
160         double dummy;
161         return modf(x, &dummy);
162 }
163
164 void Camera::step(f32 dtime)
165 {
166         if(m_view_bobbing_fall > 0)
167         {
168                 m_view_bobbing_fall -= 3 * dtime;
169                 if(m_view_bobbing_fall <= 0)
170                         m_view_bobbing_fall = -1; // Mark the effect as finished
171         }
172
173         bool was_under_zero = m_wield_change_timer < 0;
174         m_wield_change_timer = MYMIN(m_wield_change_timer + dtime, 0.125);
175
176         if (m_wield_change_timer >= 0 && was_under_zero)
177                 m_wieldnode->setItem(m_wield_item_next, m_client);
178
179         if (m_view_bobbing_state != 0)
180         {
181                 //f32 offset = dtime * m_view_bobbing_speed * 0.035;
182                 f32 offset = dtime * m_view_bobbing_speed * 0.030;
183                 if (m_view_bobbing_state == 2) {
184                         // Animation is getting turned off
185                         if (m_view_bobbing_anim < 0.25) {
186                                 m_view_bobbing_anim -= offset;
187                         } else if (m_view_bobbing_anim > 0.75) {
188                                 m_view_bobbing_anim += offset;
189                         }
190
191                         if (m_view_bobbing_anim < 0.5) {
192                                 m_view_bobbing_anim += offset;
193                                 if (m_view_bobbing_anim > 0.5)
194                                         m_view_bobbing_anim = 0.5;
195                         } else {
196                                 m_view_bobbing_anim -= offset;
197                                 if (m_view_bobbing_anim < 0.5)
198                                         m_view_bobbing_anim = 0.5;
199                         }
200
201                         if (m_view_bobbing_anim <= 0 || m_view_bobbing_anim >= 1 ||
202                                         fabs(m_view_bobbing_anim - 0.5) < 0.01) {
203                                 m_view_bobbing_anim = 0;
204                                 m_view_bobbing_state = 0;
205                         }
206                 }
207                 else {
208                         float was = m_view_bobbing_anim;
209                         m_view_bobbing_anim = my_modf(m_view_bobbing_anim + offset);
210                         bool step = (was == 0 ||
211                                         (was < 0.5f && m_view_bobbing_anim >= 0.5f) ||
212                                         (was > 0.5f && m_view_bobbing_anim <= 0.5f));
213                         if(step) {
214                                 m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::VIEW_BOBBING_STEP));
215                         }
216                 }
217         }
218
219         if (m_digging_button != -1) {
220                 f32 offset = dtime * 3.5f;
221                 float m_digging_anim_was = m_digging_anim;
222                 m_digging_anim += offset;
223                 if (m_digging_anim >= 1)
224                 {
225                         m_digging_anim = 0;
226                         m_digging_button = -1;
227                 }
228                 float lim = 0.15;
229                 if(m_digging_anim_was < lim && m_digging_anim >= lim)
230                 {
231                         if (m_digging_button == 0) {
232                                 m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::CAMERA_PUNCH_LEFT));
233                         } else if(m_digging_button == 1) {
234                                 m_client->getEventManager()->put(new SimpleTriggerEvent(MtEvent::CAMERA_PUNCH_RIGHT));
235                         }
236                 }
237         }
238 }
239
240 static inline v2f dir(const v2f &pos_dist)
241 {
242         f32 x = pos_dist.X - WIELDMESH_OFFSET_X;
243         f32 y = pos_dist.Y - WIELDMESH_OFFSET_Y;
244
245         f32 x_abs = std::fabs(x);
246         f32 y_abs = std::fabs(y);
247
248         if (x_abs >= y_abs) {
249                 y *= (1.0f / x_abs);
250                 x /= x_abs;
251         }
252
253         if (y_abs >= x_abs) {
254                 x *= (1.0f / y_abs);
255                 y /= y_abs;
256         }
257
258         return v2f(std::fabs(x), std::fabs(y));
259 }
260
261 void Camera::addArmInertia(f32 player_yaw)
262 {
263         m_cam_vel.X = std::fabs(rangelim(m_last_cam_pos.X - player_yaw,
264                 -100.0f, 100.0f) / 0.016f) * 0.01f;
265         m_cam_vel.Y = std::fabs((m_last_cam_pos.Y - m_camera_direction.Y) / 0.016f);
266         f32 gap_X = std::fabs(WIELDMESH_OFFSET_X - m_wieldmesh_offset.X);
267         f32 gap_Y = std::fabs(WIELDMESH_OFFSET_Y - m_wieldmesh_offset.Y);
268
269         if (m_cam_vel.X > 1.0f || m_cam_vel.Y > 1.0f) {
270                 /*
271                     The arm moves relative to the camera speed,
272                     with an acceleration factor.
273                 */
274
275                 if (m_cam_vel.X > 1.0f) {
276                         if (m_cam_vel.X > m_cam_vel_old.X)
277                                 m_cam_vel_old.X = m_cam_vel.X;
278
279                         f32 acc_X = 0.12f * (m_cam_vel.X - (gap_X * 0.1f));
280                         m_wieldmesh_offset.X += m_last_cam_pos.X < player_yaw ? acc_X : -acc_X;
281
282                         if (m_last_cam_pos.X != player_yaw)
283                                 m_last_cam_pos.X = player_yaw;
284
285                         m_wieldmesh_offset.X = rangelim(m_wieldmesh_offset.X,
286                                 WIELDMESH_OFFSET_X - (WIELDMESH_AMPLITUDE_X * 0.5f),
287                                 WIELDMESH_OFFSET_X + (WIELDMESH_AMPLITUDE_X * 0.5f));
288                 }
289
290                 if (m_cam_vel.Y > 1.0f) {
291                         if (m_cam_vel.Y > m_cam_vel_old.Y)
292                                 m_cam_vel_old.Y = m_cam_vel.Y;
293
294                         f32 acc_Y = 0.12f * (m_cam_vel.Y - (gap_Y * 0.1f));
295                         m_wieldmesh_offset.Y +=
296                                 m_last_cam_pos.Y > m_camera_direction.Y ? acc_Y : -acc_Y;
297
298                         if (m_last_cam_pos.Y != m_camera_direction.Y)
299                                 m_last_cam_pos.Y = m_camera_direction.Y;
300
301                         m_wieldmesh_offset.Y = rangelim(m_wieldmesh_offset.Y,
302                                 WIELDMESH_OFFSET_Y - (WIELDMESH_AMPLITUDE_Y * 0.5f),
303                                 WIELDMESH_OFFSET_Y + (WIELDMESH_AMPLITUDE_Y * 0.5f));
304                 }
305
306                 m_arm_dir = dir(m_wieldmesh_offset);
307         } else {
308                 /*
309                     Now the arm gets back to its default position when the camera stops,
310                     following a vector, with a smooth deceleration factor.
311                 */
312
313                 f32 dec_X = 0.35f * (std::min(15.0f, m_cam_vel_old.X) * (1.0f +
314                         (1.0f - m_arm_dir.X))) * (gap_X / 20.0f);
315
316                 f32 dec_Y = 0.25f * (std::min(15.0f, m_cam_vel_old.Y) * (1.0f +
317                         (1.0f - m_arm_dir.Y))) * (gap_Y / 15.0f);
318
319                 if (gap_X < 0.1f)
320                         m_cam_vel_old.X = 0.0f;
321
322                 m_wieldmesh_offset.X -=
323                         m_wieldmesh_offset.X > WIELDMESH_OFFSET_X ? dec_X : -dec_X;
324
325                 if (gap_Y < 0.1f)
326                         m_cam_vel_old.Y = 0.0f;
327
328                 m_wieldmesh_offset.Y -=
329                         m_wieldmesh_offset.Y > WIELDMESH_OFFSET_Y ? dec_Y : -dec_Y;
330         }
331 }
332
333 void Camera::update(LocalPlayer* player, f32 frametime, f32 busytime, f32 tool_reload_ratio)
334 {
335         // Get player position
336         // Smooth the movement when walking up stairs
337         v3f old_player_position = m_playernode->getPosition();
338         v3f player_position = player->getPosition();
339
340         // This is worse than `LocalPlayer::getPosition()` but
341         // mods expect the player head to be at the parent's position
342         // plus eye height.
343         if (player->getParent())
344                 player_position = player->getParent()->getPosition();
345
346         // Smooth the camera movement when the player instantly moves upward due to stepheight.
347         // To smooth the 'not touching_ground' stepheight, smoothing is necessary when jumping
348         // or swimming (for when moving from liquid to land).
349         // Disable smoothing if climbing or flying, to avoid upwards offset of player model
350         // when seen in 3rd person view.
351         bool flying = g_settings->getBool("free_move") && m_client->checkLocalPrivilege("fly");
352         if (player_position.Y > old_player_position.Y && !player->is_climbing && !flying) {
353                 f32 oldy = old_player_position.Y;
354                 f32 newy = player_position.Y;
355                 f32 t = std::exp(-23 * frametime);
356                 player_position.Y = oldy * t + newy * (1-t);
357         }
358
359         // Set player node transformation
360         m_playernode->setPosition(player_position);
361         m_playernode->setRotation(v3f(0, -1 * player->getYaw(), 0));
362         m_playernode->updateAbsolutePosition();
363
364         // Get camera tilt timer (hurt animation)
365         float cameratilt = fabs(fabs(player->hurt_tilt_timer-0.75)-0.75);
366
367         // Fall bobbing animation
368         float fall_bobbing = 0;
369         if(player->camera_impact >= 1 && m_camera_mode < CAMERA_MODE_THIRD)
370         {
371                 if(m_view_bobbing_fall == -1) // Effect took place and has finished
372                         player->camera_impact = m_view_bobbing_fall = 0;
373                 else if(m_view_bobbing_fall == 0) // Initialize effect
374                         m_view_bobbing_fall = 1;
375
376                 // Convert 0 -> 1 to 0 -> 1 -> 0
377                 fall_bobbing = m_view_bobbing_fall < 0.5 ? m_view_bobbing_fall * 2 : -(m_view_bobbing_fall - 0.5) * 2 + 1;
378                 // Smoothen and invert the above
379                 fall_bobbing = sin(fall_bobbing * 0.5 * M_PI) * -1;
380                 // Amplify according to the intensity of the impact
381                 fall_bobbing *= (1 - rangelim(50 / player->camera_impact, 0, 1)) * 5;
382
383                 fall_bobbing *= m_cache_fall_bobbing_amount;
384         }
385
386         // Calculate and translate the head SceneNode offsets
387         {
388                 v3f eye_offset = player->getEyeOffset();
389                 if (m_camera_mode == CAMERA_MODE_FIRST)
390                         eye_offset += player->eye_offset_first;
391                 else
392                         eye_offset += player->eye_offset_third;
393
394                 // Set head node transformation
395                 eye_offset.Y += cameratilt * -player->hurt_tilt_strength + fall_bobbing;
396                 m_headnode->setPosition(eye_offset);
397                 m_headnode->setRotation(v3f(player->getPitch(), 0,
398                         cameratilt * player->hurt_tilt_strength));
399                 m_headnode->updateAbsolutePosition();
400         }
401
402         // Compute relative camera position and target
403         v3f rel_cam_pos = v3f(0,0,0);
404         v3f rel_cam_target = v3f(0,0,1);
405         v3f rel_cam_up = v3f(0,1,0);
406
407         if (m_cache_view_bobbing_amount != 0.0f && m_view_bobbing_anim != 0.0f &&
408                 m_camera_mode < CAMERA_MODE_THIRD) {
409                 f32 bobfrac = my_modf(m_view_bobbing_anim * 2);
410                 f32 bobdir = (m_view_bobbing_anim < 0.5) ? 1.0 : -1.0;
411
412                 #if 1
413                 f32 bobknob = 1.2;
414                 f32 bobtmp = sin(pow(bobfrac, bobknob) * M_PI);
415                 //f32 bobtmp2 = cos(pow(bobfrac, bobknob) * M_PI);
416
417                 v3f bobvec = v3f(
418                         0.3 * bobdir * sin(bobfrac * M_PI),
419                         -0.28 * bobtmp * bobtmp,
420                         0.);
421
422                 //rel_cam_pos += 0.2 * bobvec;
423                 //rel_cam_target += 0.03 * bobvec;
424                 //rel_cam_up.rotateXYBy(0.02 * bobdir * bobtmp * M_PI);
425                 float f = 1.0;
426                 f *= m_cache_view_bobbing_amount;
427                 rel_cam_pos += bobvec * f;
428                 //rel_cam_target += 0.995 * bobvec * f;
429                 rel_cam_target += bobvec * f;
430                 rel_cam_target.Z -= 0.005 * bobvec.Z * f;
431                 //rel_cam_target.X -= 0.005 * bobvec.X * f;
432                 //rel_cam_target.Y -= 0.005 * bobvec.Y * f;
433                 rel_cam_up.rotateXYBy(-0.03 * bobdir * bobtmp * M_PI * f);
434                 #else
435                 f32 angle_deg = 1 * bobdir * sin(bobfrac * M_PI);
436                 f32 angle_rad = angle_deg * M_PI / 180;
437                 f32 r = 0.05;
438                 v3f off = v3f(
439                         r * sin(angle_rad),
440                         r * (cos(angle_rad) - 1),
441                         0);
442                 rel_cam_pos += off;
443                 //rel_cam_target += off;
444                 rel_cam_up.rotateXYBy(angle_deg);
445                 #endif
446
447         }
448
449         // Compute absolute camera position and target
450         m_headnode->getAbsoluteTransformation().transformVect(m_camera_position, rel_cam_pos);
451         m_headnode->getAbsoluteTransformation().rotateVect(m_camera_direction, rel_cam_target - rel_cam_pos);
452
453         v3f abs_cam_up;
454         m_headnode->getAbsoluteTransformation().rotateVect(abs_cam_up, rel_cam_up);
455
456         // Seperate camera position for calculation
457         v3f my_cp = m_camera_position;
458
459         // Reposition the camera for third person view
460         if (m_camera_mode > CAMERA_MODE_FIRST)
461         {
462                 if (m_camera_mode == CAMERA_MODE_THIRD_FRONT)
463                         m_camera_direction *= -1;
464
465                 my_cp.Y += 2;
466
467                 // Calculate new position
468                 bool abort = false;
469                 for (int i = BS; i <= BS * 2.75; i++) {
470                         my_cp.X = m_camera_position.X + m_camera_direction.X * -i;
471                         my_cp.Z = m_camera_position.Z + m_camera_direction.Z * -i;
472                         if (i > 12)
473                                 my_cp.Y = m_camera_position.Y + (m_camera_direction.Y * -i);
474
475                         // Prevent camera positioned inside nodes
476                         const NodeDefManager *nodemgr = m_client->ndef();
477                         MapNode n = m_client->getEnv().getClientMap()
478                                 .getNode(floatToInt(my_cp, BS));
479
480                         const ContentFeatures& features = nodemgr->get(n);
481                         if (features.walkable) {
482                                 my_cp.X += m_camera_direction.X*-1*-BS/2;
483                                 my_cp.Z += m_camera_direction.Z*-1*-BS/2;
484                                 my_cp.Y += m_camera_direction.Y*-1*-BS/2;
485                                 abort = true;
486                                 break;
487                         }
488                 }
489
490                 // If node blocks camera position don't move y to heigh
491                 if (abort && my_cp.Y > player_position.Y+BS*2)
492                         my_cp.Y = player_position.Y+BS*2;
493         }
494
495         // Update offset if too far away from the center of the map
496         m_camera_offset.X += CAMERA_OFFSET_STEP*
497                         (((s16)(my_cp.X/BS) - m_camera_offset.X)/CAMERA_OFFSET_STEP);
498         m_camera_offset.Y += CAMERA_OFFSET_STEP*
499                         (((s16)(my_cp.Y/BS) - m_camera_offset.Y)/CAMERA_OFFSET_STEP);
500         m_camera_offset.Z += CAMERA_OFFSET_STEP*
501                         (((s16)(my_cp.Z/BS) - m_camera_offset.Z)/CAMERA_OFFSET_STEP);
502
503         // Set camera node transformation
504         m_cameranode->setPosition(my_cp-intToFloat(m_camera_offset, BS));
505         m_cameranode->setUpVector(abs_cam_up);
506         // *100.0 helps in large map coordinates
507         m_cameranode->setTarget(my_cp-intToFloat(m_camera_offset, BS) + 100 * m_camera_direction);
508
509         // update the camera position in third-person mode to render blocks behind player
510         // and correctly apply liquid post FX.
511         if (m_camera_mode != CAMERA_MODE_FIRST)
512                 m_camera_position = my_cp;
513
514         /*
515          * Apply server-sent FOV, instantaneous or smooth transition.
516          * If not, check for zoom and set to zoom FOV.
517          * Otherwise, default to m_cache_fov.
518          */
519         if (m_fov_transition_active) {
520                 // Smooth FOV transition
521                 // Dynamically calculate FOV delta based on frametimes
522                 f32 delta = (frametime / m_transition_time) * m_fov_diff;
523                 m_curr_fov_degrees += delta;
524
525                 // Mark transition as complete if target FOV has been reached
526                 if ((m_fov_diff > 0.0f && m_curr_fov_degrees >= m_target_fov_degrees) ||
527                                 (m_fov_diff < 0.0f && m_curr_fov_degrees <= m_target_fov_degrees)) {
528                         m_fov_transition_active = false;
529                         m_curr_fov_degrees = m_target_fov_degrees;
530                 }
531         } else if (m_server_sent_fov) {
532                 // Instantaneous FOV change
533                 m_curr_fov_degrees = m_target_fov_degrees;
534         } else if (player->getPlayerControl().zoom && player->getZoomFOV() > 0.001f) {
535                 // Player requests zoom, apply zoom FOV
536                 m_curr_fov_degrees = player->getZoomFOV();
537         } else {
538                 // Set to client's selected FOV
539                 m_curr_fov_degrees = m_cache_fov;
540         }
541         m_curr_fov_degrees = rangelim(m_curr_fov_degrees, 1.0f, 160.0f);
542
543         // FOV and aspect ratio
544         const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
545         m_aspect = (f32) window_size.X / (f32) window_size.Y;
546         m_fov_y = m_curr_fov_degrees * M_PI / 180.0;
547         // Increase vertical FOV on lower aspect ratios (<16:10)
548         m_fov_y *= core::clamp(sqrt(16./10. / m_aspect), 1.0, 1.4);
549         m_fov_x = 2 * atan(m_aspect * tan(0.5 * m_fov_y));
550         m_cameranode->setAspectRatio(m_aspect);
551         m_cameranode->setFOV(m_fov_y);
552
553         if (m_arm_inertia)
554                 addArmInertia(player->getYaw());
555
556         // Position the wielded item
557         //v3f wield_position = v3f(45, -35, 65);
558         v3f wield_position = v3f(m_wieldmesh_offset.X, m_wieldmesh_offset.Y, 65);
559         //v3f wield_rotation = v3f(-100, 120, -100);
560         v3f wield_rotation = v3f(-100, 120, -100);
561         wield_position.Y += fabs(m_wield_change_timer)*320 - 40;
562         if(m_digging_anim < 0.05 || m_digging_anim > 0.5)
563         {
564                 f32 frac = 1.0;
565                 if(m_digging_anim > 0.5)
566                         frac = 2.0 * (m_digging_anim - 0.5);
567                 // This value starts from 1 and settles to 0
568                 f32 ratiothing = std::pow((1.0f - tool_reload_ratio), 0.5f);
569                 //f32 ratiothing2 = pow(ratiothing, 0.5f);
570                 f32 ratiothing2 = (easeCurve(ratiothing*0.5))*2.0;
571                 wield_position.Y -= frac * 25.0 * pow(ratiothing2, 1.7f);
572                 //wield_position.Z += frac * 5.0 * ratiothing2;
573                 wield_position.X -= frac * 35.0 * pow(ratiothing2, 1.1f);
574                 wield_rotation.Y += frac * 70.0 * pow(ratiothing2, 1.4f);
575                 //wield_rotation.X -= frac * 15.0 * pow(ratiothing2, 1.4f);
576                 //wield_rotation.Z += frac * 15.0 * pow(ratiothing2, 1.0f);
577         }
578         if (m_digging_button != -1)
579         {
580                 f32 digfrac = m_digging_anim;
581                 wield_position.X -= 50 * sin(pow(digfrac, 0.8f) * M_PI);
582                 wield_position.Y += 24 * sin(digfrac * 1.8 * M_PI);
583                 wield_position.Z += 25 * 0.5;
584
585                 // Euler angles are PURE EVIL, so why not use quaternions?
586                 core::quaternion quat_begin(wield_rotation * core::DEGTORAD);
587                 core::quaternion quat_end(v3f(80, 30, 100) * core::DEGTORAD);
588                 core::quaternion quat_slerp;
589                 quat_slerp.slerp(quat_begin, quat_end, sin(digfrac * M_PI));
590                 quat_slerp.toEuler(wield_rotation);
591                 wield_rotation *= core::RADTODEG;
592         } else {
593                 f32 bobfrac = my_modf(m_view_bobbing_anim);
594                 wield_position.X -= sin(bobfrac*M_PI*2.0) * 3.0;
595                 wield_position.Y += sin(my_modf(bobfrac*2.0)*M_PI) * 3.0;
596         }
597         m_wieldnode->setPosition(wield_position);
598         m_wieldnode->setRotation(wield_rotation);
599
600         m_wieldnode->setNodeLightColor(player->light_color);
601
602         // Set render distance
603         updateViewingRange();
604
605         // If the player is walking, swimming, or climbing,
606         // view bobbing is enabled and free_move is off,
607         // start (or continue) the view bobbing animation.
608         const v3f &speed = player->getSpeed();
609         const bool movement_XZ = hypot(speed.X, speed.Z) > BS;
610         const bool movement_Y = fabs(speed.Y) > BS;
611
612         const bool walking = movement_XZ && player->touching_ground;
613         const bool swimming = (movement_XZ || player->swimming_vertical) && player->in_liquid;
614         const bool climbing = movement_Y && player->is_climbing;
615         if ((walking || swimming || climbing) && !flying) {
616                 // Start animation
617                 m_view_bobbing_state = 1;
618                 m_view_bobbing_speed = MYMIN(speed.getLength(), 70);
619         } else if (m_view_bobbing_state == 1) {
620                 // Stop animation
621                 m_view_bobbing_state = 2;
622                 m_view_bobbing_speed = 60;
623         }
624 }
625
626 void Camera::updateViewingRange()
627 {
628         f32 viewing_range = g_settings->getFloat("viewing_range");
629
630         // Ignore near_plane setting on all other platforms to prevent abuse
631 #if ENABLE_GLES
632         m_cameranode->setNearValue(rangelim(
633                 g_settings->getFloat("near_plane"), 0.0f, 0.25f) * BS);
634 #else
635         m_cameranode->setNearValue(0.1f * BS);
636 #endif
637
638         m_draw_control.wanted_range = std::fmin(adjustDist(viewing_range, getFovMax()), 4000);
639         if (m_draw_control.range_all) {
640                 m_cameranode->setFarValue(100000.0);
641                 return;
642         }
643         m_cameranode->setFarValue((viewing_range < 2000) ? 2000 * BS : viewing_range * BS);
644 }
645
646 void Camera::setDigging(s32 button)
647 {
648         if (m_digging_button == -1)
649                 m_digging_button = button;
650 }
651
652 void Camera::wield(const ItemStack &item)
653 {
654         if (item.name != m_wield_item_next.name ||
655                         item.metadata != m_wield_item_next.metadata) {
656                 m_wield_item_next = item;
657                 if (m_wield_change_timer > 0)
658                         m_wield_change_timer = -m_wield_change_timer;
659                 else if (m_wield_change_timer == 0)
660                         m_wield_change_timer = -0.001;
661         }
662 }
663
664 void Camera::drawWieldedTool(irr::core::matrix4* translation)
665 {
666         // Clear Z buffer so that the wielded tool stays in front of world geometry
667         m_wieldmgr->getVideoDriver()->clearBuffers(video::ECBF_DEPTH);
668
669         // Draw the wielded node (in a separate scene manager)
670         scene::ICameraSceneNode* cam = m_wieldmgr->getActiveCamera();
671         cam->setAspectRatio(m_cameranode->getAspectRatio());
672         cam->setFOV(72.0*M_PI/180.0);
673         cam->setNearValue(10);
674         cam->setFarValue(1000);
675         if (translation != NULL)
676         {
677                 irr::core::matrix4 startMatrix = cam->getAbsoluteTransformation();
678                 irr::core::vector3df focusPoint = (cam->getTarget()
679                                 - cam->getAbsolutePosition()).setLength(1)
680                                 + cam->getAbsolutePosition();
681
682                 irr::core::vector3df camera_pos =
683                                 (startMatrix * *translation).getTranslation();
684                 cam->setPosition(camera_pos);
685                 cam->setTarget(focusPoint);
686         }
687         m_wieldmgr->drawAll();
688 }
689
690 void Camera::drawNametags()
691 {
692         core::matrix4 trans = m_cameranode->getProjectionMatrix();
693         trans *= m_cameranode->getViewMatrix();
694
695         gui::IGUIFont *font = g_fontengine->getFont();
696         video::IVideoDriver *driver = RenderingEngine::get_video_driver();
697         v2u32 screensize = driver->getScreenSize();
698
699         for (const Nametag *nametag : m_nametags) {
700                 // Nametags are hidden in GenericCAO::updateNametag()
701
702                 v3f pos = nametag->parent_node->getAbsolutePosition() + nametag->pos * BS;
703                 f32 transformed_pos[4] = { pos.X, pos.Y, pos.Z, 1.0f };
704                 trans.multiplyWith1x4Matrix(transformed_pos);
705                 if (transformed_pos[3] > 0) {
706                         std::wstring nametag_colorless =
707                                 unescape_translate(utf8_to_wide(nametag->text));
708                         core::dimension2d<u32> textsize = font->getDimension(
709                                 nametag_colorless.c_str());
710                         f32 zDiv = transformed_pos[3] == 0.0f ? 1.0f :
711                                 core::reciprocal(transformed_pos[3]);
712                         v2s32 screen_pos;
713                         screen_pos.X = screensize.X *
714                                 (0.5 * transformed_pos[0] * zDiv + 0.5) - textsize.Width / 2;
715                         screen_pos.Y = screensize.Y *
716                                 (0.5 - transformed_pos[1] * zDiv * 0.5) - textsize.Height / 2;
717                         core::rect<s32> size(0, 0, textsize.Width, textsize.Height);
718                         core::rect<s32> bg_size(-2, 0, textsize.Width+2, textsize.Height);
719
720                         auto bgcolor = nametag->getBgColor(m_show_nametag_backgrounds);
721                         if (bgcolor.getAlpha() != 0)
722                                 driver->draw2DRectangle(bgcolor, bg_size + screen_pos);
723
724                         font->draw(
725                                 translate_string(utf8_to_wide(nametag->text)).c_str(),
726                                 size + screen_pos, nametag->textcolor);
727                 }
728         }
729 }
730
731 Nametag *Camera::addNametag(scene::ISceneNode *parent_node,
732                 const std::string &text, video::SColor textcolor,
733                 Optional<video::SColor> bgcolor, const v3f &pos)
734 {
735         Nametag *nametag = new Nametag(parent_node, text, textcolor, bgcolor, pos);
736         m_nametags.push_back(nametag);
737         return nametag;
738 }
739
740 void Camera::removeNametag(Nametag *nametag)
741 {
742         m_nametags.remove(nametag);
743         delete nametag;
744 }