3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
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 General Public License for more details.
15 You should have received a copy of the GNU 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.
22 #include "connection.h"
23 #include "constants.h"
28 touching_ground(false),
30 in_water_stable(false),
32 inventory_backup(NULL),
33 craftresult_is_preview(true),
35 peer_id(PEER_ID_INEXISTENT),
42 updateName("<not set>");
48 delete inventory_backup;
51 void Player::wieldItem(u16 item)
53 m_selected_item = item;
56 void Player::resetInventory()
59 inventory.addList("main", PLAYER_INVENTORY_SIZE);
60 inventory.addList("craft", 9);
61 inventory.addList("craftresult", 1);
64 // Y direction is ignored
65 void Player::accelerate(v3f target_speed, f32 max_increase)
67 v3f d_wanted = target_speed - m_speed;
69 f32 dl_wanted = d_wanted.getLength();
74 v3f d = d_wanted.normalize() * dl;
81 if(m_speed.X < target_speed.X - max_increase)
82 m_speed.X += max_increase;
83 else if(m_speed.X > target_speed.X + max_increase)
84 m_speed.X -= max_increase;
85 else if(m_speed.X < target_speed.X)
86 m_speed.X = target_speed.X;
87 else if(m_speed.X > target_speed.X)
88 m_speed.X = target_speed.X;
90 if(m_speed.Z < target_speed.Z - max_increase)
91 m_speed.Z += max_increase;
92 else if(m_speed.Z > target_speed.Z + max_increase)
93 m_speed.Z -= max_increase;
94 else if(m_speed.Z < target_speed.Z)
95 m_speed.Z = target_speed.Z;
96 else if(m_speed.Z > target_speed.Z)
97 m_speed.Z = target_speed.Z;
101 void Player::serialize(std::ostream &os)
103 // Utilize a Settings object for storing values
105 args.setS32("version", 1);
106 args.set("name", m_name);
107 //args.set("password", m_password);
108 args.setFloat("pitch", m_pitch);
109 args.setFloat("yaw", m_yaw);
110 args.setV3F("position", m_position);
111 args.setBool("craftresult_is_preview", craftresult_is_preview);
112 args.setS32("hp", hp);
116 os<<"PlayerArgsEnd\n";
118 // If actual inventory is backed up due to creative mode, save it
119 // instead of the dummy creative mode inventory
121 inventory_backup->serialize(os);
123 inventory.serialize(os);
126 void Player::deSerialize(std::istream &is)
133 throw SerializationError
134 ("Player::deSerialize(): PlayerArgsEnd not found");
136 std::getline(is, line);
137 std::string trimmedline = trim(line);
138 if(trimmedline == "PlayerArgsEnd")
140 args.parseConfigLine(line);
143 //args.getS32("version");
144 std::string name = args.get("name");
145 updateName(name.c_str());
146 /*std::string password = "";
147 if(args.exists("password"))
148 password = args.get("password");
149 updatePassword(password.c_str());*/
150 m_pitch = args.getFloat("pitch");
151 m_yaw = args.getFloat("yaw");
152 m_position = args.getV3F("position");
154 craftresult_is_preview = args.getBool("craftresult_is_preview");
155 }catch(SettingNotFoundException &e){
156 craftresult_is_preview = true;
159 hp = args.getS32("hp");
160 }catch(SettingNotFoundException &e){
164 std::string sprivs = args.get("privs");
171 std::istringstream ss(sprivs);
174 }catch(SettingNotFoundException &e){
175 privs = PRIV_DEFAULT;
178 inventory.deSerialize(is);
187 RemotePlayer::RemotePlayer(
188 scene::ISceneNode* parent,
189 IrrlichtDevice *device,
191 scene::ISceneNode(parent, (device==NULL)?NULL:device->getSceneManager(), id),
194 m_box = core::aabbox3d<f32>(-BS/2,0,-BS/2,BS/2,BS*2,BS/2);
196 if(parent != NULL && device != NULL)
198 // ISceneNode stores a member called SceneManager
199 scene::ISceneManager* mgr = SceneManager;
200 video::IVideoDriver* driver = mgr->getVideoDriver();
201 gui::IGUIEnvironment* gui = device->getGUIEnvironment();
203 // Add a text node for showing the name
204 wchar_t wname[1] = {0};
205 m_text = mgr->addTextSceneNode(gui->getBuiltInFont(),
206 wname, video::SColor(255,255,255,255), this);
207 m_text->setPosition(v3f(0, (f32)BS*2.1, 0));
209 // Attach a simple mesh to the player for showing an image
210 scene::SMesh *mesh = new scene::SMesh();
212 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
213 video::SColor c(255,255,255,255);
214 video::S3DVertex vertices[4] =
216 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
217 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
218 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
219 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
221 u16 indices[] = {0,1,2,2,3,0};
222 buf->append(vertices, 4, indices, 6);
224 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
225 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
226 buf->getMaterial().setTexture(0, driver->getTexture(getTexturePath("player.png").c_str()));
227 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
228 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
229 //buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
230 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
232 mesh->addMeshBuffer(buf);
236 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
237 video::SColor c(255,255,255,255);
238 video::S3DVertex vertices[4] =
240 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
241 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
242 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
243 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
245 u16 indices[] = {0,1,2,2,3,0};
246 buf->append(vertices, 4, indices, 6);
248 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
249 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
250 buf->getMaterial().setTexture(0, driver->getTexture(getTexturePath("player_back.png").c_str()));
251 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
252 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
253 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
255 mesh->addMeshBuffer(buf);
258 m_node = mgr->addMeshSceneNode(mesh, this);
260 m_node->setPosition(v3f(0,0,0));
264 RemotePlayer::~RemotePlayer()
266 if(SceneManager != NULL)
267 ISceneNode::remove();
270 void RemotePlayer::updateName(const char *name)
272 Player::updateName(name);
275 wchar_t wname[PLAYERNAME_SIZE];
276 mbstowcs(wname, m_name, strlen(m_name)+1);
277 m_text->setText(wname);
281 void RemotePlayer::move(f32 dtime, Map &map, f32 pos_max_d)
283 m_pos_animation_time_counter += dtime;
284 m_pos_animation_counter += dtime;
285 v3f movevector = m_position - m_oldpos;
287 if(m_pos_animation_time < 0.001)
290 moveratio = m_pos_animation_counter / m_pos_animation_time;
293 m_showpos = m_oldpos + movevector * moveratio;
295 ISceneNode::setPosition(m_showpos);
305 LocalPlayer::LocalPlayer():
306 m_sneak_node(32767,32767,32767),
307 m_sneak_node_exists(false)
309 // Initialize hp to 0, so that no hearts will be shown if server
310 // doesn't support health points
314 LocalPlayer::~LocalPlayer()
318 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d,
319 core::list<CollisionInfo> *collision_info)
321 v3f position = getPosition();
322 v3f oldpos = position;
323 v3s16 oldpos_i = floatToInt(oldpos, BS);
325 v3f old_speed = m_speed;
327 /*std::cout<<"oldpos_i=("<<oldpos_i.X<<","<<oldpos_i.Y<<","
328 <<oldpos_i.Z<<")"<<std::endl;*/
331 Calculate new position
334 // Still move very slowly so as not to feel all completely stuck
335 position += m_speed * dtime * 0.001;
338 position += m_speed * dtime;
342 If the player enters an unloaded chunk this is set to true.
346 // Skip collision detection if a special movement mode is used
347 bool free_move = g_settings.getBool("free_move");
350 setPosition(position);
358 // Player position in nodes
359 v3s16 pos_i = floatToInt(position, BS);
362 Check if player is in water (the oscillating value)
365 // If in water, the threshold of coming out is at higher y
368 v3s16 pp = floatToInt(position + v3f(0,BS*0.1,0), BS);
369 in_water = content_liquid(map.getNode(pp).getContent());
371 // If not in water, the threshold of going in is at lower y
374 v3s16 pp = floatToInt(position + v3f(0,BS*0.5,0), BS);
375 in_water = content_liquid(map.getNode(pp).getContent());
378 catch(InvalidPositionException &e)
384 Check if player is in water (the stable value)
387 v3s16 pp = floatToInt(position + v3f(0,0,0), BS);
388 in_water_stable = content_liquid(map.getNode(pp).getContent());
390 catch(InvalidPositionException &e)
392 in_water_stable = false;
396 Check if player is climbing
400 v3s16 pp = floatToInt(position + v3f(0,0.5*BS,0), BS);
401 v3s16 pp2 = floatToInt(position + v3f(0,-0.2*BS,0), BS);
402 is_climbing = ((content_features(map.getNode(pp).getContent()).climbable ||
403 content_features(map.getNode(pp2).getContent()).climbable) && !free_move);
405 catch(InvalidPositionException &e)
411 Collision uncertainty radius
412 Make it a bit larger than the maximum distance of movement
414 //f32 d = pos_max_d * 1.1;
415 // A fairly large value in here makes moving smoother
418 // This should always apply, otherwise there are glitches
419 assert(d > pos_max_d);
421 float player_radius = BS*0.35;
422 float player_height = BS*1.7;
424 // Maximum distance over border for sneaking
425 f32 sneak_max = BS*0.4;
428 If sneaking, player has larger collision radius to keep from
432 player_radius = sneak_max + d*1.1;*/
435 If sneaking, keep in range from the last walked node and don't
438 if(control.sneak && m_sneak_node_exists)
440 f32 maxd = 0.5*BS + sneak_max;
441 v3f lwn_f = intToFloat(m_sneak_node, BS);
442 position.X = rangelim(position.X, lwn_f.X-maxd, lwn_f.X+maxd);
443 position.Z = rangelim(position.Z, lwn_f.Z-maxd, lwn_f.Z+maxd);
445 f32 min_y = lwn_f.Y + 0.5*BS;
446 if(position.Y < min_y)
450 //v3f old_speed = m_speed;
457 // Report fall collision
458 if(old_speed.Y < m_speed.Y - 0.1)
461 info.t = COLLISION_FALL;
462 info.speed = m_speed.Y - old_speed.Y;
463 collision_info->push_back(info);
470 Calculate player collision box (new and old)
472 core::aabbox3d<f32> playerbox(
473 position.X - player_radius,
475 position.Z - player_radius,
476 position.X + player_radius,
477 position.Y + player_height,
478 position.Z + player_radius
480 core::aabbox3d<f32> playerbox_old(
481 oldpos.X - player_radius,
483 oldpos.Z - player_radius,
484 oldpos.X + player_radius,
485 oldpos.Y + player_height,
486 oldpos.Z + player_radius
490 If the player's feet touch the topside of any node, this is
493 Player is allowed to jump when this is true.
495 touching_ground = false;
497 /*std::cout<<"Checking collisions for ("
498 <<oldpos_i.X<<","<<oldpos_i.Y<<","<<oldpos_i.Z
500 <<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z
504 Go through every node around the player
506 for(s16 y = oldpos_i.Y - 1; y <= oldpos_i.Y + 2; y++)
507 for(s16 z = oldpos_i.Z - 1; z <= oldpos_i.Z + 1; z++)
508 for(s16 x = oldpos_i.X - 1; x <= oldpos_i.X + 1; x++)
511 // Player collides into walkable nodes
512 if(content_walkable(map.getNode(v3s16(x,y,z)).getContent()) == false)
515 catch(InvalidPositionException &e)
518 // freeze when entering unloaded areas
524 core::aabbox3d<f32> nodebox = getNodeBox(v3s16(x,y,z), BS);
527 See if the player is touching ground.
529 Player touches ground if player's minimum Y is near node's
530 maximum Y and player's X-Z-area overlaps with the node's
533 Use 0.15*BS so that it is easier to get on a node.
536 //fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < d
537 fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < 0.15*BS
538 && nodebox.MaxEdge.X-d > playerbox.MinEdge.X
539 && nodebox.MinEdge.X+d < playerbox.MaxEdge.X
540 && nodebox.MaxEdge.Z-d > playerbox.MinEdge.Z
541 && nodebox.MinEdge.Z+d < playerbox.MaxEdge.Z
543 touching_ground = true;
546 // If player doesn't intersect with node, ignore node.
547 if(playerbox.intersectsWithBox(nodebox) == false)
551 Go through every axis
554 v3f(0,0,1), // back-front
555 v3f(0,1,0), // top-bottom
556 v3f(1,0,0), // right-left
558 for(u16 i=0; i<3; i++)
561 Calculate values along the axis
563 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[i]);
564 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[i]);
565 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[i]);
566 f32 playermin = playerbox.MinEdge.dotProduct(dirs[i]);
567 f32 playermax_old = playerbox_old.MaxEdge.dotProduct(dirs[i]);
568 f32 playermin_old = playerbox_old.MinEdge.dotProduct(dirs[i]);
571 Check collision for the axis.
572 Collision happens when player is going through a surface.
576 // Make it easier to get on top of a node
579 bool negative_axis_collides =
580 (nodemax > playermin && nodemax <= playermin_old + neg_d
581 && m_speed.dotProduct(dirs[i]) < 0);
582 bool positive_axis_collides =
583 (nodemin < playermax && nodemin >= playermax_old - pos_d
584 && m_speed.dotProduct(dirs[i]) > 0);*/
585 bool negative_axis_collides =
586 (nodemax > playermin && nodemax <= playermin_old + d
587 && m_speed.dotProduct(dirs[i]) < 0);
588 bool positive_axis_collides =
589 (nodemin < playermax && nodemin >= playermax_old - d
590 && m_speed.dotProduct(dirs[i]) > 0);
591 bool main_axis_collides =
592 negative_axis_collides || positive_axis_collides;
595 Check overlap of player and node in other axes
597 bool other_axes_overlap = true;
598 for(u16 j=0; j<3; j++)
602 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[j]);
603 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[j]);
604 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[j]);
605 f32 playermin = playerbox.MinEdge.dotProduct(dirs[j]);
606 if(!(nodemax - d > playermin && nodemin + d < playermax))
608 other_axes_overlap = false;
614 If this is a collision, revert the position in the main
617 if(other_axes_overlap && main_axis_collides)
619 //v3f old_speed = m_speed;
621 m_speed -= m_speed.dotProduct(dirs[i]) * dirs[i];
622 position -= position.dotProduct(dirs[i]) * dirs[i];
623 position += oldpos.dotProduct(dirs[i]) * dirs[i];
627 // Report fall collision
628 if(old_speed.Y < m_speed.Y - 0.1)
631 info.t = COLLISION_FALL;
632 info.speed = m_speed.Y - old_speed.Y;
633 collision_info->push_back(info);
642 Check the nodes under the player to see from which node the
643 player is sneaking from, if any.
646 v3s16 pos_i_bottom = floatToInt(position - v3f(0,BS/2,0), BS);
647 v2f player_p2df(position.X, position.Z);
648 f32 min_distance_f = 100000.0*BS;
649 // If already seeking from some node, compare to it.
650 /*if(m_sneak_node_exists)
652 v3f sneaknode_pf = intToFloat(m_sneak_node, BS);
653 v2f sneaknode_p2df(sneaknode_pf.X, sneaknode_pf.Z);
654 f32 d_horiz_f = player_p2df.getDistanceFrom(sneaknode_p2df);
655 f32 d_vert_f = fabs(sneaknode_pf.Y + BS*0.5 - position.Y);
656 // Ignore if player is not on the same level (likely dropped)
657 if(d_vert_f < 0.15*BS)
658 min_distance_f = d_horiz_f;
660 v3s16 new_sneak_node = m_sneak_node;
661 for(s16 x=-1; x<=1; x++)
662 for(s16 z=-1; z<=1; z++)
664 v3s16 p = pos_i_bottom + v3s16(x,0,z);
665 v3f pf = intToFloat(p, BS);
666 v2f node_p2df(pf.X, pf.Z);
667 f32 distance_f = player_p2df.getDistanceFrom(node_p2df);
668 f32 max_axis_distance_f = MYMAX(
669 fabs(player_p2df.X-node_p2df.X),
670 fabs(player_p2df.Y-node_p2df.Y));
672 if(distance_f > min_distance_f ||
673 max_axis_distance_f > 0.5*BS + sneak_max + 0.1*BS)
677 // The node to be sneaked on has to be walkable
678 if(content_walkable(map.getNode(p).getContent()) == false)
680 // And the node above it has to be nonwalkable
681 if(content_walkable(map.getNode(p+v3s16(0,1,0)).getContent()) == true)
684 catch(InvalidPositionException &e)
689 min_distance_f = distance_f;
693 bool sneak_node_found = (min_distance_f < 100000.0*BS*0.9);
695 if(control.sneak && m_sneak_node_exists)
698 m_sneak_node = new_sneak_node;
702 m_sneak_node = new_sneak_node;
703 m_sneak_node_exists = sneak_node_found;
707 If sneaking, the player's collision box can be in air, so
708 this has to be set explicitly
710 if(sneak_node_found && control.sneak)
711 touching_ground = true;
717 setPosition(position);
724 // Report fall collision
725 if(old_speed.Y < m_speed.Y - 0.1)
728 info.t = COLLISION_FALL;
729 info.speed = m_speed.Y - old_speed.Y;
730 collision_info->push_back(info);
735 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d)
737 move(dtime, map, pos_max_d, NULL);
740 void LocalPlayer::applyControl(float dtime)
746 f32 walk_acceleration = 4.0 * BS;
747 f32 walkspeed_max = 4.0 * BS;
749 setPitch(control.pitch);
752 v3f move_direction = v3f(0,0,1);
753 move_direction.rotateXZBy(getYaw());
755 v3f speed = v3f(0,0,0);
757 bool free_move = g_settings.getBool("free_move");
758 bool fast_move = g_settings.getBool("fast_move");
759 bool continuous_forward = g_settings.getBool("continuous_forward");
761 if(free_move || is_climbing)
763 v3f speed = getSpeed();
768 // Whether superspeed mode is used or not
769 bool superspeed = false;
771 // If free movement and fast movement, always move fast
772 if(free_move && fast_move)
775 // Auxiliary button 1 (E)
780 // In free movement mode, aux1 descends
781 v3f speed = getSpeed();
785 speed.Y = -walkspeed_max;
790 v3f speed = getSpeed();
796 // If not free movement but fast is allowed, aux1 is
803 if(continuous_forward)
804 speed += move_direction;
808 if(continuous_forward)
811 speed += move_direction;
815 speed -= move_direction;
819 speed += move_direction.crossProduct(v3f(0,1,0));
823 speed += move_direction.crossProduct(v3f(0,-1,0));
829 v3f speed = getSpeed();
833 speed.Y = walkspeed_max;
836 else if(touching_ground)
838 v3f speed = getSpeed();
840 NOTE: The d value in move() affects jump height by
841 raising the height at which the jump speed is kept
842 at its starting value
847 // Use the oscillating value for getting out of water
848 // (so that the player doesn't fly on the surface)
851 v3f speed = getSpeed();
858 v3f speed = getSpeed();
864 // The speed of the player (Y is ignored)
866 speed = speed.normalize() * walkspeed_max * 5.0;
867 else if(control.sneak)
868 speed = speed.normalize() * walkspeed_max / 3.0;
870 speed = speed.normalize() * walkspeed_max;
872 f32 inc = walk_acceleration * BS * dtime;
874 // Faster acceleration if fast and free movement
875 if(free_move && fast_move)
876 inc = walk_acceleration * BS * dtime * 10;
878 // Accelerate to target speed with maximum increment
879 accelerate(speed, inc);