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"
23 #include "clientenvironment.h"
24 #include "clientsimpleobject.h"
25 #include "clientmap.h"
26 #include "scripting_client.h"
27 #include "mapblock_mesh.h"
29 #include "collision.h"
33 #include "voxelalgorithms.h"
35 #include "content_cao.h"
37 #include "client/renderingengine.h"
43 ClientEnvironment::ClientEnvironment(ClientMap *map,
44 ITextureSource *texturesource, Client *client):
47 m_texturesource(texturesource),
51 memset(attachement_parent_ids, zero, sizeof(attachement_parent_ids));
54 ClientEnvironment::~ClientEnvironment()
58 for (auto &simple_object : m_simple_objects) {
65 delete m_local_player;
68 Map & ClientEnvironment::getMap()
73 ClientMap & ClientEnvironment::getClientMap()
78 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
81 It is a failure if already is a local player
83 FATAL_ERROR_IF(m_local_player != NULL,
84 "Local player already allocated");
86 m_local_player = player;
89 void ClientEnvironment::step(float dtime)
91 /* Step time of day */
95 bool fly_allowed = m_client->checkLocalPrivilege("fly");
96 bool free_move = fly_allowed && g_settings->getBool("free_move");
99 LocalPlayer *lplayer = getLocalPlayer();
101 // collision info queue
102 std::vector<CollisionInfo> player_collisions;
105 Get the speed the player is going
107 bool is_climbing = lplayer->is_climbing;
109 f32 player_speed = lplayer->getSpeed().getLength();
112 Maximum position increment
114 //f32 position_max_increment = 0.05*BS;
115 f32 position_max_increment = 0.1*BS;
117 // Maximum time increment (for collision detection etc)
118 // time = distance / speed
119 f32 dtime_max_increment = 1;
120 if(player_speed > 0.001)
121 dtime_max_increment = position_max_increment / player_speed;
123 // Maximum time increment is 10ms or lower
124 if(dtime_max_increment > 0.01)
125 dtime_max_increment = 0.01;
127 // Don't allow overly huge dtime
131 f32 dtime_downcount = dtime;
134 Stuff that has a maximum time increment
143 if(dtime_downcount > dtime_max_increment)
145 dtime_part = dtime_max_increment;
146 dtime_downcount -= dtime_part;
150 dtime_part = dtime_downcount;
152 Setting this to 0 (no -=dtime_part) disables an infinite loop
153 when dtime_part is so small that dtime_downcount -= dtime_part
165 if (!free_move && !is_climbing) {
167 v3f speed = lplayer->getSpeed();
168 if (!lplayer->in_liquid)
169 speed.Y -= lplayer->movement_gravity *
170 lplayer->physics_override_gravity * dtime_part * 2.0f;
172 // Liquid floating / sinking
173 if (lplayer->in_liquid && !lplayer->swimming_vertical &&
174 !lplayer->swimming_pitch)
175 speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2.0f;
178 if (lplayer->in_liquid_stable || lplayer->in_liquid) {
179 // How much the node's viscosity blocks movement, ranges
180 // between 0 and 1. Should match the scale at which viscosity
181 // increase affects other liquid attributes.
182 static const f32 viscosity_factor = 0.3f;
184 v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
185 f32 dl = d_wanted.getLength();
186 if (dl > lplayer->movement_liquid_fluidity_smooth)
187 dl = lplayer->movement_liquid_fluidity_smooth;
189 dl *= (lplayer->liquid_viscosity * viscosity_factor) +
190 (1 - viscosity_factor);
191 v3f d = d_wanted.normalize() * (dl * dtime_part * 100.0f);
195 lplayer->setSpeed(speed);
200 This also does collision detection.
202 lplayer->move(dtime_part, this, position_max_increment,
205 } while (dtime_downcount > 0.001);
207 bool player_immortal = lplayer->getCAO() && lplayer->getCAO()->isImmortal();
209 for (const CollisionInfo &info : player_collisions) {
210 v3f speed_diff = info.new_speed - info.old_speed;;
211 // Handle only fall damage
212 // (because otherwise walking against something in fast_move kills you)
213 if (speed_diff.Y < 0 || info.old_speed.Y >= 0)
215 // Get rid of other components
218 f32 pre_factor = 1; // 1 hp per node/s
219 f32 tolerance = BS*14; // 5 without damage
220 f32 post_factor = 1; // 1 hp per node/s
221 if (info.type == COLLISION_NODE) {
222 const ContentFeatures &f = m_client->ndef()->
223 get(m_map->getNodeNoEx(info.node_p));
224 // Determine fall damage multiplier
225 int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
226 pre_factor = 1.0f + (float)addp / 100.0f;
228 float speed = pre_factor * speed_diff.getLength();
229 if (speed > tolerance && !player_immortal) {
230 f32 damage_f = (speed - tolerance) / BS * post_factor;
231 u16 damage = (u16)MYMIN(damage_f + 0.5, U16_MAX);
233 damageLocalPlayer(damage, true);
234 m_client->getEventManager()->put(
235 new SimpleTriggerEvent(MtEvent::PLAYER_FALLING_DAMAGE));
240 if (m_client->modsLoaded())
241 m_script->environment_step(dtime);
243 // Update lighting on local player (used for wield item)
244 u32 day_night_ratio = getDayNightRatio();
248 // On InvalidPositionException, use this as default
249 // (day: LIGHT_SUN, night: 0)
250 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
252 v3s16 p = lplayer->getLightPosition();
253 node_at_lplayer = m_map->getNodeNoEx(p);
255 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
256 final_color_blend(&lplayer->light_color, light, day_night_ratio);
260 Step active objects and update lighting of them
263 bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
264 auto cb_state = [this, dtime, update_lighting, day_night_ratio] (ClientActiveObject *cao) {
266 cao->step(dtime, this);
268 if (update_lighting) {
274 v3s16 p = cao->getLightPosition();
275 MapNode n = this->m_map->getNodeNoEx(p, &pos_ok);
277 light = n.getLightBlend(day_night_ratio, m_client->ndef());
279 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
281 cao->updateLight(light);
285 m_ao_manager.step(dtime, cb_state);
288 Step and handle simple objects
290 g_profiler->avg("CEnv: num of simple objects", m_simple_objects.size());
291 for (auto i = m_simple_objects.begin(); i != m_simple_objects.end();) {
293 ClientSimpleObject *simple = *cur;
296 if(simple->m_to_be_removed) {
298 i = m_simple_objects.erase(cur);
306 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
308 m_simple_objects.push_back(simple);
311 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
313 ClientActiveObject *obj = getActiveObject(id);
314 if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
315 return (GenericCAO*) obj;
320 bool isFreeClientActiveObjectId(const u16 id,
321 ClientActiveObjectMap &objects)
323 return id != 0 && objects.find(id) == objects.end();
327 u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
329 // try to reuse id's as late as possible
330 static u16 last_used_id = 0;
331 u16 startid = last_used_id;
334 if (isFreeClientActiveObjectId(last_used_id, objects))
337 if (last_used_id == startid)
342 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
344 // Register object. If failed return zero id
345 if (!m_ao_manager.registerObject(object))
348 object->addToScene(m_texturesource);
350 // Update lighting immediately
355 v3s16 p = object->getLightPosition();
356 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
358 light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
360 light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
362 object->updateLight(light);
363 return object->getId();
366 void ClientEnvironment::addActiveObject(u16 id, u8 type,
367 const std::string &init_data)
369 ClientActiveObject* obj =
370 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
373 infostream<<"ClientEnvironment::addActiveObject(): "
374 <<"id="<<id<<" type="<<type<<": Couldn't create object"
383 obj->initialize(init_data);
385 catch(SerializationError &e)
387 errorstream<<"ClientEnvironment::addActiveObject():"
388 <<" id="<<id<<" type="<<type
389 <<": SerializationError in initialize(): "
391 <<": init_data="<<serializeJsonString(init_data)
395 addActiveObject(obj);
398 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
400 ClientActiveObject *obj = getActiveObject(id);
402 infostream << "ClientEnvironment::processActiveObjectMessage():"
403 << " got message for id=" << id << ", which doesn't exist."
409 obj->processMessage(data);
410 } catch (SerializationError &e) {
411 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
412 << " id=" << id << " type=" << obj->getType()
413 << " SerializationError in processMessage(): " << e.what()
419 Callbacks for activeobjects
422 void ClientEnvironment::damageLocalPlayer(u16 damage, bool handle_hp)
424 LocalPlayer *lplayer = getLocalPlayer();
428 if (lplayer->hp > damage)
429 lplayer->hp -= damage;
434 ClientEnvEvent event;
435 event.type = CEE_PLAYER_DAMAGE;
436 event.player_damage.amount = damage;
437 event.player_damage.send_to_server = handle_hp;
438 m_client_event_queue.push(event);
442 Client likes to call these
445 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
447 FATAL_ERROR_IF(m_client_event_queue.empty(),
448 "ClientEnvironment::getClientEnvEvent(): queue is empty");
450 ClientEnvEvent event = m_client_event_queue.front();
451 m_client_event_queue.pop();
455 void ClientEnvironment::getSelectedActiveObjects(
456 const core::line3d<f32> &shootline_on_map,
457 std::vector<PointedThing> &objects)
459 std::vector<DistanceSortedActiveObject> allObjects;
460 getActiveObjects(shootline_on_map.start,
461 shootline_on_map.getLength() + 10.0f, allObjects);
462 const v3f line_vector = shootline_on_map.getVector();
464 for (const auto &allObject : allObjects) {
465 ClientActiveObject *obj = allObject.obj;
466 aabb3f selection_box;
467 if (!obj->getSelectionBox(&selection_box))
470 const v3f &pos = obj->getPosition();
471 aabb3f offsetted_box(selection_box.MinEdge + pos,
472 selection_box.MaxEdge + pos);
474 v3f current_intersection;
475 v3s16 current_normal;
476 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
477 ¤t_intersection, ¤t_normal)) {
478 objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
479 (current_intersection - shootline_on_map.start).getLengthSQ());