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),
41 updateName("<not set>");
47 delete inventory_backup;
50 void Player::resetInventory()
53 inventory.addList("main", PLAYER_INVENTORY_SIZE);
54 inventory.addList("craft", 9);
55 inventory.addList("craftresult", 1);
58 // Y direction is ignored
59 void Player::accelerate(v3f target_speed, f32 max_increase)
61 v3f d_wanted = target_speed - m_speed;
63 f32 dl_wanted = d_wanted.getLength();
68 v3f d = d_wanted.normalize() * dl;
75 if(m_speed.X < target_speed.X - max_increase)
76 m_speed.X += max_increase;
77 else if(m_speed.X > target_speed.X + max_increase)
78 m_speed.X -= max_increase;
79 else if(m_speed.X < target_speed.X)
80 m_speed.X = target_speed.X;
81 else if(m_speed.X > target_speed.X)
82 m_speed.X = target_speed.X;
84 if(m_speed.Z < target_speed.Z - max_increase)
85 m_speed.Z += max_increase;
86 else if(m_speed.Z > target_speed.Z + max_increase)
87 m_speed.Z -= max_increase;
88 else if(m_speed.Z < target_speed.Z)
89 m_speed.Z = target_speed.Z;
90 else if(m_speed.Z > target_speed.Z)
91 m_speed.Z = target_speed.Z;
95 void Player::serialize(std::ostream &os)
97 // Utilize a Settings object for storing values
99 args.setS32("version", 1);
100 args.set("name", m_name);
101 //args.set("password", m_password);
102 args.setFloat("pitch", m_pitch);
103 args.setFloat("yaw", m_yaw);
104 args.setV3F("position", m_position);
105 args.setBool("craftresult_is_preview", craftresult_is_preview);
106 args.setS32("hp", hp);
110 os<<"PlayerArgsEnd\n";
112 // If actual inventory is backed up due to creative mode, save it
113 // instead of the dummy creative mode inventory
115 inventory_backup->serialize(os);
117 inventory.serialize(os);
120 void Player::deSerialize(std::istream &is)
127 throw SerializationError
128 ("Player::deSerialize(): PlayerArgsEnd not found");
130 std::getline(is, line);
131 std::string trimmedline = trim(line);
132 if(trimmedline == "PlayerArgsEnd")
134 args.parseConfigLine(line);
137 //args.getS32("version");
138 std::string name = args.get("name");
139 updateName(name.c_str());
140 /*std::string password = "";
141 if(args.exists("password"))
142 password = args.get("password");
143 updatePassword(password.c_str());*/
144 m_pitch = args.getFloat("pitch");
145 m_yaw = args.getFloat("yaw");
146 m_position = args.getV3F("position");
148 craftresult_is_preview = args.getBool("craftresult_is_preview");
149 }catch(SettingNotFoundException &e){
150 craftresult_is_preview = true;
153 hp = args.getS32("hp");
154 }catch(SettingNotFoundException &e){
158 std::string sprivs = args.get("privs");
165 std::istringstream ss(sprivs);
168 }catch(SettingNotFoundException &e){
169 privs = PRIV_DEFAULT;
172 inventory.deSerialize(is);
181 RemotePlayer::RemotePlayer(
182 scene::ISceneNode* parent,
183 IrrlichtDevice *device,
185 scene::ISceneNode(parent, (device==NULL)?NULL:device->getSceneManager(), id),
188 m_box = core::aabbox3d<f32>(-BS/2,0,-BS/2,BS/2,BS*2,BS/2);
190 if(parent != NULL && device != NULL)
192 // ISceneNode stores a member called SceneManager
193 scene::ISceneManager* mgr = SceneManager;
194 video::IVideoDriver* driver = mgr->getVideoDriver();
195 gui::IGUIEnvironment* gui = device->getGUIEnvironment();
197 // Add a text node for showing the name
198 wchar_t wname[1] = {0};
199 m_text = mgr->addTextSceneNode(gui->getBuiltInFont(),
200 wname, video::SColor(255,255,255,255), this);
201 m_text->setPosition(v3f(0, (f32)BS*2.1, 0));
203 // Attach a simple mesh to the player for showing an image
204 scene::SMesh *mesh = new scene::SMesh();
206 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
207 video::SColor c(255,255,255,255);
208 video::S3DVertex vertices[4] =
210 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
211 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
212 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
213 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
215 u16 indices[] = {0,1,2,2,3,0};
216 buf->append(vertices, 4, indices, 6);
218 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
219 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
220 buf->getMaterial().setTexture(0, driver->getTexture(getTexturePath("player.png").c_str()));
221 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
222 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
223 //buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
224 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
226 mesh->addMeshBuffer(buf);
230 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
231 video::SColor c(255,255,255,255);
232 video::S3DVertex vertices[4] =
234 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
235 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
236 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
237 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
239 u16 indices[] = {0,1,2,2,3,0};
240 buf->append(vertices, 4, indices, 6);
242 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
243 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
244 buf->getMaterial().setTexture(0, driver->getTexture(getTexturePath("player_back.png").c_str()));
245 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
246 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
247 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
249 mesh->addMeshBuffer(buf);
252 m_node = mgr->addMeshSceneNode(mesh, this);
254 m_node->setPosition(v3f(0,0,0));
258 RemotePlayer::~RemotePlayer()
260 if(SceneManager != NULL)
261 ISceneNode::remove();
264 void RemotePlayer::updateName(const char *name)
266 Player::updateName(name);
269 wchar_t wname[PLAYERNAME_SIZE];
270 mbstowcs(wname, m_name, strlen(m_name)+1);
271 m_text->setText(wname);
275 void RemotePlayer::move(f32 dtime, Map &map, f32 pos_max_d)
277 m_pos_animation_time_counter += dtime;
278 m_pos_animation_counter += dtime;
279 v3f movevector = m_position - m_oldpos;
281 if(m_pos_animation_time < 0.001)
284 moveratio = m_pos_animation_counter / m_pos_animation_time;
287 m_showpos = m_oldpos + movevector * moveratio;
289 ISceneNode::setPosition(m_showpos);
299 LocalPlayer::LocalPlayer():
300 m_sneak_node(32767,32767,32767),
301 m_sneak_node_exists(false)
303 // Initialize hp to 0, so that no hearts will be shown if server
304 // doesn't support health points
308 LocalPlayer::~LocalPlayer()
312 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d,
313 core::list<CollisionInfo> *collision_info)
315 v3f position = getPosition();
316 v3f oldpos = position;
317 v3s16 oldpos_i = floatToInt(oldpos, BS);
319 v3f old_speed = m_speed;
321 /*std::cout<<"oldpos_i=("<<oldpos_i.X<<","<<oldpos_i.Y<<","
322 <<oldpos_i.Z<<")"<<std::endl;*/
325 Calculate new position
327 position += m_speed * dtime;
329 // Skip collision detection if a special movement mode is used
330 bool free_move = g_settings.getBool("free_move");
333 setPosition(position);
341 // Player position in nodes
342 v3s16 pos_i = floatToInt(position, BS);
345 Check if player is in water (the oscillating value)
348 // If in water, the threshold of coming out is at higher y
351 v3s16 pp = floatToInt(position + v3f(0,BS*0.1,0), BS);
352 in_water = content_liquid(map.getNode(pp).getContent());
354 // If not in water, the threshold of going in is at lower y
357 v3s16 pp = floatToInt(position + v3f(0,BS*0.5,0), BS);
358 in_water = content_liquid(map.getNode(pp).getContent());
361 catch(InvalidPositionException &e)
367 Check if player is in water (the stable value)
370 v3s16 pp = floatToInt(position + v3f(0,0,0), BS);
371 in_water_stable = content_liquid(map.getNode(pp).getContent());
373 catch(InvalidPositionException &e)
375 in_water_stable = false;
379 Collision uncertainty radius
380 Make it a bit larger than the maximum distance of movement
382 //f32 d = pos_max_d * 1.1;
383 // A fairly large value in here makes moving smoother
386 // This should always apply, otherwise there are glitches
387 assert(d > pos_max_d);
389 float player_radius = BS*0.35;
390 float player_height = BS*1.7;
392 // Maximum distance over border for sneaking
393 f32 sneak_max = BS*0.4;
396 If sneaking, player has larger collision radius to keep from
400 player_radius = sneak_max + d*1.1;*/
403 If sneaking, keep in range from the last walked node and don't
406 if(control.sneak && m_sneak_node_exists)
408 f32 maxd = 0.5*BS + sneak_max;
409 v3f lwn_f = intToFloat(m_sneak_node, BS);
410 position.X = rangelim(position.X, lwn_f.X-maxd, lwn_f.X+maxd);
411 position.Z = rangelim(position.Z, lwn_f.Z-maxd, lwn_f.Z+maxd);
413 f32 min_y = lwn_f.Y + 0.5*BS;
414 if(position.Y < min_y)
418 //v3f old_speed = m_speed;
425 // Report fall collision
426 if(old_speed.Y < m_speed.Y - 0.1)
429 info.t = COLLISION_FALL;
430 info.speed = m_speed.Y - old_speed.Y;
431 collision_info->push_back(info);
438 Calculate player collision box (new and old)
440 core::aabbox3d<f32> playerbox(
441 position.X - player_radius,
443 position.Z - player_radius,
444 position.X + player_radius,
445 position.Y + player_height,
446 position.Z + player_radius
448 core::aabbox3d<f32> playerbox_old(
449 oldpos.X - player_radius,
451 oldpos.Z - player_radius,
452 oldpos.X + player_radius,
453 oldpos.Y + player_height,
454 oldpos.Z + player_radius
458 If the player's feet touch the topside of any node, this is
461 Player is allowed to jump when this is true.
463 touching_ground = false;
465 /*std::cout<<"Checking collisions for ("
466 <<oldpos_i.X<<","<<oldpos_i.Y<<","<<oldpos_i.Z
468 <<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z
472 Go through every node around the player
474 for(s16 y = oldpos_i.Y - 1; y <= oldpos_i.Y + 2; y++)
475 for(s16 z = oldpos_i.Z - 1; z <= oldpos_i.Z + 1; z++)
476 for(s16 x = oldpos_i.X - 1; x <= oldpos_i.X + 1; x++)
479 // Player collides into walkable nodes
480 if(content_walkable(map.getNode(v3s16(x,y,z)).getContent()) == false)
483 catch(InvalidPositionException &e)
485 // Doing nothing here will block the player from
486 // walking over map borders
489 core::aabbox3d<f32> nodebox = getNodeBox(v3s16(x,y,z), BS);
492 See if the player is touching ground.
494 Player touches ground if player's minimum Y is near node's
495 maximum Y and player's X-Z-area overlaps with the node's
498 Use 0.15*BS so that it is easier to get on a node.
501 //fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < d
502 fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < 0.15*BS
503 && nodebox.MaxEdge.X-d > playerbox.MinEdge.X
504 && nodebox.MinEdge.X+d < playerbox.MaxEdge.X
505 && nodebox.MaxEdge.Z-d > playerbox.MinEdge.Z
506 && nodebox.MinEdge.Z+d < playerbox.MaxEdge.Z
508 touching_ground = true;
511 // If player doesn't intersect with node, ignore node.
512 if(playerbox.intersectsWithBox(nodebox) == false)
516 Go through every axis
519 v3f(0,0,1), // back-front
520 v3f(0,1,0), // top-bottom
521 v3f(1,0,0), // right-left
523 for(u16 i=0; i<3; i++)
526 Calculate values along the axis
528 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[i]);
529 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[i]);
530 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[i]);
531 f32 playermin = playerbox.MinEdge.dotProduct(dirs[i]);
532 f32 playermax_old = playerbox_old.MaxEdge.dotProduct(dirs[i]);
533 f32 playermin_old = playerbox_old.MinEdge.dotProduct(dirs[i]);
536 Check collision for the axis.
537 Collision happens when player is going through a surface.
541 // Make it easier to get on top of a node
544 bool negative_axis_collides =
545 (nodemax > playermin && nodemax <= playermin_old + neg_d
546 && m_speed.dotProduct(dirs[i]) < 0);
547 bool positive_axis_collides =
548 (nodemin < playermax && nodemin >= playermax_old - pos_d
549 && m_speed.dotProduct(dirs[i]) > 0);*/
550 bool negative_axis_collides =
551 (nodemax > playermin && nodemax <= playermin_old + d
552 && m_speed.dotProduct(dirs[i]) < 0);
553 bool positive_axis_collides =
554 (nodemin < playermax && nodemin >= playermax_old - d
555 && m_speed.dotProduct(dirs[i]) > 0);
556 bool main_axis_collides =
557 negative_axis_collides || positive_axis_collides;
560 Check overlap of player and node in other axes
562 bool other_axes_overlap = true;
563 for(u16 j=0; j<3; j++)
567 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[j]);
568 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[j]);
569 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[j]);
570 f32 playermin = playerbox.MinEdge.dotProduct(dirs[j]);
571 if(!(nodemax - d > playermin && nodemin + d < playermax))
573 other_axes_overlap = false;
579 If this is a collision, revert the position in the main
582 if(other_axes_overlap && main_axis_collides)
584 //v3f old_speed = m_speed;
586 m_speed -= m_speed.dotProduct(dirs[i]) * dirs[i];
587 position -= position.dotProduct(dirs[i]) * dirs[i];
588 position += oldpos.dotProduct(dirs[i]) * dirs[i];
592 // Report fall collision
593 if(old_speed.Y < m_speed.Y - 0.1)
596 info.t = COLLISION_FALL;
597 info.speed = m_speed.Y - old_speed.Y;
598 collision_info->push_back(info);
607 Check the nodes under the player to see from which node the
608 player is sneaking from, if any.
611 v3s16 pos_i_bottom = floatToInt(position - v3f(0,BS/2,0), BS);
612 v2f player_p2df(position.X, position.Z);
613 f32 min_distance_f = 100000.0*BS;
614 // If already seeking from some node, compare to it.
615 /*if(m_sneak_node_exists)
617 v3f sneaknode_pf = intToFloat(m_sneak_node, BS);
618 v2f sneaknode_p2df(sneaknode_pf.X, sneaknode_pf.Z);
619 f32 d_horiz_f = player_p2df.getDistanceFrom(sneaknode_p2df);
620 f32 d_vert_f = fabs(sneaknode_pf.Y + BS*0.5 - position.Y);
621 // Ignore if player is not on the same level (likely dropped)
622 if(d_vert_f < 0.15*BS)
623 min_distance_f = d_horiz_f;
625 v3s16 new_sneak_node = m_sneak_node;
626 for(s16 x=-1; x<=1; x++)
627 for(s16 z=-1; z<=1; z++)
629 v3s16 p = pos_i_bottom + v3s16(x,0,z);
630 v3f pf = intToFloat(p, BS);
631 v2f node_p2df(pf.X, pf.Z);
632 f32 distance_f = player_p2df.getDistanceFrom(node_p2df);
633 f32 max_axis_distance_f = MYMAX(
634 fabs(player_p2df.X-node_p2df.X),
635 fabs(player_p2df.Y-node_p2df.Y));
637 if(distance_f > min_distance_f ||
638 max_axis_distance_f > 0.5*BS + sneak_max + 0.1*BS)
642 // The node to be sneaked on has to be walkable
643 if(content_walkable(map.getNode(p).getContent()) == false)
645 // And the node above it has to be nonwalkable
646 if(content_walkable(map.getNode(p+v3s16(0,1,0)).getContent()) == true)
649 catch(InvalidPositionException &e)
654 min_distance_f = distance_f;
658 bool sneak_node_found = (min_distance_f < 100000.0*BS*0.9);
660 if(control.sneak && m_sneak_node_exists)
663 m_sneak_node = new_sneak_node;
667 m_sneak_node = new_sneak_node;
668 m_sneak_node_exists = sneak_node_found;
672 If sneaking, the player's collision box can be in air, so
673 this has to be set explicitly
675 if(sneak_node_found && control.sneak)
676 touching_ground = true;
682 setPosition(position);
689 // Report fall collision
690 if(old_speed.Y < m_speed.Y - 0.1)
693 info.t = COLLISION_FALL;
694 info.speed = m_speed.Y - old_speed.Y;
695 collision_info->push_back(info);
700 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d)
702 move(dtime, map, pos_max_d, NULL);
705 void LocalPlayer::applyControl(float dtime)
711 f32 walk_acceleration = 4.0 * BS;
712 f32 walkspeed_max = 4.0 * BS;
714 setPitch(control.pitch);
717 v3f move_direction = v3f(0,0,1);
718 move_direction.rotateXZBy(getYaw());
720 v3f speed = v3f(0,0,0);
722 bool free_move = g_settings.getBool("free_move");
723 bool fast_move = g_settings.getBool("fast_move");
724 bool continuous_forward = g_settings.getBool("continuous_forward");
728 v3f speed = getSpeed();
733 // Whether superspeed mode is used or not
734 bool superspeed = false;
736 // If free movement and fast movement, always move fast
737 if(free_move && fast_move)
740 // Auxiliary button 1 (E)
745 // In free movement mode, aux1 descends
746 v3f speed = getSpeed();
750 speed.Y = -walkspeed_max;
755 // If not free movement but fast is allowed, aux1 is
762 if(continuous_forward)
763 speed += move_direction;
767 if(continuous_forward)
770 speed += move_direction;
774 speed -= move_direction;
778 speed += move_direction.crossProduct(v3f(0,1,0));
782 speed += move_direction.crossProduct(v3f(0,-1,0));
788 v3f speed = getSpeed();
792 speed.Y = walkspeed_max;
795 else if(touching_ground)
797 v3f speed = getSpeed();
799 NOTE: The d value in move() affects jump height by
800 raising the height at which the jump speed is kept
801 at its starting value
806 // Use the oscillating value for getting out of water
807 // (so that the player doesn't fly on the surface)
810 v3f speed = getSpeed();
817 // The speed of the player (Y is ignored)
819 speed = speed.normalize() * walkspeed_max * 5.0;
820 else if(control.sneak)
821 speed = speed.normalize() * walkspeed_max / 3.0;
823 speed = speed.normalize() * walkspeed_max;
825 f32 inc = walk_acceleration * BS * dtime;
827 // Faster acceleration if fast and free movement
828 if(free_move && fast_move)
829 inc = walk_acceleration * BS * dtime * 10;
831 // Accelerate to target speed with maximum increment
832 accelerate(speed, inc);