[CSM] Add core.get_timeofday & core.get_day_count env calls (#5401)
[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 "clientenvironment.h"
23 #include "clientsimpleobject.h"
24 #include "clientmap.h"
25 #include "clientscripting.h"
26 #include "mapblock_mesh.h"
27 #include "event.h"
28 #include "collision.h"
29 #include "profiler.h"
30 #include "raycast.h"
31 #include "voxelalgorithms.h"
32 #include "settings.h"
33
34 /*
35         ClientEnvironment
36 */
37
38 ClientEnvironment::ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
39         ITextureSource *texturesource, Client *client,
40         IrrlichtDevice *irr):
41         Environment(client),
42         m_map(map),
43         m_local_player(NULL),
44         m_smgr(smgr),
45         m_texturesource(texturesource),
46         m_client(client),
47         m_script(NULL),
48         m_irr(irr)
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 (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
58                 i != m_active_objects.end(); ++i) {
59                 delete i->second;
60         }
61
62         for(std::vector<ClientSimpleObject*>::iterator
63                 i = m_simple_objects.begin(); i != m_simple_objects.end(); ++i) {
64                 delete *i;
65         }
66
67         // Drop/delete map
68         m_map->drop();
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         DSTACK(FUNCTION_NAME);
84         /*
85                 It is a failure if already is a local player
86         */
87         FATAL_ERROR_IF(m_local_player != NULL,
88                 "Local player already allocated");
89
90         m_local_player = player;
91 }
92
93 void ClientEnvironment::step(float dtime)
94 {
95         DSTACK(FUNCTION_NAME);
96
97         /* Step time of day */
98         stepTimeOfDay(dtime);
99
100         // Get some settings
101         bool fly_allowed = m_client->checkLocalPrivilege("fly");
102         bool free_move = fly_allowed && g_settings->getBool("free_move");
103
104         // Get local player
105         LocalPlayer *lplayer = getLocalPlayer();
106         assert(lplayer);
107         // collision info queue
108         std::vector<CollisionInfo> player_collisions;
109
110         /*
111                 Get the speed the player is going
112         */
113         bool is_climbing = lplayer->is_climbing;
114
115         f32 player_speed = lplayer->getSpeed().getLength();
116
117         /*
118                 Maximum position increment
119         */
120         //f32 position_max_increment = 0.05*BS;
121         f32 position_max_increment = 0.1*BS;
122
123         // Maximum time increment (for collision detection etc)
124         // time = distance / speed
125         f32 dtime_max_increment = 1;
126         if(player_speed > 0.001)
127                 dtime_max_increment = position_max_increment / player_speed;
128
129         // Maximum time increment is 10ms or lower
130         if(dtime_max_increment > 0.01)
131                 dtime_max_increment = 0.01;
132
133         // Don't allow overly huge dtime
134         if(dtime > 0.5)
135                 dtime = 0.5;
136
137         f32 dtime_downcount = dtime;
138
139         /*
140                 Stuff that has a maximum time increment
141         */
142
143         u32 loopcount = 0;
144         do
145         {
146                 loopcount++;
147
148                 f32 dtime_part;
149                 if(dtime_downcount > dtime_max_increment)
150                 {
151                         dtime_part = dtime_max_increment;
152                         dtime_downcount -= dtime_part;
153                 }
154                 else
155                 {
156                         dtime_part = dtime_downcount;
157                         /*
158                                 Setting this to 0 (no -=dtime_part) disables an infinite loop
159                                 when dtime_part is so small that dtime_downcount -= dtime_part
160                                 does nothing
161                         */
162                         dtime_downcount = 0;
163                 }
164
165                 /*
166                         Handle local player
167                 */
168
169                 {
170                         // Apply physics
171                         if(!free_move && !is_climbing)
172                         {
173                                 // Gravity
174                                 v3f speed = lplayer->getSpeed();
175                                 if(!lplayer->in_liquid)
176                                         speed.Y -= lplayer->movement_gravity * lplayer->physics_override_gravity * dtime_part * 2;
177
178                                 // Liquid floating / sinking
179                                 if(lplayer->in_liquid && !lplayer->swimming_vertical)
180                                         speed.Y -= lplayer->movement_liquid_sink * dtime_part * 2;
181
182                                 // Liquid resistance
183                                 if(lplayer->in_liquid_stable || lplayer->in_liquid)
184                                 {
185                                         // How much the node's viscosity blocks movement, ranges between 0 and 1
186                                         // Should match the scale at which viscosity increase affects other liquid attributes
187                                         const f32 viscosity_factor = 0.3;
188
189                                         v3f d_wanted = -speed / lplayer->movement_liquid_fluidity;
190                                         f32 dl = d_wanted.getLength();
191                                         if(dl > lplayer->movement_liquid_fluidity_smooth)
192                                                 dl = lplayer->movement_liquid_fluidity_smooth;
193                                         dl *= (lplayer->liquid_viscosity * viscosity_factor) + (1 - viscosity_factor);
194
195                                         v3f d = d_wanted.normalize() * dl;
196                                         speed += d;
197                                 }
198
199                                 lplayer->setSpeed(speed);
200                         }
201
202                         /*
203                                 Move the lplayer.
204                                 This also does collision detection.
205                         */
206                         lplayer->move(dtime_part, this, position_max_increment,
207                                 &player_collisions);
208                 }
209         }
210         while(dtime_downcount > 0.001);
211
212         //std::cout<<"Looped "<<loopcount<<" times."<<std::endl;
213
214         for(std::vector<CollisionInfo>::iterator i = player_collisions.begin();
215                 i != player_collisions.end(); ++i) {
216                 CollisionInfo &info = *i;
217                 v3f speed_diff = info.new_speed - info.old_speed;;
218                 // Handle only fall damage
219                 // (because otherwise walking against something in fast_move kills you)
220                 if(speed_diff.Y < 0 || info.old_speed.Y >= 0)
221                         continue;
222                 // Get rid of other components
223                 speed_diff.X = 0;
224                 speed_diff.Z = 0;
225                 f32 pre_factor = 1; // 1 hp per node/s
226                 f32 tolerance = BS*14; // 5 without damage
227                 f32 post_factor = 1; // 1 hp per node/s
228                 if(info.type == COLLISION_NODE)
229                 {
230                         const ContentFeatures &f = m_client->ndef()->
231                                 get(m_map->getNodeNoEx(info.node_p));
232                         // Determine fall damage multiplier
233                         int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
234                         pre_factor = 1.0 + (float)addp/100.0;
235                 }
236                 float speed = pre_factor * speed_diff.getLength();
237                 if(speed > tolerance)
238                 {
239                         f32 damage_f = (speed - tolerance)/BS * post_factor;
240                         u16 damage = (u16)(damage_f+0.5);
241                         if(damage != 0){
242                                 damageLocalPlayer(damage, true);
243                                 MtEvent *e = new SimpleTriggerEvent("PlayerFallingDamage");
244                                 m_client->event()->put(e);
245                         }
246                 }
247         }
248
249         if (m_client->moddingEnabled()) {
250                 m_script->environment_step(dtime);
251         }
252
253         /*
254                 A quick draft of lava damage
255         */
256         if(m_lava_hurt_interval.step(dtime, 1.0))
257         {
258                 v3f pf = lplayer->getPosition();
259
260                 // Feet, middle and head
261                 v3s16 p1 = floatToInt(pf + v3f(0, BS*0.1, 0), BS);
262                 MapNode n1 = m_map->getNodeNoEx(p1);
263                 v3s16 p2 = floatToInt(pf + v3f(0, BS*0.8, 0), BS);
264                 MapNode n2 = m_map->getNodeNoEx(p2);
265                 v3s16 p3 = floatToInt(pf + v3f(0, BS*1.6, 0), BS);
266                 MapNode n3 = m_map->getNodeNoEx(p3);
267
268                 u32 damage_per_second = 0;
269                 damage_per_second = MYMAX(damage_per_second,
270                         m_client->ndef()->get(n1).damage_per_second);
271                 damage_per_second = MYMAX(damage_per_second,
272                         m_client->ndef()->get(n2).damage_per_second);
273                 damage_per_second = MYMAX(damage_per_second,
274                         m_client->ndef()->get(n3).damage_per_second);
275
276                 if(damage_per_second != 0)
277                 {
278                         damageLocalPlayer(damage_per_second, true);
279                 }
280         }
281
282         // Protocol v29 make this behaviour obsolete
283         if (getGameDef()->getProtoVersion() < 29) {
284                 /*
285                         Drowning
286                 */
287                 if (m_drowning_interval.step(dtime, 2.0)) {
288                         v3f pf = lplayer->getPosition();
289
290                         // head
291                         v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
292                         MapNode n = m_map->getNodeNoEx(p);
293                         ContentFeatures c = m_client->ndef()->get(n);
294                         u8 drowning_damage = c.drowning;
295                         if (drowning_damage > 0 && lplayer->hp > 0) {
296                                 u16 breath = lplayer->getBreath();
297                                 if (breath > 10) {
298                                         breath = 11;
299                                 }
300                                 if (breath > 0) {
301                                         breath -= 1;
302                                 }
303                                 lplayer->setBreath(breath);
304                                 updateLocalPlayerBreath(breath);
305                         }
306
307                         if (lplayer->getBreath() == 0 && drowning_damage > 0) {
308                                 damageLocalPlayer(drowning_damage, true);
309                         }
310                 }
311                 if (m_breathing_interval.step(dtime, 0.5)) {
312                         v3f pf = lplayer->getPosition();
313
314                         // head
315                         v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
316                         MapNode n = m_map->getNodeNoEx(p);
317                         ContentFeatures c = m_client->ndef()->get(n);
318                         if (!lplayer->hp) {
319                                 lplayer->setBreath(11);
320                         } else if (c.drowning == 0) {
321                                 u16 breath = lplayer->getBreath();
322                                 if (breath <= 10) {
323                                         breath += 1;
324                                         lplayer->setBreath(breath);
325                                         updateLocalPlayerBreath(breath);
326                                 }
327                         }
328                 }
329         }
330
331         // Update lighting on local player (used for wield item)
332         u32 day_night_ratio = getDayNightRatio();
333         {
334                 // Get node at head
335
336                 // On InvalidPositionException, use this as default
337                 // (day: LIGHT_SUN, night: 0)
338                 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
339
340                 v3s16 p = lplayer->getLightPosition();
341                 node_at_lplayer = m_map->getNodeNoEx(p);
342
343                 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
344                 final_color_blend(&lplayer->light_color, light, day_night_ratio);
345         }
346
347         /*
348                 Step active objects and update lighting of them
349         */
350
351         g_profiler->avg("CEnv: num of objects", m_active_objects.size());
352         bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
353         for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
354                 i != m_active_objects.end(); ++i) {
355                 ClientActiveObject* obj = i->second;
356                 // Step object
357                 obj->step(dtime, this);
358
359                 if(update_lighting)
360                 {
361                         // Update lighting
362                         u8 light = 0;
363                         bool pos_ok;
364
365                         // Get node at head
366                         v3s16 p = obj->getLightPosition();
367                         MapNode n = m_map->getNodeNoEx(p, &pos_ok);
368                         if (pos_ok)
369                                 light = n.getLightBlend(day_night_ratio, m_client->ndef());
370                         else
371                                 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
372
373                         obj->updateLight(light);
374                 }
375         }
376
377         /*
378                 Step and handle simple objects
379         */
380         g_profiler->avg("CEnv: num of simple objects", m_simple_objects.size());
381         for(std::vector<ClientSimpleObject*>::iterator
382                 i = m_simple_objects.begin(); i != m_simple_objects.end();) {
383                 std::vector<ClientSimpleObject*>::iterator cur = i;
384                 ClientSimpleObject *simple = *cur;
385
386                 simple->step(dtime);
387                 if(simple->m_to_be_removed) {
388                         delete simple;
389                         i = m_simple_objects.erase(cur);
390                 }
391                 else {
392                         ++i;
393                 }
394         }
395 }
396
397 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
398 {
399         m_simple_objects.push_back(simple);
400 }
401
402 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
403 {
404         ClientActiveObject *obj = getActiveObject(id);
405         if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
406                 return (GenericCAO*) obj;
407         else
408                 return NULL;
409 }
410
411 ClientActiveObject* ClientEnvironment::getActiveObject(u16 id)
412 {
413         UNORDERED_MAP<u16, ClientActiveObject*>::iterator n = m_active_objects.find(id);
414         if (n == m_active_objects.end())
415                 return NULL;
416         return n->second;
417 }
418
419 bool isFreeClientActiveObjectId(const u16 id,
420         UNORDERED_MAP<u16, ClientActiveObject*> &objects)
421 {
422         if(id == 0)
423                 return false;
424
425         return objects.find(id) == objects.end();
426 }
427
428 u16 getFreeClientActiveObjectId(UNORDERED_MAP<u16, ClientActiveObject*> &objects)
429 {
430         //try to reuse id's as late as possible
431         static u16 last_used_id = 0;
432         u16 startid = last_used_id;
433         for(;;) {
434                 last_used_id ++;
435                 if (isFreeClientActiveObjectId(last_used_id, objects))
436                         return last_used_id;
437
438                 if (last_used_id == startid)
439                         return 0;
440         }
441 }
442
443 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
444 {
445         assert(object); // Pre-condition
446         if(object->getId() == 0)
447         {
448                 u16 new_id = getFreeClientActiveObjectId(m_active_objects);
449                 if(new_id == 0)
450                 {
451                         infostream<<"ClientEnvironment::addActiveObject(): "
452                                 <<"no free ids available"<<std::endl;
453                         delete object;
454                         return 0;
455                 }
456                 object->setId(new_id);
457         }
458         if (!isFreeClientActiveObjectId(object->getId(), m_active_objects)) {
459                 infostream<<"ClientEnvironment::addActiveObject(): "
460                         <<"id is not free ("<<object->getId()<<")"<<std::endl;
461                 delete object;
462                 return 0;
463         }
464         infostream<<"ClientEnvironment::addActiveObject(): "
465                 <<"added (id="<<object->getId()<<")"<<std::endl;
466         m_active_objects[object->getId()] = object;
467         object->addToScene(m_smgr, m_texturesource, m_irr);
468         { // Update lighting immediately
469                 u8 light = 0;
470                 bool pos_ok;
471
472                 // Get node at head
473                 v3s16 p = object->getLightPosition();
474                 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
475                 if (pos_ok)
476                         light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
477                 else
478                         light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
479
480                 object->updateLight(light);
481         }
482         return object->getId();
483 }
484
485 void ClientEnvironment::addActiveObject(u16 id, u8 type,
486         const std::string &init_data)
487 {
488         ClientActiveObject* obj =
489                 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
490         if(obj == NULL)
491         {
492                 infostream<<"ClientEnvironment::addActiveObject(): "
493                         <<"id="<<id<<" type="<<type<<": Couldn't create object"
494                         <<std::endl;
495                 return;
496         }
497
498         obj->setId(id);
499
500         try
501         {
502                 obj->initialize(init_data);
503         }
504         catch(SerializationError &e)
505         {
506                 errorstream<<"ClientEnvironment::addActiveObject():"
507                         <<" id="<<id<<" type="<<type
508                         <<": SerializationError in initialize(): "
509                         <<e.what()
510                         <<": init_data="<<serializeJsonString(init_data)
511                         <<std::endl;
512         }
513
514         addActiveObject(obj);
515 }
516
517 void ClientEnvironment::removeActiveObject(u16 id)
518 {
519         verbosestream<<"ClientEnvironment::removeActiveObject(): "
520                 <<"id="<<id<<std::endl;
521         ClientActiveObject* obj = getActiveObject(id);
522         if (obj == NULL) {
523                 infostream<<"ClientEnvironment::removeActiveObject(): "
524                         <<"id="<<id<<" not found"<<std::endl;
525                 return;
526         }
527         obj->removeFromScene(true);
528         delete obj;
529         m_active_objects.erase(id);
530 }
531
532 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
533 {
534         ClientActiveObject *obj = getActiveObject(id);
535         if (obj == NULL) {
536                 infostream << "ClientEnvironment::processActiveObjectMessage():"
537                         << " got message for id=" << id << ", which doesn't exist."
538                         << std::endl;
539                 return;
540         }
541
542         try {
543                 obj->processMessage(data);
544         } catch (SerializationError &e) {
545                 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
546                         << " id=" << id << " type=" << obj->getType()
547                         << " SerializationError in processMessage(): " << e.what()
548                         << std::endl;
549         }
550 }
551
552 /*
553         Callbacks for activeobjects
554 */
555
556 void ClientEnvironment::damageLocalPlayer(u8 damage, bool handle_hp)
557 {
558         LocalPlayer *lplayer = getLocalPlayer();
559         assert(lplayer);
560
561         if (handle_hp) {
562                 if (lplayer->hp > damage)
563                         lplayer->hp -= damage;
564                 else
565                         lplayer->hp = 0;
566         }
567
568         ClientEnvEvent event;
569         event.type = CEE_PLAYER_DAMAGE;
570         event.player_damage.amount = damage;
571         event.player_damage.send_to_server = handle_hp;
572         m_client_event_queue.push(event);
573 }
574
575 void ClientEnvironment::updateLocalPlayerBreath(u16 breath)
576 {
577         ClientEnvEvent event;
578         event.type = CEE_PLAYER_BREATH;
579         event.player_breath.amount = breath;
580         m_client_event_queue.push(event);
581 }
582
583 /*
584         Client likes to call these
585 */
586
587 void ClientEnvironment::getActiveObjects(v3f origin, f32 max_d,
588         std::vector<DistanceSortedActiveObject> &dest)
589 {
590         for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
591                 i != m_active_objects.end(); ++i) {
592                 ClientActiveObject* obj = i->second;
593
594                 f32 d = (obj->getPosition() - origin).getLength();
595
596                 if(d > max_d)
597                         continue;
598
599                 DistanceSortedActiveObject dso(obj, d);
600
601                 dest.push_back(dso);
602         }
603 }
604
605 ClientEnvEvent ClientEnvironment::getClientEvent()
606 {
607         ClientEnvEvent event;
608         if(m_client_event_queue.empty())
609                 event.type = CEE_NONE;
610         else {
611                 event = m_client_event_queue.front();
612                 m_client_event_queue.pop();
613         }
614         return event;
615 }
616
617 ClientActiveObject * ClientEnvironment::getSelectedActiveObject(
618         const core::line3d<f32> &shootline_on_map, v3f *intersection_point,
619         v3s16 *intersection_normal)
620 {
621         std::vector<DistanceSortedActiveObject> objects;
622         getActiveObjects(shootline_on_map.start,
623                 shootline_on_map.getLength() + 3, objects);
624         const v3f line_vector = shootline_on_map.getVector();
625
626         // Sort them.
627         // After this, the closest object is the first in the array.
628         std::sort(objects.begin(), objects.end());
629
630         /* Because objects can have different nodebox sizes,
631          * the object whose center is the nearest isn't necessarily
632          * the closest one. If an object is found, don't stop
633          * immediately. */
634
635         f32 d_min = shootline_on_map.getLength();
636         ClientActiveObject *nearest_obj = NULL;
637         for (u32 i = 0; i < objects.size(); i++) {
638                 ClientActiveObject *obj = objects[i].obj;
639
640                 aabb3f *selection_box = obj->getSelectionBox();
641                 if (selection_box == NULL)
642                         continue;
643
644                 v3f pos = obj->getPosition();
645
646                 aabb3f offsetted_box(selection_box->MinEdge + pos,
647                         selection_box->MaxEdge + pos);
648
649                 if (offsetted_box.getCenter().getDistanceFrom(
650                         shootline_on_map.start) > d_min + 9.6f*BS) {
651                         // Probably there is no active object that has bigger nodebox than
652                         // (-5.5,-5.5,-5.5,5.5,5.5,5.5)
653                         // 9.6 > 5.5*sqrt(3)
654                         break;
655                 }
656
657                 v3f current_intersection;
658                 v3s16 current_normal;
659                 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
660                         &current_intersection, &current_normal)) {
661                         f32 d_current = current_intersection.getDistanceFrom(
662                                 shootline_on_map.start);
663                         if (d_current <= d_min) {
664                                 d_min = d_current;
665                                 nearest_obj = obj;
666                                 *intersection_point = current_intersection;
667                                 *intersection_normal = current_normal;
668                         }
669                 }
670         }
671
672         return nearest_obj;
673 }
674
675 /*
676         Check if a node is pointable
677 */
678 static inline bool isPointableNode(const MapNode &n,
679         INodeDefManager *ndef, bool liquids_pointable)
680 {
681         const ContentFeatures &features = ndef->get(n);
682         return features.pointable ||
683                 (liquids_pointable && features.isLiquid());
684 }
685
686 PointedThing ClientEnvironment::getPointedThing(
687         core::line3d<f32> shootline,
688         bool liquids_pointable,
689         bool look_for_object)
690 {
691         PointedThing result;
692
693         INodeDefManager *nodedef = m_map->getNodeDefManager();
694
695         core::aabbox3d<s16> maximal_exceed = nodedef->getSelectionBoxIntUnion();
696         // The code needs to search these nodes
697         core::aabbox3d<s16> search_range(-maximal_exceed.MaxEdge,
698                 -maximal_exceed.MinEdge);
699         // If a node is found, there might be a larger node behind.
700         // To find it, we have to go further.
701         s16 maximal_overcheck =
702                 std::max(abs(search_range.MinEdge.X), abs(search_range.MaxEdge.X))
703                         + std::max(abs(search_range.MinEdge.Y), abs(search_range.MaxEdge.Y))
704                         + std::max(abs(search_range.MinEdge.Z), abs(search_range.MaxEdge.Z));
705
706         const v3f original_vector = shootline.getVector();
707         const f32 original_length = original_vector.getLength();
708
709         f32 min_distance = original_length;
710
711         // First try to find an active object
712         if (look_for_object) {
713                 ClientActiveObject *selected_object = getSelectedActiveObject(
714                         shootline, &result.intersection_point,
715                         &result.intersection_normal);
716
717                 if (selected_object != NULL) {
718                         min_distance =
719                                 (result.intersection_point - shootline.start).getLength();
720
721                         result.type = POINTEDTHING_OBJECT;
722                         result.object_id = selected_object->getId();
723                 }
724         }
725
726         // Reduce shootline
727         if (original_length > 0) {
728                 shootline.end = shootline.start
729                         + shootline.getVector() / original_length * min_distance;
730         }
731
732         // Try to find a node that is closer than the selected active
733         // object (if it exists).
734
735         voxalgo::VoxelLineIterator iterator(shootline.start / BS,
736                 shootline.getVector() / BS);
737         v3s16 oldnode = iterator.m_current_node_pos;
738         // Indicates that a node was found.
739         bool is_node_found = false;
740         // If a node is found, it is possible that there's a node
741         // behind it with a large nodebox, so continue the search.
742         u16 node_foundcounter = 0;
743         // If a node is found, this is the center of the
744         // first nodebox the shootline meets.
745         v3f found_boxcenter(0, 0, 0);
746         // The untested nodes are in this range.
747         core::aabbox3d<s16> new_nodes;
748         while (true) {
749                 // Test the nodes around the current node in search_range.
750                 new_nodes = search_range;
751                 new_nodes.MinEdge += iterator.m_current_node_pos;
752                 new_nodes.MaxEdge += iterator.m_current_node_pos;
753
754                 // Only check new nodes
755                 v3s16 delta = iterator.m_current_node_pos - oldnode;
756                 if (delta.X > 0)
757                         new_nodes.MinEdge.X = new_nodes.MaxEdge.X;
758                 else if (delta.X < 0)
759                         new_nodes.MaxEdge.X = new_nodes.MinEdge.X;
760                 else if (delta.Y > 0)
761                         new_nodes.MinEdge.Y = new_nodes.MaxEdge.Y;
762                 else if (delta.Y < 0)
763                         new_nodes.MaxEdge.Y = new_nodes.MinEdge.Y;
764                 else if (delta.Z > 0)
765                         new_nodes.MinEdge.Z = new_nodes.MaxEdge.Z;
766                 else if (delta.Z < 0)
767                         new_nodes.MaxEdge.Z = new_nodes.MinEdge.Z;
768
769                 // For each untested node
770                 for (s16 x = new_nodes.MinEdge.X; x <= new_nodes.MaxEdge.X; x++) {
771                         for (s16 y = new_nodes.MinEdge.Y; y <= new_nodes.MaxEdge.Y; y++) {
772                                 for (s16 z = new_nodes.MinEdge.Z; z <= new_nodes.MaxEdge.Z; z++) {
773                                         MapNode n;
774                                         v3s16 np(x, y, z);
775                                         bool is_valid_position;
776
777                                         n = m_map->getNodeNoEx(np, &is_valid_position);
778                                         if (!(is_valid_position &&
779                                                 isPointableNode(n, nodedef, liquids_pointable))) {
780                                                 continue;
781                                         }
782                                         std::vector<aabb3f> boxes;
783                                         n.getSelectionBoxes(nodedef, &boxes,
784                                                 n.getNeighbors(np, m_map));
785
786                                         v3f npf = intToFloat(np, BS);
787                                         for (std::vector<aabb3f>::const_iterator i = boxes.begin();
788                                                 i != boxes.end(); ++i) {
789                                                 aabb3f box = *i;
790                                                 box.MinEdge += npf;
791                                                 box.MaxEdge += npf;
792                                                 v3f intersection_point;
793                                                 v3s16 intersection_normal;
794                                                 if (!boxLineCollision(box, shootline.start, shootline.getVector(),
795                                                         &intersection_point, &intersection_normal)) {
796                                                         continue;
797                                                 }
798                                                 f32 distance = (intersection_point - shootline.start).getLength();
799                                                 if (distance >= min_distance) {
800                                                         continue;
801                                                 }
802                                                 result.type = POINTEDTHING_NODE;
803                                                 result.node_undersurface = np;
804                                                 result.intersection_point = intersection_point;
805                                                 result.intersection_normal = intersection_normal;
806                                                 found_boxcenter = box.getCenter();
807                                                 min_distance = distance;
808                                                 is_node_found = true;
809                                         }
810                                 }
811                         }
812                 }
813                 if (is_node_found) {
814                         node_foundcounter++;
815                         if (node_foundcounter > maximal_overcheck) {
816                                 break;
817                         }
818                 }
819                 // Next node
820                 if (iterator.hasNext()) {
821                         oldnode = iterator.m_current_node_pos;
822                         iterator.next();
823                 } else {
824                         break;
825                 }
826         }
827
828         if (is_node_found) {
829                 // Set undersurface and abovesurface nodes
830                 f32 d = 0.002 * BS;
831                 v3f fake_intersection = result.intersection_point;
832                 // Move intersection towards its source block.
833                 if (fake_intersection.X < found_boxcenter.X)
834                         fake_intersection.X += d;
835                 else
836                         fake_intersection.X -= d;
837
838                 if (fake_intersection.Y < found_boxcenter.Y)
839                         fake_intersection.Y += d;
840                 else
841                         fake_intersection.Y -= d;
842
843                 if (fake_intersection.Z < found_boxcenter.Z)
844                         fake_intersection.Z += d;
845                 else
846                         fake_intersection.Z -= d;
847
848                 result.node_real_undersurface = floatToInt(fake_intersection, BS);
849                 result.node_abovesurface = result.node_real_undersurface
850                         + result.intersection_normal;
851         }
852         return result;
853 }