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