3 Copyright (C) 2010-2017 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 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.
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.
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.
20 #include "util/serialize.h"
21 #include "util/pointedthing.h"
22 #include "clientenvironment.h"
23 #include "clientsimpleobject.h"
24 #include "clientmap.h"
25 #include "clientscripting.h"
26 #include "mapblock_mesh.h"
28 #include "collision.h"
31 #include "voxelalgorithms.h"
38 ClientEnvironment::ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
39 ITextureSource *texturesource, Client *client,
45 m_texturesource(texturesource),
51 memset(attachement_parent_ids, zero, sizeof(attachement_parent_ids));
54 ClientEnvironment::~ClientEnvironment()
56 // delete active objects
57 for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
58 i != m_active_objects.end(); ++i) {
62 for(std::vector<ClientSimpleObject*>::iterator
63 i = m_simple_objects.begin(); i != m_simple_objects.end(); ++i) {
70 delete m_local_player;
73 Map & ClientEnvironment::getMap()
78 ClientMap & ClientEnvironment::getClientMap()
83 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
85 DSTACK(FUNCTION_NAME);
87 It is a failure if already is a local player
89 FATAL_ERROR_IF(m_local_player != NULL,
90 "Local player already allocated");
92 m_local_player = player;
95 void ClientEnvironment::step(float dtime)
97 DSTACK(FUNCTION_NAME);
99 /* Step time of day */
100 stepTimeOfDay(dtime);
103 bool fly_allowed = m_client->checkLocalPrivilege("fly");
104 bool free_move = fly_allowed && g_settings->getBool("free_move");
107 LocalPlayer *lplayer = getLocalPlayer();
109 // collision info queue
110 std::vector<CollisionInfo> player_collisions;
113 Get the speed the player is going
115 bool is_climbing = lplayer->is_climbing;
117 f32 player_speed = lplayer->getSpeed().getLength();
120 Maximum position increment
122 //f32 position_max_increment = 0.05*BS;
123 f32 position_max_increment = 0.1*BS;
125 // Maximum time increment (for collision detection etc)
126 // time = distance / speed
127 f32 dtime_max_increment = 1;
128 if(player_speed > 0.001)
129 dtime_max_increment = position_max_increment / player_speed;
131 // Maximum time increment is 10ms or lower
132 if(dtime_max_increment > 0.01)
133 dtime_max_increment = 0.01;
135 // Don't allow overly huge dtime
139 f32 dtime_downcount = dtime;
142 Stuff that has a maximum time increment
151 if(dtime_downcount > dtime_max_increment)
153 dtime_part = dtime_max_increment;
154 dtime_downcount -= dtime_part;
158 dtime_part = dtime_downcount;
160 Setting this to 0 (no -=dtime_part) disables an infinite loop
161 when dtime_part is so small that dtime_downcount -= dtime_part
173 if(!free_move && !is_climbing)
176 v3f speed = lplayer->getSpeed();
177 if(!lplayer->in_liquid)
178 speed.Y -= lplayer->movement_gravity * lplayer->physics_override_gravity * dtime_part * 2;
180 // Liquid floating / sinking
181 if(lplayer->in_liquid && !lplayer->swimming_vertical)
182 speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2;
185 if(lplayer->in_liquid_stable || lplayer->in_liquid)
187 // How much the node's viscosity blocks movement, ranges between 0 and 1
188 // Should match the scale at which viscosity increase affects other liquid attributes
189 const f32 viscosity_factor = 0.3;
191 v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
192 f32 dl = d_wanted.getLength();
193 if(dl > lplayer->movement_liquid_fluidity_smooth)
194 dl = lplayer->movement_liquid_fluidity_smooth;
195 dl *= (lplayer->liquid_viscosity * viscosity_factor) + (1 - viscosity_factor);
197 v3f d = d_wanted.normalize() * dl;
201 lplayer->setSpeed(speed);
206 This also does collision detection.
208 lplayer->move(dtime_part, this, position_max_increment,
212 while(dtime_downcount > 0.001);
214 //std::cout<<"Looped "<<loopcount<<" times."<<std::endl;
216 for(std::vector<CollisionInfo>::iterator i = player_collisions.begin();
217 i != player_collisions.end(); ++i) {
218 CollisionInfo &info = *i;
219 v3f speed_diff = info.new_speed - info.old_speed;;
220 // Handle only fall damage
221 // (because otherwise walking against something in fast_move kills you)
222 if(speed_diff.Y < 0 || info.old_speed.Y >= 0)
224 // Get rid of other components
227 f32 pre_factor = 1; // 1 hp per node/s
228 f32 tolerance = BS*14; // 5 without damage
229 f32 post_factor = 1; // 1 hp per node/s
230 if(info.type == COLLISION_NODE)
232 const ContentFeatures &f = m_client->ndef()->
233 get(m_map->getNodeNoEx(info.node_p));
234 // Determine fall damage multiplier
235 int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
236 pre_factor = 1.0 + (float)addp/100.0;
238 float speed = pre_factor * speed_diff.getLength();
239 if(speed > tolerance)
241 f32 damage_f = (speed - tolerance)/BS * post_factor;
242 u16 damage = (u16)(damage_f+0.5);
244 damageLocalPlayer(damage, true);
245 MtEvent *e = new SimpleTriggerEvent("PlayerFallingDamage");
246 m_client->event()->put(e);
251 if (m_client->moddingEnabled()) {
252 m_script->environment_step(dtime);
256 A quick draft of lava damage
258 if(m_lava_hurt_interval.step(dtime, 1.0))
260 v3f pf = lplayer->getPosition();
262 // Feet, middle and head
263 v3s16 p1 = floatToInt(pf + v3f(0, BS*0.1, 0), BS);
264 MapNode n1 = m_map->getNodeNoEx(p1);
265 v3s16 p2 = floatToInt(pf + v3f(0, BS*0.8, 0), BS);
266 MapNode n2 = m_map->getNodeNoEx(p2);
267 v3s16 p3 = floatToInt(pf + v3f(0, BS*1.6, 0), BS);
268 MapNode n3 = m_map->getNodeNoEx(p3);
270 u32 damage_per_second = 0;
271 damage_per_second = MYMAX(damage_per_second,
272 m_client->ndef()->get(n1).damage_per_second);
273 damage_per_second = MYMAX(damage_per_second,
274 m_client->ndef()->get(n2).damage_per_second);
275 damage_per_second = MYMAX(damage_per_second,
276 m_client->ndef()->get(n3).damage_per_second);
278 if(damage_per_second != 0)
280 damageLocalPlayer(damage_per_second, true);
284 // Protocol v29 make this behaviour obsolete
285 if (getGameDef()->getProtoVersion() < 29) {
289 if (m_drowning_interval.step(dtime, 2.0)) {
290 v3f pf = lplayer->getPosition();
293 v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
294 MapNode n = m_map->getNodeNoEx(p);
295 ContentFeatures c = m_client->ndef()->get(n);
296 u8 drowning_damage = c.drowning;
297 if (drowning_damage > 0 && lplayer->hp > 0) {
298 u16 breath = lplayer->getBreath();
305 lplayer->setBreath(breath);
306 updateLocalPlayerBreath(breath);
309 if (lplayer->getBreath() == 0 && drowning_damage > 0) {
310 damageLocalPlayer(drowning_damage, true);
313 if (m_breathing_interval.step(dtime, 0.5)) {
314 v3f pf = lplayer->getPosition();
317 v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
318 MapNode n = m_map->getNodeNoEx(p);
319 ContentFeatures c = m_client->ndef()->get(n);
321 lplayer->setBreath(11);
322 } else if (c.drowning == 0) {
323 u16 breath = lplayer->getBreath();
326 lplayer->setBreath(breath);
327 updateLocalPlayerBreath(breath);
333 // Update lighting on local player (used for wield item)
334 u32 day_night_ratio = getDayNightRatio();
338 // On InvalidPositionException, use this as default
339 // (day: LIGHT_SUN, night: 0)
340 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
342 v3s16 p = lplayer->getLightPosition();
343 node_at_lplayer = m_map->getNodeNoEx(p);
345 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
346 final_color_blend(&lplayer->light_color, light, day_night_ratio);
350 Step active objects and update lighting of them
353 g_profiler->avg("CEnv: num of objects", m_active_objects.size());
354 bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
355 for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
356 i != m_active_objects.end(); ++i) {
357 ClientActiveObject* obj = i->second;
359 obj->step(dtime, this);
368 v3s16 p = obj->getLightPosition();
369 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
371 light = n.getLightBlend(day_night_ratio, m_client->ndef());
373 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
375 obj->updateLight(light);
380 Step and handle simple objects
382 g_profiler->avg("CEnv: num of simple objects", m_simple_objects.size());
383 for(std::vector<ClientSimpleObject*>::iterator
384 i = m_simple_objects.begin(); i != m_simple_objects.end();) {
385 std::vector<ClientSimpleObject*>::iterator cur = i;
386 ClientSimpleObject *simple = *cur;
389 if(simple->m_to_be_removed) {
391 i = m_simple_objects.erase(cur);
399 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
401 m_simple_objects.push_back(simple);
404 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
406 ClientActiveObject *obj = getActiveObject(id);
407 if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
408 return (GenericCAO*) obj;
413 ClientActiveObject* ClientEnvironment::getActiveObject(u16 id)
415 UNORDERED_MAP<u16, ClientActiveObject*>::iterator n = m_active_objects.find(id);
416 if (n == m_active_objects.end())
421 bool isFreeClientActiveObjectId(const u16 id,
422 UNORDERED_MAP<u16, ClientActiveObject*> &objects)
427 return objects.find(id) == objects.end();
430 u16 getFreeClientActiveObjectId(UNORDERED_MAP<u16, ClientActiveObject*> &objects)
432 //try to reuse id's as late as possible
433 static u16 last_used_id = 0;
434 u16 startid = last_used_id;
437 if (isFreeClientActiveObjectId(last_used_id, objects))
440 if (last_used_id == startid)
445 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
447 assert(object); // Pre-condition
448 if(object->getId() == 0)
450 u16 new_id = getFreeClientActiveObjectId(m_active_objects);
453 infostream<<"ClientEnvironment::addActiveObject(): "
454 <<"no free ids available"<<std::endl;
458 object->setId(new_id);
460 if (!isFreeClientActiveObjectId(object->getId(), m_active_objects)) {
461 infostream<<"ClientEnvironment::addActiveObject(): "
462 <<"id is not free ("<<object->getId()<<")"<<std::endl;
466 infostream<<"ClientEnvironment::addActiveObject(): "
467 <<"added (id="<<object->getId()<<")"<<std::endl;
468 m_active_objects[object->getId()] = object;
469 object->addToScene(m_smgr, m_texturesource, m_irr);
470 { // Update lighting immediately
475 v3s16 p = object->getLightPosition();
476 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
478 light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
480 light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
482 object->updateLight(light);
484 return object->getId();
487 void ClientEnvironment::addActiveObject(u16 id, u8 type,
488 const std::string &init_data)
490 ClientActiveObject* obj =
491 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
494 infostream<<"ClientEnvironment::addActiveObject(): "
495 <<"id="<<id<<" type="<<type<<": Couldn't create object"
504 obj->initialize(init_data);
506 catch(SerializationError &e)
508 errorstream<<"ClientEnvironment::addActiveObject():"
509 <<" id="<<id<<" type="<<type
510 <<": SerializationError in initialize(): "
512 <<": init_data="<<serializeJsonString(init_data)
516 addActiveObject(obj);
519 void ClientEnvironment::removeActiveObject(u16 id)
521 verbosestream<<"ClientEnvironment::removeActiveObject(): "
522 <<"id="<<id<<std::endl;
523 ClientActiveObject* obj = getActiveObject(id);
525 infostream<<"ClientEnvironment::removeActiveObject(): "
526 <<"id="<<id<<" not found"<<std::endl;
529 obj->removeFromScene(true);
531 m_active_objects.erase(id);
534 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
536 ClientActiveObject *obj = getActiveObject(id);
538 infostream << "ClientEnvironment::processActiveObjectMessage():"
539 << " got message for id=" << id << ", which doesn't exist."
545 obj->processMessage(data);
546 } catch (SerializationError &e) {
547 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
548 << " id=" << id << " type=" << obj->getType()
549 << " SerializationError in processMessage(): " << e.what()
555 Callbacks for activeobjects
558 void ClientEnvironment::damageLocalPlayer(u8 damage, bool handle_hp)
560 LocalPlayer *lplayer = getLocalPlayer();
564 if (lplayer->hp > damage)
565 lplayer->hp -= damage;
570 ClientEnvEvent event;
571 event.type = CEE_PLAYER_DAMAGE;
572 event.player_damage.amount = damage;
573 event.player_damage.send_to_server = handle_hp;
574 m_client_event_queue.push(event);
577 void ClientEnvironment::updateLocalPlayerBreath(u16 breath)
579 ClientEnvEvent event;
580 event.type = CEE_PLAYER_BREATH;
581 event.player_breath.amount = breath;
582 m_client_event_queue.push(event);
586 Client likes to call these
589 void ClientEnvironment::getActiveObjects(v3f origin, f32 max_d,
590 std::vector<DistanceSortedActiveObject> &dest)
592 for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
593 i != m_active_objects.end(); ++i) {
594 ClientActiveObject* obj = i->second;
596 f32 d = (obj->getPosition() - origin).getLength();
601 DistanceSortedActiveObject dso(obj, d);
607 ClientEnvEvent ClientEnvironment::getClientEvent()
609 ClientEnvEvent event;
610 if(m_client_event_queue.empty())
611 event.type = CEE_NONE;
613 event = m_client_event_queue.front();
614 m_client_event_queue.pop();
619 ClientActiveObject * ClientEnvironment::getSelectedActiveObject(
620 const core::line3d<f32> &shootline_on_map, v3f *intersection_point,
621 v3s16 *intersection_normal)
623 std::vector<DistanceSortedActiveObject> objects;
624 getActiveObjects(shootline_on_map.start,
625 shootline_on_map.getLength() + 3, objects);
626 const v3f line_vector = shootline_on_map.getVector();
629 // After this, the closest object is the first in the array.
630 std::sort(objects.begin(), objects.end());
632 /* Because objects can have different nodebox sizes,
633 * the object whose center is the nearest isn't necessarily
634 * the closest one. If an object is found, don't stop
637 f32 d_min = shootline_on_map.getLength();
638 ClientActiveObject *nearest_obj = NULL;
639 for (u32 i = 0; i < objects.size(); i++) {
640 ClientActiveObject *obj = objects[i].obj;
642 aabb3f *selection_box = obj->getSelectionBox();
643 if (selection_box == NULL)
646 v3f pos = obj->getPosition();
648 aabb3f offsetted_box(selection_box->MinEdge + pos,
649 selection_box->MaxEdge + pos);
651 if (offsetted_box.getCenter().getDistanceFrom(
652 shootline_on_map.start) > d_min + 9.6f*BS) {
653 // Probably there is no active object that has bigger nodebox than
654 // (-5.5,-5.5,-5.5,5.5,5.5,5.5)
659 v3f current_intersection;
660 v3s16 current_normal;
661 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
662 ¤t_intersection, ¤t_normal)) {
663 f32 d_current = current_intersection.getDistanceFrom(
664 shootline_on_map.start);
665 if (d_current <= d_min) {
668 *intersection_point = current_intersection;
669 *intersection_normal = current_normal;
678 Check if a node is pointable
680 static inline bool isPointableNode(const MapNode &n,
681 INodeDefManager *ndef, bool liquids_pointable)
683 const ContentFeatures &features = ndef->get(n);
684 return features.pointable ||
685 (liquids_pointable && features.isLiquid());
688 PointedThing ClientEnvironment::getPointedThing(
689 core::line3d<f32> shootline,
690 bool liquids_pointable,
691 bool look_for_object)
695 INodeDefManager *nodedef = m_map->getNodeDefManager();
697 core::aabbox3d<s16> maximal_exceed = nodedef->getSelectionBoxIntUnion();
698 // The code needs to search these nodes
699 core::aabbox3d<s16> search_range(-maximal_exceed.MaxEdge,
700 -maximal_exceed.MinEdge);
701 // If a node is found, there might be a larger node behind.
702 // To find it, we have to go further.
703 s16 maximal_overcheck =
704 std::max(abs(search_range.MinEdge.X), abs(search_range.MaxEdge.X))
705 + std::max(abs(search_range.MinEdge.Y), abs(search_range.MaxEdge.Y))
706 + std::max(abs(search_range.MinEdge.Z), abs(search_range.MaxEdge.Z));
708 const v3f original_vector = shootline.getVector();
709 const f32 original_length = original_vector.getLength();
711 f32 min_distance = original_length;
713 // First try to find an active object
714 if (look_for_object) {
715 ClientActiveObject *selected_object = getSelectedActiveObject(
716 shootline, &result.intersection_point,
717 &result.intersection_normal);
719 if (selected_object != NULL) {
721 (result.intersection_point - shootline.start).getLength();
723 result.type = POINTEDTHING_OBJECT;
724 result.object_id = selected_object->getId();
729 if (original_length > 0) {
730 shootline.end = shootline.start
731 + shootline.getVector() / original_length * min_distance;
734 // Try to find a node that is closer than the selected active
735 // object (if it exists).
737 voxalgo::VoxelLineIterator iterator(shootline.start / BS,
738 shootline.getVector() / BS);
739 v3s16 oldnode = iterator.m_current_node_pos;
740 // Indicates that a node was found.
741 bool is_node_found = false;
742 // If a node is found, it is possible that there's a node
743 // behind it with a large nodebox, so continue the search.
744 u16 node_foundcounter = 0;
745 // If a node is found, this is the center of the
746 // first nodebox the shootline meets.
747 v3f found_boxcenter(0, 0, 0);
748 // The untested nodes are in this range.
749 core::aabbox3d<s16> new_nodes;
751 // Test the nodes around the current node in search_range.
752 new_nodes = search_range;
753 new_nodes.MinEdge += iterator.m_current_node_pos;
754 new_nodes.MaxEdge += iterator.m_current_node_pos;
756 // Only check new nodes
757 v3s16 delta = iterator.m_current_node_pos - oldnode;
759 new_nodes.MinEdge.X = new_nodes.MaxEdge.X;
760 else if (delta.X < 0)
761 new_nodes.MaxEdge.X = new_nodes.MinEdge.X;
762 else if (delta.Y > 0)
763 new_nodes.MinEdge.Y = new_nodes.MaxEdge.Y;
764 else if (delta.Y < 0)
765 new_nodes.MaxEdge.Y = new_nodes.MinEdge.Y;
766 else if (delta.Z > 0)
767 new_nodes.MinEdge.Z = new_nodes.MaxEdge.Z;
768 else if (delta.Z < 0)
769 new_nodes.MaxEdge.Z = new_nodes.MinEdge.Z;
771 // For each untested node
772 for (s16 x = new_nodes.MinEdge.X; x <= new_nodes.MaxEdge.X; x++) {
773 for (s16 y = new_nodes.MinEdge.Y; y <= new_nodes.MaxEdge.Y; y++) {
774 for (s16 z = new_nodes.MinEdge.Z; z <= new_nodes.MaxEdge.Z; z++) {
777 bool is_valid_position;
779 n = m_map->getNodeNoEx(np, &is_valid_position);
780 if (!(is_valid_position &&
781 isPointableNode(n, nodedef, liquids_pointable))) {
784 std::vector<aabb3f> boxes;
785 n.getSelectionBoxes(nodedef, &boxes,
786 n.getNeighbors(np, m_map));
788 v3f npf = intToFloat(np, BS);
789 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
790 i != boxes.end(); ++i) {
794 v3f intersection_point;
795 v3s16 intersection_normal;
796 if (!boxLineCollision(box, shootline.start, shootline.getVector(),
797 &intersection_point, &intersection_normal)) {
800 f32 distance = (intersection_point - shootline.start).getLength();
801 if (distance >= min_distance) {
804 result.type = POINTEDTHING_NODE;
805 result.node_undersurface = np;
806 result.intersection_point = intersection_point;
807 result.intersection_normal = intersection_normal;
808 found_boxcenter = box.getCenter();
809 min_distance = distance;
810 is_node_found = true;
817 if (node_foundcounter > maximal_overcheck) {
822 if (iterator.hasNext()) {
823 oldnode = iterator.m_current_node_pos;
831 // Set undersurface and abovesurface nodes
833 v3f fake_intersection = result.intersection_point;
834 // Move intersection towards its source block.
835 if (fake_intersection.X < found_boxcenter.X)
836 fake_intersection.X += d;
838 fake_intersection.X -= d;
840 if (fake_intersection.Y < found_boxcenter.Y)
841 fake_intersection.Y += d;
843 fake_intersection.Y -= d;
845 if (fake_intersection.Z < found_boxcenter.Z)
846 fake_intersection.Z += d;
848 fake_intersection.Z -= d;
850 result.node_real_undersurface = floatToInt(fake_intersection, BS);
851 result.node_abovesurface = result.node_real_undersurface
852 + result.intersection_normal;