Fix Android build, but there is a remaining linking issue in guiConfirmRegistration
[oweals/minetest.git] / src / 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         // delete active objects
57         for (auto &active_object : m_active_objects) {
58                 delete active_object.second;
59         }
60
61         for (auto &simple_object : m_simple_objects) {
62                 delete simple_object;
63         }
64
65         // Drop/delete map
66         m_map->drop();
67
68         delete m_local_player;
69 }
70
71 Map & ClientEnvironment::getMap()
72 {
73         return *m_map;
74 }
75
76 ClientMap & ClientEnvironment::getClientMap()
77 {
78         return *m_map;
79 }
80
81 void ClientEnvironment::setLocalPlayer(LocalPlayer *player)
82 {
83         /*
84                 It is a failure if already is a local player
85         */
86         FATAL_ERROR_IF(m_local_player != NULL,
87                 "Local player already allocated");
88
89         m_local_player = player;
90 }
91
92 void ClientEnvironment::step(float dtime)
93 {
94         /* Step time of day */
95         stepTimeOfDay(dtime);
96
97         // Get some settings
98         bool fly_allowed = m_client->checkLocalPrivilege("fly");
99         bool free_move = fly_allowed && g_settings->getBool("free_move");
100
101         // Get local player
102         LocalPlayer *lplayer = getLocalPlayer();
103         assert(lplayer);
104         // collision info queue
105         std::vector<CollisionInfo> player_collisions;
106
107         /*
108                 Get the speed the player is going
109         */
110         bool is_climbing = lplayer->is_climbing;
111
112         f32 player_speed = lplayer->getSpeed().getLength();
113
114         /*
115                 Maximum position increment
116         */
117         //f32 position_max_increment = 0.05*BS;
118         f32 position_max_increment = 0.1*BS;
119
120         // Maximum time increment (for collision detection etc)
121         // time = distance / speed
122         f32 dtime_max_increment = 1;
123         if(player_speed > 0.001)
124                 dtime_max_increment = position_max_increment / player_speed;
125
126         // Maximum time increment is 10ms or lower
127         if(dtime_max_increment > 0.01)
128                 dtime_max_increment = 0.01;
129
130         // Don't allow overly huge dtime
131         if(dtime > 0.5)
132                 dtime = 0.5;
133
134         f32 dtime_downcount = dtime;
135
136         /*
137                 Stuff that has a maximum time increment
138         */
139
140         u32 loopcount = 0;
141         do
142         {
143                 loopcount++;
144
145                 f32 dtime_part;
146                 if(dtime_downcount > dtime_max_increment)
147                 {
148                         dtime_part = dtime_max_increment;
149                         dtime_downcount -= dtime_part;
150                 }
151                 else
152                 {
153                         dtime_part = dtime_downcount;
154                         /*
155                                 Setting this to 0 (no -=dtime_part) disables an infinite loop
156                                 when dtime_part is so small that dtime_downcount -= dtime_part
157                                 does nothing
158                         */
159                         dtime_downcount = 0;
160                 }
161
162                 /*
163                         Handle local player
164                 */
165
166                 {
167                         // Apply physics
168                         if(!free_move && !is_climbing)
169                         {
170                                 // Gravity
171                                 v3f speed = lplayer->getSpeed();
172                                 if(!lplayer->in_liquid)
173                                         speed.Y -= lplayer->movement_gravity * lplayer->physics_override_gravity * dtime_part * 2;
174
175                                 // Liquid floating / sinking
176                                 if(lplayer->in_liquid && !lplayer->swimming_vertical)
177                                         speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2;
178
179                                 // Liquid resistance
180                                 if(lplayer->in_liquid_stable || lplayer->in_liquid)
181                                 {
182                                         // How much the node's viscosity blocks movement, ranges between 0 and 1
183                                         // Should match the scale at which viscosity increase affects other liquid attributes
184                                         const f32 viscosity_factor = 0.3;
185
186                                         v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
187                                         f32 dl = d_wanted.getLength();
188                                         if(dl > lplayer->movement_liquid_fluidity_smooth)
189                                                 dl = lplayer->movement_liquid_fluidity_smooth;
190                                         dl *= (lplayer->liquid_viscosity * viscosity_factor) + (1 - viscosity_factor);
191
192                                         v3f d = d_wanted.normalize() * dl;
193                                         speed += d;
194                                 }
195
196                                 lplayer->setSpeed(speed);
197                         }
198
199                         /*
200                                 Move the lplayer.
201                                 This also does collision detection.
202                         */
203                         lplayer->move(dtime_part, this, position_max_increment,
204                                 &player_collisions);
205                 }
206         }
207         while(dtime_downcount > 0.001);
208
209         //std::cout<<"Looped "<<loopcount<<" times."<<std::endl;
210
211         bool player_immortal = lplayer->getCAO() && lplayer->getCAO()->isImmortal();
212
213         for (const CollisionInfo &info : player_collisions) {
214                 v3f speed_diff = info.new_speed - info.old_speed;;
215                 // Handle only fall damage
216                 // (because otherwise walking against something in fast_move kills you)
217                 if (speed_diff.Y < 0 || info.old_speed.Y >= 0)
218                         continue;
219                 // Get rid of other components
220                 speed_diff.X = 0;
221                 speed_diff.Z = 0;
222                 f32 pre_factor = 1; // 1 hp per node/s
223                 f32 tolerance = BS*14; // 5 without damage
224                 f32 post_factor = 1; // 1 hp per node/s
225                 if (info.type == COLLISION_NODE) {
226                         const ContentFeatures &f = m_client->ndef()->
227                                 get(m_map->getNodeNoEx(info.node_p));
228                         // Determine fall damage multiplier
229                         int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
230                         pre_factor = 1.0 + (float)addp/100.0;
231                 }
232                 float speed = pre_factor * speed_diff.getLength();
233                 if (speed > tolerance && !player_immortal) {
234                         f32 damage_f = (speed - tolerance) / BS * post_factor;
235                         u8 damage = (u8)MYMIN(damage_f + 0.5, 255);
236                         if (damage != 0) {
237                                 damageLocalPlayer(damage, true);
238                                 MtEvent *e = new SimpleTriggerEvent("PlayerFallingDamage");
239                                 m_client->event()->put(e);
240                         }
241                 }
242         }
243
244         if (m_client->moddingEnabled()) {
245                 m_script->environment_step(dtime);
246         }
247
248         // Update lighting on local player (used for wield item)
249         u32 day_night_ratio = getDayNightRatio();
250         {
251                 // Get node at head
252
253                 // On InvalidPositionException, use this as default
254                 // (day: LIGHT_SUN, night: 0)
255                 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
256
257                 v3s16 p = lplayer->getLightPosition();
258                 node_at_lplayer = m_map->getNodeNoEx(p);
259
260                 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
261                 final_color_blend(&lplayer->light_color, light, day_night_ratio);
262         }
263
264         /*
265                 Step active objects and update lighting of them
266         */
267
268         g_profiler->avg("CEnv: num of objects", m_active_objects.size());
269         bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
270         for (auto &ao_it : m_active_objects) {
271                 ClientActiveObject* obj = ao_it.second;
272                 // Step object
273                 obj->step(dtime, this);
274
275                 if (update_lighting) {
276                         // Update lighting
277                         u8 light = 0;
278                         bool pos_ok;
279
280                         // Get node at head
281                         v3s16 p = obj->getLightPosition();
282                         MapNode n = m_map->getNodeNoEx(p, &pos_ok);
283                         if (pos_ok)
284                                 light = n.getLightBlend(day_night_ratio, m_client->ndef());
285                         else
286                                 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
287
288                         obj->updateLight(light);
289                 }
290         }
291
292         /*
293                 Step and handle simple objects
294         */
295         g_profiler->avg("CEnv: num of simple objects", m_simple_objects.size());
296         for (auto i = m_simple_objects.begin(); i != m_simple_objects.end();) {
297                 auto cur = i;
298                 ClientSimpleObject *simple = *cur;
299
300                 simple->step(dtime);
301                 if(simple->m_to_be_removed) {
302                         delete simple;
303                         i = m_simple_objects.erase(cur);
304                 }
305                 else {
306                         ++i;
307                 }
308         }
309 }
310
311 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
312 {
313         m_simple_objects.push_back(simple);
314 }
315
316 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
317 {
318         ClientActiveObject *obj = getActiveObject(id);
319         if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
320                 return (GenericCAO*) obj;
321
322         return NULL;
323 }
324
325 ClientActiveObject* ClientEnvironment::getActiveObject(u16 id)
326 {
327         auto n = m_active_objects.find(id);
328         if (n == m_active_objects.end())
329                 return NULL;
330         return n->second;
331 }
332
333 bool isFreeClientActiveObjectId(const u16 id,
334         ClientActiveObjectMap &objects)
335 {
336         return id != 0 && objects.find(id) == objects.end();
337
338 }
339
340 u16 getFreeClientActiveObjectId(ClientActiveObjectMap &objects)
341 {
342         //try to reuse id's as late as possible
343         static u16 last_used_id = 0;
344         u16 startid = last_used_id;
345         for(;;) {
346                 last_used_id ++;
347                 if (isFreeClientActiveObjectId(last_used_id, objects))
348                         return last_used_id;
349
350                 if (last_used_id == startid)
351                         return 0;
352         }
353 }
354
355 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
356 {
357         assert(object); // Pre-condition
358         if(object->getId() == 0)
359         {
360                 u16 new_id = getFreeClientActiveObjectId(m_active_objects);
361                 if(new_id == 0)
362                 {
363                         infostream<<"ClientEnvironment::addActiveObject(): "
364                                 <<"no free ids available"<<std::endl;
365                         delete object;
366                         return 0;
367                 }
368                 object->setId(new_id);
369         }
370         if (!isFreeClientActiveObjectId(object->getId(), m_active_objects)) {
371                 infostream<<"ClientEnvironment::addActiveObject(): "
372                         <<"id is not free ("<<object->getId()<<")"<<std::endl;
373                 delete object;
374                 return 0;
375         }
376         infostream<<"ClientEnvironment::addActiveObject(): "
377                 <<"added (id="<<object->getId()<<")"<<std::endl;
378         m_active_objects[object->getId()] = object;
379         object->addToScene(m_texturesource);
380         { // Update lighting immediately
381                 u8 light = 0;
382                 bool pos_ok;
383
384                 // Get node at head
385                 v3s16 p = object->getLightPosition();
386                 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
387                 if (pos_ok)
388                         light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
389                 else
390                         light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
391
392                 object->updateLight(light);
393         }
394         return object->getId();
395 }
396
397 void ClientEnvironment::addActiveObject(u16 id, u8 type,
398         const std::string &init_data)
399 {
400         ClientActiveObject* obj =
401                 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
402         if(obj == NULL)
403         {
404                 infostream<<"ClientEnvironment::addActiveObject(): "
405                         <<"id="<<id<<" type="<<type<<": Couldn't create object"
406                         <<std::endl;
407                 return;
408         }
409
410         obj->setId(id);
411
412         try
413         {
414                 obj->initialize(init_data);
415         }
416         catch(SerializationError &e)
417         {
418                 errorstream<<"ClientEnvironment::addActiveObject():"
419                         <<" id="<<id<<" type="<<type
420                         <<": SerializationError in initialize(): "
421                         <<e.what()
422                         <<": init_data="<<serializeJsonString(init_data)
423                         <<std::endl;
424         }
425
426         addActiveObject(obj);
427 }
428
429 void ClientEnvironment::removeActiveObject(u16 id)
430 {
431         verbosestream<<"ClientEnvironment::removeActiveObject(): "
432                 <<"id="<<id<<std::endl;
433         ClientActiveObject* obj = getActiveObject(id);
434         if (obj == NULL) {
435                 infostream<<"ClientEnvironment::removeActiveObject(): "
436                         <<"id="<<id<<" not found"<<std::endl;
437                 return;
438         }
439         obj->removeFromScene(true);
440         delete obj;
441         m_active_objects.erase(id);
442 }
443
444 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
445 {
446         ClientActiveObject *obj = getActiveObject(id);
447         if (obj == NULL) {
448                 infostream << "ClientEnvironment::processActiveObjectMessage():"
449                         << " got message for id=" << id << ", which doesn't exist."
450                         << std::endl;
451                 return;
452         }
453
454         try {
455                 obj->processMessage(data);
456         } catch (SerializationError &e) {
457                 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
458                         << " id=" << id << " type=" << obj->getType()
459                         << " SerializationError in processMessage(): " << e.what()
460                         << std::endl;
461         }
462 }
463
464 /*
465         Callbacks for activeobjects
466 */
467
468 void ClientEnvironment::damageLocalPlayer(u8 damage, bool handle_hp)
469 {
470         LocalPlayer *lplayer = getLocalPlayer();
471         assert(lplayer);
472
473         if (handle_hp) {
474                 if (lplayer->hp > damage)
475                         lplayer->hp -= damage;
476                 else
477                         lplayer->hp = 0;
478         }
479
480         ClientEnvEvent event;
481         event.type = CEE_PLAYER_DAMAGE;
482         event.player_damage.amount = damage;
483         event.player_damage.send_to_server = handle_hp;
484         m_client_event_queue.push(event);
485 }
486
487 void ClientEnvironment::updateLocalPlayerBreath(u16 breath)
488 {
489         ClientEnvEvent event;
490         event.type = CEE_PLAYER_BREATH;
491         event.player_breath.amount = breath;
492         m_client_event_queue.push(event);
493 }
494
495 /*
496         Client likes to call these
497 */
498
499 void ClientEnvironment::getActiveObjects(v3f origin, f32 max_d,
500         std::vector<DistanceSortedActiveObject> &dest)
501 {
502         for (auto &ao_it : m_active_objects) {
503                 ClientActiveObject* obj = ao_it.second;
504
505                 f32 d = (obj->getPosition() - origin).getLength();
506
507                 if (d > max_d)
508                         continue;
509
510                 dest.emplace_back(obj, d);
511         }
512 }
513
514 ClientEnvEvent ClientEnvironment::getClientEnvEvent()
515 {
516         FATAL_ERROR_IF(m_client_event_queue.empty(),
517                         "ClientEnvironment::getClientEnvEvent(): queue is empty");
518
519         ClientEnvEvent event = m_client_event_queue.front();
520         m_client_event_queue.pop();
521         return event;
522 }
523
524 void ClientEnvironment::getSelectedActiveObjects(
525         const core::line3d<f32> &shootline_on_map,
526         std::vector<PointedThing> &objects)
527 {
528         std::vector<DistanceSortedActiveObject> allObjects;
529         getActiveObjects(shootline_on_map.start,
530                 shootline_on_map.getLength() + 10.0f, allObjects);
531         const v3f line_vector = shootline_on_map.getVector();
532
533         for (const auto &allObject : allObjects) {
534                 ClientActiveObject *obj = allObject.obj;
535                 aabb3f selection_box;
536                 if (!obj->getSelectionBox(&selection_box))
537                         continue;
538
539                 const v3f &pos = obj->getPosition();
540                 aabb3f offsetted_box(selection_box.MinEdge + pos,
541                         selection_box.MaxEdge + pos);
542
543                 v3f current_intersection;
544                 v3s16 current_normal;
545                 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
546                                 &current_intersection, &current_normal)) {
547                         objects.emplace_back((s16) obj->getId(), current_intersection, current_normal,
548                                 (current_intersection - shootline_on_map.start).getLengthSQ());
549                 }
550         }
551 }