3 Copyright (C) 2010 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.
21 (c) 2010 Perttu Ahola <celeron55@gmail.com>
26 #include "connection.h"
27 #include "constants.h"
31 touching_ground(false),
33 in_water_stable(false),
35 craftresult_is_preview(true),
37 peer_id(PEER_ID_INEXISTENT),
43 updateName("<not set>");
51 void Player::resetInventory()
54 inventory.addList("main", PLAYER_INVENTORY_SIZE);
55 inventory.addList("craft", 9);
56 inventory.addList("craftresult", 1);
59 // Y direction is ignored
60 void Player::accelerate(v3f target_speed, f32 max_increase)
62 v3f d_wanted = target_speed - m_speed;
64 f32 dl_wanted = d_wanted.getLength();
69 v3f d = d_wanted.normalize() * dl;
76 if(m_speed.X < target_speed.X - max_increase)
77 m_speed.X += max_increase;
78 else if(m_speed.X > target_speed.X + max_increase)
79 m_speed.X -= max_increase;
80 else if(m_speed.X < target_speed.X)
81 m_speed.X = target_speed.X;
82 else if(m_speed.X > target_speed.X)
83 m_speed.X = target_speed.X;
85 if(m_speed.Z < target_speed.Z - max_increase)
86 m_speed.Z += max_increase;
87 else if(m_speed.Z > target_speed.Z + max_increase)
88 m_speed.Z -= max_increase;
89 else if(m_speed.Z < target_speed.Z)
90 m_speed.Z = target_speed.Z;
91 else if(m_speed.Z > target_speed.Z)
92 m_speed.Z = target_speed.Z;
96 void Player::serialize(std::ostream &os)
98 // Utilize a Settings object for storing values
100 args.setS32("version", 1);
101 args.set("name", m_name);
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 inventory.serialize(os);
115 void Player::deSerialize(std::istream &is)
122 throw SerializationError
123 ("Player::deSerialize(): PlayerArgsEnd not found");
125 std::getline(is, line);
126 std::string trimmedline = trim(line);
127 if(trimmedline == "PlayerArgsEnd")
129 args.parseConfigLine(line);
132 //args.getS32("version");
133 std::string name = args.get("name");
134 updateName(name.c_str());
135 m_pitch = args.getFloat("pitch");
136 m_yaw = args.getFloat("yaw");
137 m_position = args.getV3F("position");
139 craftresult_is_preview = args.getBool("craftresult_is_preview");
140 }catch(SettingNotFoundException &e){
141 craftresult_is_preview = true;
144 hp = args.getS32("hp");
145 }catch(SettingNotFoundException &e){
149 inventory.deSerialize(is);
158 RemotePlayer::RemotePlayer(
159 scene::ISceneNode* parent,
160 IrrlichtDevice *device,
162 scene::ISceneNode(parent, (device==NULL)?NULL:device->getSceneManager(), id),
165 m_box = core::aabbox3d<f32>(-BS/2,0,-BS/2,BS/2,BS*2,BS/2);
167 if(parent != NULL && device != NULL)
169 // ISceneNode stores a member called SceneManager
170 scene::ISceneManager* mgr = SceneManager;
171 video::IVideoDriver* driver = mgr->getVideoDriver();
172 gui::IGUIEnvironment* gui = device->getGUIEnvironment();
174 // Add a text node for showing the name
175 wchar_t wname[1] = {0};
176 m_text = mgr->addTextSceneNode(gui->getBuiltInFont(),
177 wname, video::SColor(255,255,255,255), this);
178 m_text->setPosition(v3f(0, (f32)BS*2.1, 0));
180 // Attach a simple mesh to the player for showing an image
181 scene::SMesh *mesh = new scene::SMesh();
183 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
184 video::SColor c(255,255,255,255);
185 video::S3DVertex vertices[4] =
187 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
188 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
189 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
190 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
192 u16 indices[] = {0,1,2,2,3,0};
193 buf->append(vertices, 4, indices, 6);
195 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
196 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
197 buf->getMaterial().setTexture(0, driver->getTexture(porting::getDataPath("player.png").c_str()));
198 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
199 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
200 //buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
201 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
203 mesh->addMeshBuffer(buf);
207 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
208 video::SColor c(255,255,255,255);
209 video::S3DVertex vertices[4] =
211 video::S3DVertex(BS/2,0,0, 0,0,0, c, 1,1),
212 video::S3DVertex(-BS/2,0,0, 0,0,0, c, 0,1),
213 video::S3DVertex(-BS/2,BS*2,0, 0,0,0, c, 0,0),
214 video::S3DVertex(BS/2,BS*2,0, 0,0,0, c, 1,0),
216 u16 indices[] = {0,1,2,2,3,0};
217 buf->append(vertices, 4, indices, 6);
219 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
220 //buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
221 buf->getMaterial().setTexture(0, driver->getTexture(porting::getDataPath("player_back.png").c_str()));
222 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
223 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
224 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
226 mesh->addMeshBuffer(buf);
229 m_node = mgr->addMeshSceneNode(mesh, this);
231 m_node->setPosition(v3f(0,0,0));
235 RemotePlayer::~RemotePlayer()
237 if(SceneManager != NULL)
238 ISceneNode::remove();
241 void RemotePlayer::updateName(const char *name)
243 Player::updateName(name);
246 wchar_t wname[PLAYERNAME_SIZE];
247 mbstowcs(wname, m_name, strlen(m_name)+1);
248 m_text->setText(wname);
252 void RemotePlayer::move(f32 dtime, Map &map, f32 pos_max_d)
254 m_pos_animation_time_counter += dtime;
255 m_pos_animation_counter += dtime;
256 v3f movevector = m_position - m_oldpos;
258 if(m_pos_animation_time < 0.001)
261 moveratio = m_pos_animation_counter / m_pos_animation_time;
264 m_showpos = m_oldpos + movevector * moveratio;
266 ISceneNode::setPosition(m_showpos);
276 LocalPlayer::LocalPlayer():
277 m_sneak_node(32767,32767,32767),
278 m_sneak_node_exists(false)
280 // Initialize hp to 0, so that no hearts will be shown if server
281 // doesn't support health points
285 LocalPlayer::~LocalPlayer()
289 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d,
290 core::list<CollisionInfo> *collision_info)
292 v3f position = getPosition();
293 v3f oldpos = position;
294 v3s16 oldpos_i = floatToInt(oldpos, BS);
296 /*std::cout<<"oldpos_i=("<<oldpos_i.X<<","<<oldpos_i.Y<<","
297 <<oldpos_i.Z<<")"<<std::endl;*/
300 Calculate new position
302 position += m_speed * dtime;
304 // Skip collision detection if a special movement mode is used
305 bool free_move = g_settings.getBool("free_move");
308 setPosition(position);
316 // Player position in nodes
317 v3s16 pos_i = floatToInt(position, BS);
320 Check if player is in water (the oscillating value)
323 // If in water, the threshold of coming out is at higher y
326 v3s16 pp = floatToInt(position + v3f(0,BS*0.1,0), BS);
327 in_water = content_liquid(map.getNode(pp).d);
329 // If not in water, the threshold of going in is at lower y
332 v3s16 pp = floatToInt(position + v3f(0,BS*0.5,0), BS);
333 in_water = content_liquid(map.getNode(pp).d);
336 catch(InvalidPositionException &e)
342 Check if player is in water (the stable value)
345 v3s16 pp = floatToInt(position + v3f(0,0,0), BS);
346 in_water_stable = content_liquid(map.getNode(pp).d);
348 catch(InvalidPositionException &e)
350 in_water_stable = false;
354 Collision uncertainty radius
355 Make it a bit larger than the maximum distance of movement
357 //f32 d = pos_max_d * 1.1;
358 // A fairly large value in here makes moving smoother
361 // This should always apply, otherwise there are glitches
362 assert(d > pos_max_d);
364 float player_radius = BS*0.35;
365 float player_height = BS*1.7;
367 // Maximum distance over border for sneaking
368 f32 sneak_max = BS*0.4;
371 If sneaking, player has larger collision radius to keep from
375 player_radius = sneak_max + d*1.1;*/
378 If sneaking, keep in range from the last walked node and don't
381 if(control.sneak && m_sneak_node_exists)
383 f32 maxd = 0.5*BS + sneak_max;
384 v3f lwn_f = intToFloat(m_sneak_node, BS);
385 position.X = rangelim(position.X, lwn_f.X-maxd, lwn_f.X+maxd);
386 position.Z = rangelim(position.Z, lwn_f.Z-maxd, lwn_f.Z+maxd);
388 f32 min_y = lwn_f.Y + 0.5*BS;
389 if(position.Y < min_y)
398 Calculate player collision box (new and old)
400 core::aabbox3d<f32> playerbox(
401 position.X - player_radius,
403 position.Z - player_radius,
404 position.X + player_radius,
405 position.Y + player_height,
406 position.Z + player_radius
408 core::aabbox3d<f32> playerbox_old(
409 oldpos.X - player_radius,
411 oldpos.Z - player_radius,
412 oldpos.X + player_radius,
413 oldpos.Y + player_height,
414 oldpos.Z + player_radius
418 If the player's feet touch the topside of any node, this is
421 Player is allowed to jump when this is true.
423 touching_ground = false;
425 /*std::cout<<"Checking collisions for ("
426 <<oldpos_i.X<<","<<oldpos_i.Y<<","<<oldpos_i.Z
428 <<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z
432 Go through every node around the player
434 for(s16 y = oldpos_i.Y - 1; y <= oldpos_i.Y + 2; y++)
435 for(s16 z = oldpos_i.Z - 1; z <= oldpos_i.Z + 1; z++)
436 for(s16 x = oldpos_i.X - 1; x <= oldpos_i.X + 1; x++)
439 // Player collides into walkable nodes
440 if(content_walkable(map.getNode(v3s16(x,y,z)).d) == false)
443 catch(InvalidPositionException &e)
445 // Doing nothing here will block the player from
446 // walking over map borders
449 core::aabbox3d<f32> nodebox = getNodeBox(v3s16(x,y,z), BS);
452 See if the player is touching ground.
454 Player touches ground if player's minimum Y is near node's
455 maximum Y and player's X-Z-area overlaps with the node's
458 Use 0.15*BS so that it is easier to get on a node.
461 //fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < d
462 fabs(nodebox.MaxEdge.Y-playerbox.MinEdge.Y) < 0.15*BS
463 && nodebox.MaxEdge.X-d > playerbox.MinEdge.X
464 && nodebox.MinEdge.X+d < playerbox.MaxEdge.X
465 && nodebox.MaxEdge.Z-d > playerbox.MinEdge.Z
466 && nodebox.MinEdge.Z+d < playerbox.MaxEdge.Z
468 touching_ground = true;
471 // If player doesn't intersect with node, ignore node.
472 if(playerbox.intersectsWithBox(nodebox) == false)
476 Go through every axis
479 v3f(0,0,1), // back-front
480 v3f(0,1,0), // top-bottom
481 v3f(1,0,0), // right-left
483 for(u16 i=0; i<3; i++)
486 Calculate values along the axis
488 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[i]);
489 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[i]);
490 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[i]);
491 f32 playermin = playerbox.MinEdge.dotProduct(dirs[i]);
492 f32 playermax_old = playerbox_old.MaxEdge.dotProduct(dirs[i]);
493 f32 playermin_old = playerbox_old.MinEdge.dotProduct(dirs[i]);
496 Check collision for the axis.
497 Collision happens when player is going through a surface.
501 // Make it easier to get on top of a node
504 bool negative_axis_collides =
505 (nodemax > playermin && nodemax <= playermin_old + neg_d
506 && m_speed.dotProduct(dirs[i]) < 0);
507 bool positive_axis_collides =
508 (nodemin < playermax && nodemin >= playermax_old - pos_d
509 && m_speed.dotProduct(dirs[i]) > 0);*/
510 bool negative_axis_collides =
511 (nodemax > playermin && nodemax <= playermin_old + d
512 && m_speed.dotProduct(dirs[i]) < 0);
513 bool positive_axis_collides =
514 (nodemin < playermax && nodemin >= playermax_old - d
515 && m_speed.dotProduct(dirs[i]) > 0);
516 bool main_axis_collides =
517 negative_axis_collides || positive_axis_collides;
520 Check overlap of player and node in other axes
522 bool other_axes_overlap = true;
523 for(u16 j=0; j<3; j++)
527 f32 nodemax = nodebox.MaxEdge.dotProduct(dirs[j]);
528 f32 nodemin = nodebox.MinEdge.dotProduct(dirs[j]);
529 f32 playermax = playerbox.MaxEdge.dotProduct(dirs[j]);
530 f32 playermin = playerbox.MinEdge.dotProduct(dirs[j]);
531 if(!(nodemax - d > playermin && nodemin + d < playermax))
533 other_axes_overlap = false;
539 If this is a collision, revert the position in the main
542 if(other_axes_overlap && main_axis_collides)
544 v3f old_speed = m_speed;
546 m_speed -= m_speed.dotProduct(dirs[i]) * dirs[i];
547 position -= position.dotProduct(dirs[i]) * dirs[i];
548 position += oldpos.dotProduct(dirs[i]) * dirs[i];
552 // Report fall collision
553 if(old_speed.Y < m_speed.Y - 0.1)
556 info.t = COLLISION_FALL;
557 info.speed = m_speed.Y - old_speed.Y;
558 collision_info->push_back(info);
567 Check the nodes under the player to see from which node the
568 player is sneaking from, if any.
571 v3s16 pos_i_bottom = floatToInt(position - v3f(0,BS/2,0), BS);
572 v2f player_p2df(position.X, position.Z);
573 f32 min_distance_f = 100000.0*BS;
574 // If already seeking from some node, compare to it.
575 /*if(m_sneak_node_exists)
577 v3f sneaknode_pf = intToFloat(m_sneak_node, BS);
578 v2f sneaknode_p2df(sneaknode_pf.X, sneaknode_pf.Z);
579 f32 d_horiz_f = player_p2df.getDistanceFrom(sneaknode_p2df);
580 f32 d_vert_f = fabs(sneaknode_pf.Y + BS*0.5 - position.Y);
581 // Ignore if player is not on the same level (likely dropped)
582 if(d_vert_f < 0.15*BS)
583 min_distance_f = d_horiz_f;
585 v3s16 new_sneak_node = m_sneak_node;
586 for(s16 x=-1; x<=1; x++)
587 for(s16 z=-1; z<=1; z++)
589 v3s16 p = pos_i_bottom + v3s16(x,0,z);
590 v3f pf = intToFloat(p, BS);
591 v2f node_p2df(pf.X, pf.Z);
592 f32 distance_f = player_p2df.getDistanceFrom(node_p2df);
593 f32 max_axis_distance_f = MYMAX(
594 fabs(player_p2df.X-node_p2df.X),
595 fabs(player_p2df.Y-node_p2df.Y));
597 if(distance_f > min_distance_f ||
598 max_axis_distance_f > 0.5*BS + sneak_max + 0.1*BS)
602 // The node to be sneaked on has to be walkable
603 if(content_walkable(map.getNode(p).d) == false)
605 // And the node above it has to be nonwalkable
606 if(content_walkable(map.getNode(p+v3s16(0,1,0)).d) == true)
609 catch(InvalidPositionException &e)
614 min_distance_f = distance_f;
618 bool sneak_node_found = (min_distance_f < 100000.0*BS*0.9);
620 if(control.sneak && m_sneak_node_exists)
623 m_sneak_node = new_sneak_node;
627 m_sneak_node = new_sneak_node;
628 m_sneak_node_exists = sneak_node_found;
632 If sneaking, the player's collision box can be in air, so
633 this has to be set explicitly
635 if(sneak_node_found && control.sneak)
636 touching_ground = true;
642 setPosition(position);
645 void LocalPlayer::move(f32 dtime, Map &map, f32 pos_max_d)
647 move(dtime, map, pos_max_d, NULL);
650 void LocalPlayer::applyControl(float dtime)
656 f32 walk_acceleration = 4.0 * BS;
657 f32 walkspeed_max = 4.0 * BS;
659 setPitch(control.pitch);
662 v3f move_direction = v3f(0,0,1);
663 move_direction.rotateXZBy(getYaw());
665 v3f speed = v3f(0,0,0);
667 bool free_move = g_settings.getBool("free_move");
668 bool fast_move = g_settings.getBool("fast_move");
669 bool continuous_forward = g_settings.getBool("continuous_forward");
673 v3f speed = getSpeed();
678 // Whether superspeed mode is used or not
679 bool superspeed = false;
681 // If free movement and fast movement, always move fast
682 if(free_move && fast_move)
685 // Auxiliary button 1 (E)
690 // In free movement mode, aux1 descends
691 v3f speed = getSpeed();
695 speed.Y = -walkspeed_max;
700 // If not free movement but fast is allowed, aux1 is
707 if(continuous_forward)
708 speed += move_direction;
712 if(continuous_forward)
715 speed += move_direction;
719 speed -= move_direction;
723 speed += move_direction.crossProduct(v3f(0,1,0));
727 speed += move_direction.crossProduct(v3f(0,-1,0));
733 v3f speed = getSpeed();
737 speed.Y = walkspeed_max;
740 else if(touching_ground)
742 v3f speed = getSpeed();
744 NOTE: The d value in move() affects jump height by
745 raising the height at which the jump speed is kept
746 at its starting value
751 // Use the oscillating value for getting out of water
752 // (so that the player doesn't fly on the surface)
755 v3f speed = getSpeed();
762 // The speed of the player (Y is ignored)
764 speed = speed.normalize() * walkspeed_max * 5.0;
765 else if(control.sneak)
766 speed = speed.normalize() * walkspeed_max / 3.0;
768 speed = speed.normalize() * walkspeed_max;
770 f32 inc = walk_acceleration * BS * dtime;
772 // Faster acceleration if fast and free movement
773 if(free_move && fast_move)
774 inc = walk_acceleration * BS * dtime * 10;
776 // Accelerate to target speed with maximum increment
777 accelerate(speed, inc);