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 "scripting_client.h"
26 #include "mapblock_mesh.h"
28 #include "collision.h"
31 #include "voxelalgorithms.h"
39 ClientEnvironment::ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
40 ITextureSource *texturesource, Client *client,
46 m_texturesource(texturesource),
52 memset(attachement_parent_ids, zero, sizeof(attachement_parent_ids));
55 ClientEnvironment::~ClientEnvironment()
57 // delete active objects
58 for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
59 i != m_active_objects.end(); ++i) {
63 for(std::vector<ClientSimpleObject*>::iterator
64 i = m_simple_objects.begin(); i != m_simple_objects.end(); ++i) {
71 delete m_local_player;
74 Map & ClientEnvironment::getMap()
79 ClientMap & ClientEnvironment::getClientMap()
84 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
86 DSTACK(FUNCTION_NAME);
88 It is a failure if already is a local player
90 FATAL_ERROR_IF(m_local_player != NULL,
91 "Local player already allocated");
93 m_local_player = player;
96 void ClientEnvironment::step(float dtime)
98 DSTACK(FUNCTION_NAME);
100 /* Step time of day */
101 stepTimeOfDay(dtime);
104 bool fly_allowed = m_client->checkLocalPrivilege("fly");
105 bool free_move = fly_allowed && g_settings->getBool("free_move");
108 LocalPlayer *lplayer = getLocalPlayer();
110 // collision info queue
111 std::vector<CollisionInfo> player_collisions;
114 Get the speed the player is going
116 bool is_climbing = lplayer->is_climbing;
118 f32 player_speed = lplayer->getSpeed().getLength();
121 Maximum position increment
123 //f32 position_max_increment = 0.05*BS;
124 f32 position_max_increment = 0.1*BS;
126 // Maximum time increment (for collision detection etc)
127 // time = distance / speed
128 f32 dtime_max_increment = 1;
129 if(player_speed > 0.001)
130 dtime_max_increment = position_max_increment / player_speed;
132 // Maximum time increment is 10ms or lower
133 if(dtime_max_increment > 0.01)
134 dtime_max_increment = 0.01;
136 // Don't allow overly huge dtime
140 f32 dtime_downcount = dtime;
143 Stuff that has a maximum time increment
152 if(dtime_downcount > dtime_max_increment)
154 dtime_part = dtime_max_increment;
155 dtime_downcount -= dtime_part;
159 dtime_part = dtime_downcount;
161 Setting this to 0 (no -=dtime_part) disables an infinite loop
162 when dtime_part is so small that dtime_downcount -= dtime_part
174 if(!free_move && !is_climbing)
177 v3f speed = lplayer->getSpeed();
178 if(!lplayer->in_liquid)
179 speed.Y -= lplayer->movement_gravity * lplayer->physics_override_gravity * dtime_part * 2;
181 // Liquid floating / sinking
182 if(lplayer->in_liquid && !lplayer->swimming_vertical)
183 speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2;
186 if(lplayer->in_liquid_stable || lplayer->in_liquid)
188 // How much the node's viscosity blocks movement, ranges between 0 and 1
189 // Should match the scale at which viscosity increase affects other liquid attributes
190 const f32 viscosity_factor = 0.3;
192 v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
193 f32 dl = d_wanted.getLength();
194 if(dl > lplayer->movement_liquid_fluidity_smooth)
195 dl = lplayer->movement_liquid_fluidity_smooth;
196 dl *= (lplayer->liquid_viscosity * viscosity_factor) + (1 - viscosity_factor);
198 v3f d = d_wanted.normalize() * dl;
202 lplayer->setSpeed(speed);
207 This also does collision detection.
209 lplayer->move(dtime_part, this, position_max_increment,
213 while(dtime_downcount > 0.001);
215 //std::cout<<"Looped "<<loopcount<<" times."<<std::endl;
217 for(std::vector<CollisionInfo>::iterator i = player_collisions.begin();
218 i != player_collisions.end(); ++i) {
219 CollisionInfo &info = *i;
220 v3f speed_diff = info.new_speed - info.old_speed;;
221 // Handle only fall damage
222 // (because otherwise walking against something in fast_move kills you)
223 if(speed_diff.Y < 0 || info.old_speed.Y >= 0)
225 // Get rid of other components
228 f32 pre_factor = 1; // 1 hp per node/s
229 f32 tolerance = BS*14; // 5 without damage
230 f32 post_factor = 1; // 1 hp per node/s
231 if(info.type == COLLISION_NODE)
233 const ContentFeatures &f = m_client->ndef()->
234 get(m_map->getNodeNoEx(info.node_p));
235 // Determine fall damage multiplier
236 int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
237 pre_factor = 1.0 + (float)addp/100.0;
239 float speed = pre_factor * speed_diff.getLength();
240 if (speed > tolerance) {
241 f32 damage_f = (speed - tolerance) / BS * post_factor;
242 u8 damage = (u8)MYMIN(damage_f + 0.5, 255);
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);
255 // Protocol v29 make this behaviour obsolete
256 if (getGameDef()->getProtoVersion() < 29) {
257 if (m_lava_hurt_interval.step(dtime, 1.0)) {
258 v3f pf = lplayer->getPosition();
260 // Feet, middle and head
261 v3s16 p1 = floatToInt(pf + v3f(0, BS * 0.1, 0), BS);
262 MapNode n1 = m_map->getNodeNoEx(p1);
263 v3s16 p2 = floatToInt(pf + v3f(0, BS * 0.8, 0), BS);
264 MapNode n2 = m_map->getNodeNoEx(p2);
265 v3s16 p3 = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
266 MapNode n3 = m_map->getNodeNoEx(p3);
268 u32 damage_per_second = 0;
269 damage_per_second = MYMAX(damage_per_second,
270 m_client->ndef()->get(n1).damage_per_second);
271 damage_per_second = MYMAX(damage_per_second,
272 m_client->ndef()->get(n2).damage_per_second);
273 damage_per_second = MYMAX(damage_per_second,
274 m_client->ndef()->get(n3).damage_per_second);
276 if (damage_per_second != 0)
277 damageLocalPlayer(damage_per_second, true);
283 if (m_drowning_interval.step(dtime, 2.0)) {
284 v3f pf = lplayer->getPosition();
287 v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
288 MapNode n = m_map->getNodeNoEx(p);
289 ContentFeatures c = m_client->ndef()->get(n);
290 u8 drowning_damage = c.drowning;
291 if (drowning_damage > 0 && lplayer->hp > 0) {
292 u16 breath = lplayer->getBreath();
299 lplayer->setBreath(breath);
300 updateLocalPlayerBreath(breath);
303 if (lplayer->getBreath() == 0 && drowning_damage > 0) {
304 damageLocalPlayer(drowning_damage, true);
307 if (m_breathing_interval.step(dtime, 0.5)) {
308 v3f pf = lplayer->getPosition();
311 v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
312 MapNode n = m_map->getNodeNoEx(p);
313 ContentFeatures c = m_client->ndef()->get(n);
315 lplayer->setBreath(11);
316 } else if (c.drowning == 0) {
317 u16 breath = lplayer->getBreath();
320 lplayer->setBreath(breath);
321 updateLocalPlayerBreath(breath);
327 // Update lighting on local player (used for wield item)
328 u32 day_night_ratio = getDayNightRatio();
332 // On InvalidPositionException, use this as default
333 // (day: LIGHT_SUN, night: 0)
334 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
336 v3s16 p = lplayer->getLightPosition();
337 node_at_lplayer = m_map->getNodeNoEx(p);
339 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
340 final_color_blend(&lplayer->light_color, light, day_night_ratio);
344 Step active objects and update lighting of them
347 g_profiler->avg("CEnv: num of objects", m_active_objects.size());
348 bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
349 for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
350 i != m_active_objects.end(); ++i) {
351 ClientActiveObject* obj = i->second;
353 obj->step(dtime, this);
362 v3s16 p = obj->getLightPosition();
363 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
365 light = n.getLightBlend(day_night_ratio, m_client->ndef());
367 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
369 obj->updateLight(light);
374 Step and handle simple objects
376 g_profiler->avg("CEnv: num of simple objects", m_simple_objects.size());
377 for(std::vector<ClientSimpleObject*>::iterator
378 i = m_simple_objects.begin(); i != m_simple_objects.end();) {
379 std::vector<ClientSimpleObject*>::iterator cur = i;
380 ClientSimpleObject *simple = *cur;
383 if(simple->m_to_be_removed) {
385 i = m_simple_objects.erase(cur);
393 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
395 m_simple_objects.push_back(simple);
398 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
400 ClientActiveObject *obj = getActiveObject(id);
401 if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
402 return (GenericCAO*) obj;
407 ClientActiveObject* ClientEnvironment::getActiveObject(u16 id)
409 UNORDERED_MAP<u16, ClientActiveObject*>::iterator n = m_active_objects.find(id);
410 if (n == m_active_objects.end())
415 bool isFreeClientActiveObjectId(const u16 id,
416 UNORDERED_MAP<u16, ClientActiveObject*> &objects)
421 return objects.find(id) == objects.end();
424 u16 getFreeClientActiveObjectId(UNORDERED_MAP<u16, ClientActiveObject*> &objects)
426 //try to reuse id's as late as possible
427 static u16 last_used_id = 0;
428 u16 startid = last_used_id;
431 if (isFreeClientActiveObjectId(last_used_id, objects))
434 if (last_used_id == startid)
439 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
441 assert(object); // Pre-condition
442 if(object->getId() == 0)
444 u16 new_id = getFreeClientActiveObjectId(m_active_objects);
447 infostream<<"ClientEnvironment::addActiveObject(): "
448 <<"no free ids available"<<std::endl;
452 object->setId(new_id);
454 if (!isFreeClientActiveObjectId(object->getId(), m_active_objects)) {
455 infostream<<"ClientEnvironment::addActiveObject(): "
456 <<"id is not free ("<<object->getId()<<")"<<std::endl;
460 infostream<<"ClientEnvironment::addActiveObject(): "
461 <<"added (id="<<object->getId()<<")"<<std::endl;
462 m_active_objects[object->getId()] = object;
463 object->addToScene(m_smgr, m_texturesource, m_irr);
464 { // Update lighting immediately
469 v3s16 p = object->getLightPosition();
470 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
472 light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
474 light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
476 object->updateLight(light);
478 return object->getId();
481 void ClientEnvironment::addActiveObject(u16 id, u8 type,
482 const std::string &init_data)
484 ClientActiveObject* obj =
485 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
488 infostream<<"ClientEnvironment::addActiveObject(): "
489 <<"id="<<id<<" type="<<type<<": Couldn't create object"
498 obj->initialize(init_data);
500 catch(SerializationError &e)
502 errorstream<<"ClientEnvironment::addActiveObject():"
503 <<" id="<<id<<" type="<<type
504 <<": SerializationError in initialize(): "
506 <<": init_data="<<serializeJsonString(init_data)
510 addActiveObject(obj);
513 void ClientEnvironment::removeActiveObject(u16 id)
515 verbosestream<<"ClientEnvironment::removeActiveObject(): "
516 <<"id="<<id<<std::endl;
517 ClientActiveObject* obj = getActiveObject(id);
519 infostream<<"ClientEnvironment::removeActiveObject(): "
520 <<"id="<<id<<" not found"<<std::endl;
523 obj->removeFromScene(true);
525 m_active_objects.erase(id);
528 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
530 ClientActiveObject *obj = getActiveObject(id);
532 infostream << "ClientEnvironment::processActiveObjectMessage():"
533 << " got message for id=" << id << ", which doesn't exist."
539 obj->processMessage(data);
540 } catch (SerializationError &e) {
541 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
542 << " id=" << id << " type=" << obj->getType()
543 << " SerializationError in processMessage(): " << e.what()
549 Callbacks for activeobjects
552 void ClientEnvironment::damageLocalPlayer(u8 damage, bool handle_hp)
554 LocalPlayer *lplayer = getLocalPlayer();
558 if (lplayer->hp > damage)
559 lplayer->hp -= damage;
564 ClientEnvEvent event;
565 event.type = CEE_PLAYER_DAMAGE;
566 event.player_damage.amount = damage;
567 event.player_damage.send_to_server = handle_hp;
568 m_client_event_queue.push(event);
571 void ClientEnvironment::updateLocalPlayerBreath(u16 breath)
573 ClientEnvEvent event;
574 event.type = CEE_PLAYER_BREATH;
575 event.player_breath.amount = breath;
576 m_client_event_queue.push(event);
580 Client likes to call these
583 void ClientEnvironment::getActiveObjects(v3f origin, f32 max_d,
584 std::vector<DistanceSortedActiveObject> &dest)
586 for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
587 i != m_active_objects.end(); ++i) {
588 ClientActiveObject* obj = i->second;
590 f32 d = (obj->getPosition() - origin).getLength();
595 DistanceSortedActiveObject dso(obj, d);
601 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
603 FATAL_ERROR_IF(m_client_event_queue.empty(),
604 "ClientEnvironment::getClientEnvEvent(): queue is empty");
606 ClientEnvEvent event = m_client_event_queue.front();
607 m_client_event_queue.pop();
611 ClientActiveObject * ClientEnvironment::getSelectedActiveObject(
612 const core::line3d<f32> &shootline_on_map, v3f *intersection_point,
613 v3s16 *intersection_normal)
615 std::vector<DistanceSortedActiveObject> objects;
616 getActiveObjects(shootline_on_map.start,
617 shootline_on_map.getLength() + 3, objects);
618 const v3f line_vector = shootline_on_map.getVector();
621 // After this, the closest object is the first in the array.
622 std::sort(objects.begin(), objects.end());
624 /* Because objects can have different nodebox sizes,
625 * the object whose center is the nearest isn't necessarily
626 * the closest one. If an object is found, don't stop
629 f32 d_min = shootline_on_map.getLength();
630 ClientActiveObject *nearest_obj = NULL;
631 for (u32 i = 0; i < objects.size(); i++) {
632 ClientActiveObject *obj = objects[i].obj;
634 aabb3f *selection_box = obj->getSelectionBox();
635 if (selection_box == NULL)
638 v3f pos = obj->getPosition();
640 aabb3f offsetted_box(selection_box->MinEdge + pos,
641 selection_box->MaxEdge + pos);
643 if (offsetted_box.getCenter().getDistanceFrom(
644 shootline_on_map.start) > d_min + 9.6f*BS) {
645 // Probably there is no active object that has bigger nodebox than
646 // (-5.5,-5.5,-5.5,5.5,5.5,5.5)
651 v3f current_intersection;
652 v3s16 current_normal;
653 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
654 ¤t_intersection, ¤t_normal)) {
655 f32 d_current = current_intersection.getDistanceFrom(
656 shootline_on_map.start);
657 if (d_current <= d_min) {
660 *intersection_point = current_intersection;
661 *intersection_normal = current_normal;
670 Check if a node is pointable
672 static inline bool isPointableNode(const MapNode &n,
673 INodeDefManager *ndef, bool liquids_pointable)
675 const ContentFeatures &features = ndef->get(n);
676 return features.pointable ||
677 (liquids_pointable && features.isLiquid());
680 PointedThing ClientEnvironment::getPointedThing(
681 core::line3d<f32> shootline,
682 bool liquids_pointable,
683 bool look_for_object)
687 INodeDefManager *nodedef = m_map->getNodeDefManager();
689 core::aabbox3d<s16> maximal_exceed = nodedef->getSelectionBoxIntUnion();
690 // The code needs to search these nodes
691 core::aabbox3d<s16> search_range(-maximal_exceed.MaxEdge,
692 -maximal_exceed.MinEdge);
693 // If a node is found, there might be a larger node behind.
694 // To find it, we have to go further.
695 s16 maximal_overcheck =
696 std::max(abs(search_range.MinEdge.X), abs(search_range.MaxEdge.X))
697 + std::max(abs(search_range.MinEdge.Y), abs(search_range.MaxEdge.Y))
698 + std::max(abs(search_range.MinEdge.Z), abs(search_range.MaxEdge.Z));
700 const v3f original_vector = shootline.getVector();
701 const f32 original_length = original_vector.getLength();
703 f32 min_distance = original_length;
705 // First try to find an active object
706 if (look_for_object) {
707 ClientActiveObject *selected_object = getSelectedActiveObject(
708 shootline, &result.intersection_point,
709 &result.intersection_normal);
711 if (selected_object != NULL) {
713 (result.intersection_point - shootline.start).getLength();
715 result.type = POINTEDTHING_OBJECT;
716 result.object_id = selected_object->getId();
721 if (original_length > 0) {
722 shootline.end = shootline.start
723 + shootline.getVector() / original_length * min_distance;
726 // Try to find a node that is closer than the selected active
727 // object (if it exists).
729 voxalgo::VoxelLineIterator iterator(shootline.start / BS,
730 shootline.getVector() / BS);
731 v3s16 oldnode = iterator.m_current_node_pos;
732 // Indicates that a node was found.
733 bool is_node_found = false;
734 // If a node is found, it is possible that there's a node
735 // behind it with a large nodebox, so continue the search.
736 u16 node_foundcounter = 0;
737 // If a node is found, this is the center of the
738 // first nodebox the shootline meets.
739 v3f found_boxcenter(0, 0, 0);
740 // The untested nodes are in this range.
741 core::aabbox3d<s16> new_nodes;
743 // Test the nodes around the current node in search_range.
744 new_nodes = search_range;
745 new_nodes.MinEdge += iterator.m_current_node_pos;
746 new_nodes.MaxEdge += iterator.m_current_node_pos;
748 // Only check new nodes
749 v3s16 delta = iterator.m_current_node_pos - oldnode;
751 new_nodes.MinEdge.X = new_nodes.MaxEdge.X;
752 else if (delta.X < 0)
753 new_nodes.MaxEdge.X = new_nodes.MinEdge.X;
754 else if (delta.Y > 0)
755 new_nodes.MinEdge.Y = new_nodes.MaxEdge.Y;
756 else if (delta.Y < 0)
757 new_nodes.MaxEdge.Y = new_nodes.MinEdge.Y;
758 else if (delta.Z > 0)
759 new_nodes.MinEdge.Z = new_nodes.MaxEdge.Z;
760 else if (delta.Z < 0)
761 new_nodes.MaxEdge.Z = new_nodes.MinEdge.Z;
763 // For each untested node
764 for (s16 x = new_nodes.MinEdge.X; x <= new_nodes.MaxEdge.X; x++) {
765 for (s16 y = new_nodes.MinEdge.Y; y <= new_nodes.MaxEdge.Y; y++) {
766 for (s16 z = new_nodes.MinEdge.Z; z <= new_nodes.MaxEdge.Z; z++) {
769 bool is_valid_position;
771 n = m_map->getNodeNoEx(np, &is_valid_position);
772 if (!(is_valid_position &&
773 isPointableNode(n, nodedef, liquids_pointable))) {
776 std::vector<aabb3f> boxes;
777 n.getSelectionBoxes(nodedef, &boxes,
778 n.getNeighbors(np, m_map));
780 v3f npf = intToFloat(np, BS);
781 for (std::vector<aabb3f>::const_iterator i = boxes.begin();
782 i != boxes.end(); ++i) {
786 v3f intersection_point;
787 v3s16 intersection_normal;
788 if (!boxLineCollision(box, shootline.start, shootline.getVector(),
789 &intersection_point, &intersection_normal)) {
792 f32 distance = (intersection_point - shootline.start).getLength();
793 if (distance >= min_distance) {
796 result.type = POINTEDTHING_NODE;
797 result.node_undersurface = np;
798 result.intersection_point = intersection_point;
799 result.intersection_normal = intersection_normal;
800 found_boxcenter = box.getCenter();
801 min_distance = distance;
802 is_node_found = true;
809 if (node_foundcounter > maximal_overcheck) {
814 if (iterator.hasNext()) {
815 oldnode = iterator.m_current_node_pos;
823 // Set undersurface and abovesurface nodes
825 v3f fake_intersection = result.intersection_point;
826 // Move intersection towards its source block.
827 if (fake_intersection.X < found_boxcenter.X)
828 fake_intersection.X += d;
830 fake_intersection.X -= d;
832 if (fake_intersection.Y < found_boxcenter.Y)
833 fake_intersection.Y += d;
835 fake_intersection.Y -= d;
837 if (fake_intersection.Z < found_boxcenter.Z)
838 fake_intersection.Z += d;
840 fake_intersection.Z -= d;
842 result.node_real_undersurface = floatToInt(fake_intersection, BS);
843 result.node_abovesurface = result.node_real_undersurface
844 + result.intersection_normal;