]> git.lizzy.rs Git - minetest.git/blob - src/client/clientenvironment.cpp
Consistent HP and damage types (#8167)
[minetest.git] / src / client / clientenvironment.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2017 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "util/serialize.h"
21 #include "util/pointedthing.h"
22 #include "client.h"
23 #include "clientenvironment.h"
24 #include "clientsimpleobject.h"
25 #include "clientmap.h"
26 #include "scripting_client.h"
27 #include "mapblock_mesh.h"
28 #include "event.h"
29 #include "collision.h"
30 #include "nodedef.h"
31 #include "profiler.h"
32 #include "raycast.h"
33 #include "voxelalgorithms.h"
34 #include "settings.h"
35 #include "content_cao.h"
36 #include <algorithm>
37 #include "client/renderingengine.h"
38
39 /*
40         ClientEnvironment
41 */
42
43 ClientEnvironment::ClientEnvironment(ClientMap *map,
44         ITextureSource *texturesource, Client *client):
45         Environment(client),
46         m_map(map),
47         m_texturesource(texturesource),
48         m_client(client)
49 {
50         char zero = 0;
51         memset(attachement_parent_ids, zero, sizeof(attachement_parent_ids));
52 }
53
54 ClientEnvironment::~ClientEnvironment()
55 {
56         m_ao_manager.clear();
57
58         for (auto &simple_object : m_simple_objects) {
59                 delete simple_object;
60         }
61
62         // Drop/delete map
63         m_map->drop();
64
65         delete m_local_player;
66 }
67
68 Map & ClientEnvironment::getMap()
69 {
70         return *m_map;
71 }
72
73 ClientMap & ClientEnvironment::getClientMap()
74 {
75         return *m_map;
76 }
77
78 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
79 {
80         /*
81                 It is a failure if already is a local player
82         */
83         FATAL_ERROR_IF(m_local_player != NULL,
84                 "Local player already allocated");
85
86         m_local_player = player;
87 }
88
89 void ClientEnvironment::step(float dtime)
90 {
91         /* Step time of day */
92         stepTimeOfDay(dtime);
93
94         // Get some settings
95         bool fly_allowed = m_client->checkLocalPrivilege("fly");
96         bool free_move = fly_allowed && g_settings->getBool("free_move");
97
98         // Get local player
99         LocalPlayer *lplayer = getLocalPlayer();
100         assert(lplayer);
101         // collision info queue
102         std::vector<CollisionInfo> player_collisions;
103
104         /*
105                 Get the speed the player is going
106         */
107         bool is_climbing = lplayer->is_climbing;
108
109         f32 player_speed = lplayer->getSpeed().getLength();
110
111         /*
112                 Maximum position increment
113         */
114         //f32 position_max_increment = 0.05*BS;
115         f32 position_max_increment = 0.1*BS;
116
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;
122
123         // Maximum time increment is 10ms or lower
124         if(dtime_max_increment > 0.01)
125                 dtime_max_increment = 0.01;
126
127         // Don't allow overly huge dtime
128         if(dtime > 0.5)
129                 dtime = 0.5;
130
131         f32 dtime_downcount = dtime;
132
133         /*
134                 Stuff that has a maximum time increment
135         */
136
137         u32 loopcount = 0;
138         do
139         {
140                 loopcount++;
141
142                 f32 dtime_part;
143                 if(dtime_downcount > dtime_max_increment)
144                 {
145                         dtime_part = dtime_max_increment;
146                         dtime_downcount -= dtime_part;
147                 }
148                 else
149                 {
150                         dtime_part = dtime_downcount;
151                         /*
152                                 Setting this to 0 (no -=dtime_part) disables an infinite loop
153                                 when dtime_part is so small that dtime_downcount -= dtime_part
154                                 does nothing
155                         */
156                         dtime_downcount = 0;
157                 }
158
159                 /*
160                         Handle local player
161                 */
162
163                 {
164                         // Apply physics
165                         if (!free_move && !is_climbing) {
166                                 // Gravity
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;
171
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;
176
177                                 // Liquid resistance
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;
183
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;
188
189                                         dl *= (lplayer->liquid_viscosity * viscosity_factor) +
190                                                 (1 - viscosity_factor);
191                                         v3f d = d_wanted.normalize() * (dl * dtime_part * 100.0f);
192                                         speed += d;
193                                 }
194
195                                 lplayer->setSpeed(speed);
196                         }
197
198                         /*
199                                 Move the lplayer.
200                                 This also does collision detection.
201                         */
202                         lplayer->move(dtime_part, this, position_max_increment,
203                                 &player_collisions);
204                 }
205         } while (dtime_downcount > 0.001);
206
207         bool player_immortal = lplayer->getCAO() && lplayer->getCAO()->isImmortal();
208
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)
214                         continue;
215                 // Get rid of other components
216                 speed_diff.X = 0;
217                 speed_diff.Z = 0;
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;
227                 }
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);
232                         if (damage != 0) {
233                                 damageLocalPlayer(damage, true);
234                                 m_client->getEventManager()->put(
235                                         new SimpleTriggerEvent(MtEvent::PLAYER_FALLING_DAMAGE));
236                         }
237                 }
238         }
239
240         if (m_client->modsLoaded())
241                 m_script->environment_step(dtime);
242
243         // Update lighting on local player (used for wield item)
244         u32 day_night_ratio = getDayNightRatio();
245         {
246                 // Get node at head
247
248                 // On InvalidPositionException, use this as default
249                 // (day: LIGHT_SUN, night: 0)
250                 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
251
252                 v3s16 p = lplayer->getLightPosition();
253                 node_at_lplayer = m_map->getNodeNoEx(p);
254
255                 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
256                 final_color_blend(&lplayer->light_color, light, day_night_ratio);
257         }
258
259         /*
260                 Step active objects and update lighting of them
261         */
262
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) {
265                 // Step object
266                 cao->step(dtime, this);
267
268                 if (update_lighting) {
269                         // Update lighting
270                         u8 light = 0;
271                         bool pos_ok;
272
273                         // Get node at head
274                         v3s16 p = cao->getLightPosition();
275                         MapNode n = this->m_map->getNodeNoEx(p, &pos_ok);
276                         if (pos_ok)
277                                 light = n.getLightBlend(day_night_ratio, m_client->ndef());
278                         else
279                                 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
280
281                         cao->updateLight(light);
282                 }
283         };
284
285         m_ao_manager.step(dtime, cb_state);
286
287         /*
288                 Step and handle simple objects
289         */
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();) {
292                 auto cur = i;
293                 ClientSimpleObject *simple = *cur;
294
295                 simple->step(dtime);
296                 if(simple->m_to_be_removed) {
297                         delete simple;
298                         i = m_simple_objects.erase(cur);
299                 }
300                 else {
301                         ++i;
302                 }
303         }
304 }
305
306 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
307 {
308         m_simple_objects.push_back(simple);
309 }
310
311 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
312 {
313         ClientActiveObject *obj = getActiveObject(id);
314         if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
315                 return (GenericCAO*) obj;
316
317         return NULL;
318 }
319
320 bool isFreeClientActiveObjectId(const u16 id,
321         ClientActiveObjectMap &objects)
322 {
323         return id != 0 && objects.find(id) == objects.end();
324
325 }
326
327 u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
328 {
329         // try to reuse id's as late as possible
330         static u16 last_used_id = 0;
331         u16 startid = last_used_id;
332         for(;;) {
333                 last_used_id ++;
334                 if (isFreeClientActiveObjectId(last_used_id, objects))
335                         return last_used_id;
336
337                 if (last_used_id == startid)
338                         return 0;
339         }
340 }
341
342 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
343 {
344         // Register object. If failed return zero id
345         if (!m_ao_manager.registerObject(object))
346                 return 0;
347
348         object->addToScene(m_texturesource);
349
350         // Update lighting immediately
351         u8 light = 0;
352         bool pos_ok;
353
354         // Get node at head
355         v3s16 p = object->getLightPosition();
356         MapNode n = m_map->getNodeNoEx(p, &pos_ok);
357         if (pos_ok)
358                 light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
359         else
360                 light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
361
362         object->updateLight(light);
363         return object->getId();
364 }
365
366 void ClientEnvironment::addActiveObject(u16 id, u8 type,
367         const std::string &init_data)
368 {
369         ClientActiveObject* obj =
370                 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
371         if(obj == NULL)
372         {
373                 infostream<<"ClientEnvironment::addActiveObject(): "
374                         <<"id="<<id<<" type="<<type<<": Couldn't create object"
375                         <<std::endl;
376                 return;
377         }
378
379         obj->setId(id);
380
381         try
382         {
383                 obj->initialize(init_data);
384         }
385         catch(SerializationError &e)
386         {
387                 errorstream<<"ClientEnvironment::addActiveObject():"
388                         <<" id="<<id<<" type="<<type
389                         <<": SerializationError in initialize(): "
390                         <<e.what()
391                         <<": init_data="<<serializeJsonString(init_data)
392                         <<std::endl;
393         }
394
395         addActiveObject(obj);
396 }
397
398 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
399 {
400         ClientActiveObject *obj = getActiveObject(id);
401         if (obj == NULL) {
402                 infostream << "ClientEnvironment::processActiveObjectMessage():"
403                         << " got message for id=" << id << ", which doesn't exist."
404                         << std::endl;
405                 return;
406         }
407
408         try {
409                 obj->processMessage(data);
410         } catch (SerializationError &e) {
411                 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
412                         << " id=" << id << " type=" << obj->getType()
413                         << " SerializationError in processMessage(): " << e.what()
414                         << std::endl;
415         }
416 }
417
418 /*
419         Callbacks for activeobjects
420 */
421
422 void ClientEnvironment::damageLocalPlayer(u16 damage, bool handle_hp)
423 {
424         LocalPlayer *lplayer = getLocalPlayer();
425         assert(lplayer);
426
427         if (handle_hp) {
428                 if (lplayer->hp > damage)
429                         lplayer->hp -= damage;
430                 else
431                         lplayer->hp = 0;
432         }
433
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);
439 }
440
441 /*
442         Client likes to call these
443 */
444
445 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
446 {
447         FATAL_ERROR_IF(m_client_event_queue.empty(),
448                         "ClientEnvironment::getClientEnvEvent(): queue is empty");
449
450         ClientEnvEvent event = m_client_event_queue.front();
451         m_client_event_queue.pop();
452         return event;
453 }
454
455 void ClientEnvironment::getSelectedActiveObjects(
456         const core::line3d<f32> &shootline_on_map,
457         std::vector<PointedThing> &objects)
458 {
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();
463
464         for (const auto &allObject : allObjects) {
465                 ClientActiveObject *obj = allObject.obj;
466                 aabb3f selection_box;
467                 if (!obj->getSelectionBox(&selection_box))
468                         continue;
469
470                 const v3f &pos = obj->getPosition();
471                 aabb3f offsetted_box(selection_box.MinEdge + pos,
472                         selection_box.MaxEdge + pos);
473
474                 v3f current_intersection;
475                 v3s16 current_normal;
476                 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
477                                 &current_intersection, &current_normal)) {
478                         objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
479                                 (current_intersection - shootline_on_map.start).getLengthSQ());
480                 }
481         }
482 }