7c2ec099ce017fff7f4afc37433e7838cd4aef9f
[oweals/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                                         speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2.0f;
175
176                                 // Liquid resistance
177                                 if (lplayer->in_liquid_stable || lplayer->in_liquid) {
178                                         // How much the node's viscosity blocks movement, ranges
179                                         // between 0 and 1. Should match the scale at which viscosity
180                                         // increase affects other liquid attributes.
181                                         static const f32 viscosity_factor = 0.3f;
182
183                                         v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
184                                         f32 dl = d_wanted.getLength();
185                                         if (dl > lplayer->movement_liquid_fluidity_smooth)
186                                                 dl = lplayer->movement_liquid_fluidity_smooth;
187
188                                         dl *= (lplayer->liquid_viscosity * viscosity_factor) +
189                                                 (1 - viscosity_factor);
190                                         v3f d = d_wanted.normalize() * (dl * dtime_part * 100.0f);
191                                         speed += d;
192                                 }
193
194                                 lplayer->setSpeed(speed);
195                         }
196
197                         /*
198                                 Move the lplayer.
199                                 This also does collision detection.
200                         */
201                         lplayer->move(dtime_part, this, position_max_increment,
202                                 &player_collisions);
203                 }
204         } while (dtime_downcount > 0.001);
205
206         bool player_immortal = lplayer->getCAO() && lplayer->getCAO()->isImmortal();
207
208         for (const CollisionInfo &info : player_collisions) {
209                 v3f speed_diff = info.new_speed - info.old_speed;;
210                 // Handle only fall damage
211                 // (because otherwise walking against something in fast_move kills you)
212                 if (speed_diff.Y < 0 || info.old_speed.Y >= 0)
213                         continue;
214                 // Get rid of other components
215                 speed_diff.X = 0;
216                 speed_diff.Z = 0;
217                 f32 pre_factor = 1; // 1 hp per node/s
218                 f32 tolerance = BS*14; // 5 without damage
219                 f32 post_factor = 1; // 1 hp per node/s
220                 if (info.type == COLLISION_NODE) {
221                         const ContentFeatures &f = m_client->ndef()->
222                                 get(m_map->getNodeNoEx(info.node_p));
223                         // Determine fall damage multiplier
224                         int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
225                         pre_factor = 1.0f + (float)addp / 100.0f;
226                 }
227                 float speed = pre_factor * speed_diff.getLength();
228                 if (speed > tolerance && !player_immortal) {
229                         f32 damage_f = (speed - tolerance) / BS * post_factor;
230                         u8 damage = (u8)MYMIN(damage_f + 0.5, 255);
231                         if (damage != 0) {
232                                 damageLocalPlayer(damage, true);
233                                 m_client->getEventManager()->put(
234                                         new SimpleTriggerEvent(MtEvent::PLAYER_FALLING_DAMAGE));
235                         }
236                 }
237         }
238
239         if (m_client->modsLoaded())
240                 m_script->environment_step(dtime);
241
242         // Update lighting on local player (used for wield item)
243         u32 day_night_ratio = getDayNightRatio();
244         {
245                 // Get node at head
246
247                 // On InvalidPositionException, use this as default
248                 // (day: LIGHT_SUN, night: 0)
249                 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
250
251                 v3s16 p = lplayer->getLightPosition();
252                 node_at_lplayer = m_map->getNodeNoEx(p);
253
254                 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
255                 final_color_blend(&lplayer->light_color, light, day_night_ratio);
256         }
257
258         /*
259                 Step active objects and update lighting of them
260         */
261
262         bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
263         auto cb_state = [this, dtime, update_lighting, day_night_ratio] (ClientActiveObject *cao) {
264                 // Step object
265                 cao->step(dtime, this);
266
267                 if (update_lighting) {
268                         // Update lighting
269                         u8 light = 0;
270                         bool pos_ok;
271
272                         // Get node at head
273                         v3s16 p = cao->getLightPosition();
274                         MapNode n = this->m_map->getNodeNoEx(p, &pos_ok);
275                         if (pos_ok)
276                                 light = n.getLightBlend(day_night_ratio, m_client->ndef());
277                         else
278                                 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
279
280                         cao->updateLight(light);
281                 }
282         };
283
284         m_ao_manager.step(dtime, cb_state);
285
286         /*
287                 Step and handle simple objects
288         */
289         g_profiler->avg("CEnv: num of simple objects", m_simple_objects.size());
290         for (auto i = m_simple_objects.begin(); i != m_simple_objects.end();) {
291                 auto cur = i;
292                 ClientSimpleObject *simple = *cur;
293
294                 simple->step(dtime);
295                 if(simple->m_to_be_removed) {
296                         delete simple;
297                         i = m_simple_objects.erase(cur);
298                 }
299                 else {
300                         ++i;
301                 }
302         }
303 }
304
305 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
306 {
307         m_simple_objects.push_back(simple);
308 }
309
310 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
311 {
312         ClientActiveObject *obj = getActiveObject(id);
313         if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
314                 return (GenericCAO*) obj;
315
316         return NULL;
317 }
318
319 bool isFreeClientActiveObjectId(const u16 id,
320         ClientActiveObjectMap &objects)
321 {
322         return id != 0 && objects.find(id) == objects.end();
323
324 }
325
326 u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
327 {
328         // try to reuse id's as late as possible
329         static u16 last_used_id = 0;
330         u16 startid = last_used_id;
331         for(;;) {
332                 last_used_id ++;
333                 if (isFreeClientActiveObjectId(last_used_id, objects))
334                         return last_used_id;
335
336                 if (last_used_id == startid)
337                         return 0;
338         }
339 }
340
341 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
342 {
343         // Register object. If failed return zero id
344         if (!m_ao_manager.registerObject(object))
345                 return 0;
346
347         object->addToScene(m_texturesource);
348
349         // Update lighting immediately
350         u8 light = 0;
351         bool pos_ok;
352
353         // Get node at head
354         v3s16 p = object->getLightPosition();
355         MapNode n = m_map->getNodeNoEx(p, &pos_ok);
356         if (pos_ok)
357                 light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
358         else
359                 light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
360
361         object->updateLight(light);
362         return object->getId();
363 }
364
365 void ClientEnvironment::addActiveObject(u16 id, u8 type,
366         const std::string &init_data)
367 {
368         ClientActiveObject* obj =
369                 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
370         if(obj == NULL)
371         {
372                 infostream<<"ClientEnvironment::addActiveObject(): "
373                         <<"id="<<id<<" type="<<type<<": Couldn't create object"
374                         <<std::endl;
375                 return;
376         }
377
378         obj->setId(id);
379
380         try
381         {
382                 obj->initialize(init_data);
383         }
384         catch(SerializationError &e)
385         {
386                 errorstream<<"ClientEnvironment::addActiveObject():"
387                         <<" id="<<id<<" type="<<type
388                         <<": SerializationError in initialize(): "
389                         <<e.what()
390                         <<": init_data="<<serializeJsonString(init_data)
391                         <<std::endl;
392         }
393
394         addActiveObject(obj);
395 }
396
397 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
398 {
399         ClientActiveObject *obj = getActiveObject(id);
400         if (obj == NULL) {
401                 infostream << "ClientEnvironment::processActiveObjectMessage():"
402                         << " got message for id=" << id << ", which doesn't exist."
403                         << std::endl;
404                 return;
405         }
406
407         try {
408                 obj->processMessage(data);
409         } catch (SerializationError &e) {
410                 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
411                         << " id=" << id << " type=" << obj->getType()
412                         << " SerializationError in processMessage(): " << e.what()
413                         << std::endl;
414         }
415 }
416
417 /*
418         Callbacks for activeobjects
419 */
420
421 void ClientEnvironment::damageLocalPlayer(u8 damage, bool handle_hp)
422 {
423         LocalPlayer *lplayer = getLocalPlayer();
424         assert(lplayer);
425
426         if (handle_hp) {
427                 if (lplayer->hp > damage)
428                         lplayer->hp -= damage;
429                 else
430                         lplayer->hp = 0;
431         }
432
433         ClientEnvEvent event;
434         event.type = CEE_PLAYER_DAMAGE;
435         event.player_damage.amount = damage;
436         event.player_damage.send_to_server = handle_hp;
437         m_client_event_queue.push(event);
438 }
439
440 /*
441         Client likes to call these
442 */
443
444 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
445 {
446         FATAL_ERROR_IF(m_client_event_queue.empty(),
447                         "ClientEnvironment::getClientEnvEvent(): queue is empty");
448
449         ClientEnvEvent event = m_client_event_queue.front();
450         m_client_event_queue.pop();
451         return event;
452 }
453
454 void ClientEnvironment::getSelectedActiveObjects(
455         const core::line3d<f32> &shootline_on_map,
456         std::vector<PointedThing> &objects)
457 {
458         std::vector<DistanceSortedActiveObject> allObjects;
459         getActiveObjects(shootline_on_map.start,
460                 shootline_on_map.getLength() + 10.0f, allObjects);
461         const v3f line_vector = shootline_on_map.getVector();
462
463         for (const auto &allObject : allObjects) {
464                 ClientActiveObject *obj = allObject.obj;
465                 aabb3f selection_box;
466                 if (!obj->getSelectionBox(&selection_box))
467                         continue;
468
469                 const v3f &pos = obj->getPosition();
470                 aabb3f offsetted_box(selection_box.MinEdge + pos,
471                         selection_box.MaxEdge + pos);
472
473                 v3f current_intersection;
474                 v3s16 current_normal;
475                 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
476                                 &current_intersection, &current_normal)) {
477                         objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
478                                 (current_intersection - shootline_on_map.start).getLengthSQ());
479                 }
480         }
481 }