]> git.lizzy.rs Git - minetest.git/blob - src/clientenvironment.cpp
Cleanup some header inclusions to improve compilation times
[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 "mapblock_mesh.h"
26 #include "event.h"
27 #include "collision.h"
28 #include "profiler.h"
29 #include "raycast.h"
30 #include "voxelalgorithms.h"
31 #include "settings.h"
32
33 /*
34         ClientEnvironment
35 */
36
37 ClientEnvironment::ClientEnvironment(ClientMap *map, scene::ISceneManager *smgr,
38         ITextureSource *texturesource, Client *client,
39         IrrlichtDevice *irr):
40         m_map(map),
41         m_local_player(NULL),
42         m_smgr(smgr),
43         m_texturesource(texturesource),
44         m_client(client),
45         m_irr(irr)
46 {
47         char zero = 0;
48         memset(attachement_parent_ids, zero, sizeof(attachement_parent_ids));
49 }
50
51 ClientEnvironment::~ClientEnvironment()
52 {
53         // delete active objects
54         for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
55                 i != m_active_objects.end(); ++i) {
56                 delete i->second;
57         }
58
59         for(std::vector<ClientSimpleObject*>::iterator
60                 i = m_simple_objects.begin(); i != m_simple_objects.end(); ++i) {
61                 delete *i;
62         }
63
64         // Drop/delete map
65         m_map->drop();
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         DSTACK(FUNCTION_NAME);
81         /*
82                 It is a failure if already is a local player
83         */
84         FATAL_ERROR_IF(m_local_player != NULL,
85                 "Local player already allocated");
86
87         m_local_player = player;
88 }
89
90 void ClientEnvironment::step(float dtime)
91 {
92         DSTACK(FUNCTION_NAME);
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         for(std::vector<CollisionInfo>::iterator i = player_collisions.begin();
212                 i != player_collisions.end(); ++i) {
213                 CollisionInfo &info = *i;
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                 {
227                         const ContentFeatures &f = m_client->ndef()->
228                                 get(m_map->getNodeNoEx(info.node_p));
229                         // Determine fall damage multiplier
230                         int addp = itemgroup_get(f.groups, "fall_damage_add_percent");
231                         pre_factor = 1.0 + (float)addp/100.0;
232                 }
233                 float speed = pre_factor * speed_diff.getLength();
234                 if(speed > tolerance)
235                 {
236                         f32 damage_f = (speed - tolerance)/BS * post_factor;
237                         u16 damage = (u16)(damage_f+0.5);
238                         if(damage != 0){
239                                 damageLocalPlayer(damage, true);
240                                 MtEvent *e = new SimpleTriggerEvent("PlayerFallingDamage");
241                                 m_client->event()->put(e);
242                         }
243                 }
244         }
245
246         /*
247                 A quick draft of lava damage
248         */
249         if(m_lava_hurt_interval.step(dtime, 1.0))
250         {
251                 v3f pf = lplayer->getPosition();
252
253                 // Feet, middle and head
254                 v3s16 p1 = floatToInt(pf + v3f(0, BS*0.1, 0), BS);
255                 MapNode n1 = m_map->getNodeNoEx(p1);
256                 v3s16 p2 = floatToInt(pf + v3f(0, BS*0.8, 0), BS);
257                 MapNode n2 = m_map->getNodeNoEx(p2);
258                 v3s16 p3 = floatToInt(pf + v3f(0, BS*1.6, 0), BS);
259                 MapNode n3 = m_map->getNodeNoEx(p3);
260
261                 u32 damage_per_second = 0;
262                 damage_per_second = MYMAX(damage_per_second,
263                         m_client->ndef()->get(n1).damage_per_second);
264                 damage_per_second = MYMAX(damage_per_second,
265                         m_client->ndef()->get(n2).damage_per_second);
266                 damage_per_second = MYMAX(damage_per_second,
267                         m_client->ndef()->get(n3).damage_per_second);
268
269                 if(damage_per_second != 0)
270                 {
271                         damageLocalPlayer(damage_per_second, true);
272                 }
273         }
274
275         // Protocol v29 make this behaviour obsolete
276         if (getGameDef()->getProtoVersion() < 29) {
277                 /*
278                         Drowning
279                 */
280                 if (m_drowning_interval.step(dtime, 2.0)) {
281                         v3f pf = lplayer->getPosition();
282
283                         // head
284                         v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
285                         MapNode n = m_map->getNodeNoEx(p);
286                         ContentFeatures c = m_client->ndef()->get(n);
287                         u8 drowning_damage = c.drowning;
288                         if (drowning_damage > 0 && lplayer->hp > 0) {
289                                 u16 breath = lplayer->getBreath();
290                                 if (breath > 10) {
291                                         breath = 11;
292                                 }
293                                 if (breath > 0) {
294                                         breath -= 1;
295                                 }
296                                 lplayer->setBreath(breath);
297                                 updateLocalPlayerBreath(breath);
298                         }
299
300                         if (lplayer->getBreath() == 0 && drowning_damage > 0) {
301                                 damageLocalPlayer(drowning_damage, true);
302                         }
303                 }
304                 if (m_breathing_interval.step(dtime, 0.5)) {
305                         v3f pf = lplayer->getPosition();
306
307                         // head
308                         v3s16 p = floatToInt(pf + v3f(0, BS * 1.6, 0), BS);
309                         MapNode n = m_map->getNodeNoEx(p);
310                         ContentFeatures c = m_client->ndef()->get(n);
311                         if (!lplayer->hp) {
312                                 lplayer->setBreath(11);
313                         } else if (c.drowning == 0) {
314                                 u16 breath = lplayer->getBreath();
315                                 if (breath <= 10) {
316                                         breath += 1;
317                                         lplayer->setBreath(breath);
318                                         updateLocalPlayerBreath(breath);
319                                 }
320                         }
321                 }
322         }
323
324         // Update lighting on local player (used for wield item)
325         u32 day_night_ratio = getDayNightRatio();
326         {
327                 // Get node at head
328
329                 // On InvalidPositionException, use this as default
330                 // (day: LIGHT_SUN, night: 0)
331                 MapNode node_at_lplayer(CONTENT_AIR, 0x0f, 0);
332
333                 v3s16 p = lplayer->getLightPosition();
334                 node_at_lplayer = m_map->getNodeNoEx(p);
335
336                 u16 light = getInteriorLight(node_at_lplayer, 0, m_client->ndef());
337                 u8 day = light & 0xff;
338                 u8 night = (light >> 8) & 0xff;
339                 finalColorBlend(lplayer->light_color, day, night, day_night_ratio);
340         }
341
342         /*
343                 Step active objects and update lighting of them
344         */
345
346         g_profiler->avg("CEnv: num of objects", m_active_objects.size());
347         bool update_lighting = m_active_object_light_update_interval.step(dtime, 0.21);
348         for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
349                 i != m_active_objects.end(); ++i) {
350                 ClientActiveObject* obj = i->second;
351                 // Step object
352                 obj->step(dtime, this);
353
354                 if(update_lighting)
355                 {
356                         // Update lighting
357                         u8 light = 0;
358                         bool pos_ok;
359
360                         // Get node at head
361                         v3s16 p = obj->getLightPosition();
362                         MapNode n = m_map->getNodeNoEx(p, &pos_ok);
363                         if (pos_ok)
364                                 light = n.getLightBlend(day_night_ratio, m_client->ndef());
365                         else
366                                 light = blend_light(day_night_ratio, LIGHT_SUN, 0);
367
368                         obj->updateLight(light);
369                 }
370         }
371
372         /*
373                 Step and handle simple objects
374         */
375         g_profiler->avg("CEnv: num of simple objects", m_simple_objects.size());
376         for(std::vector<ClientSimpleObject*>::iterator
377                 i = m_simple_objects.begin(); i != m_simple_objects.end();) {
378                 std::vector<ClientSimpleObject*>::iterator cur = i;
379                 ClientSimpleObject *simple = *cur;
380
381                 simple->step(dtime);
382                 if(simple->m_to_be_removed) {
383                         delete simple;
384                         i = m_simple_objects.erase(cur);
385                 }
386                 else {
387                         ++i;
388                 }
389         }
390 }
391
392 void ClientEnvironment::addSimpleObject(ClientSimpleObject *simple)
393 {
394         m_simple_objects.push_back(simple);
395 }
396
397 GenericCAO* ClientEnvironment::getGenericCAO(u16 id)
398 {
399         ClientActiveObject *obj = getActiveObject(id);
400         if (obj && obj->getType() == ACTIVEOBJECT_TYPE_GENERIC)
401                 return (GenericCAO*) obj;
402         else
403                 return NULL;
404 }
405
406 ClientActiveObject* ClientEnvironment::getActiveObject(u16 id)
407 {
408         UNORDERED_MAP<u16, ClientActiveObject*>::iterator n = m_active_objects.find(id);
409         if (n == m_active_objects.end())
410                 return NULL;
411         return n->second;
412 }
413
414 bool isFreeClientActiveObjectId(const u16 id,
415         UNORDERED_MAP<u16, ClientActiveObject*> &objects)
416 {
417         if(id == 0)
418                 return false;
419
420         return objects.find(id) == objects.end();
421 }
422
423 u16 getFreeClientActiveObjectId(UNORDERED_MAP<u16, ClientActiveObject*> &objects)
424 {
425         //try to reuse id's as late as possible
426         static u16 last_used_id = 0;
427         u16 startid = last_used_id;
428         for(;;) {
429                 last_used_id ++;
430                 if (isFreeClientActiveObjectId(last_used_id, objects))
431                         return last_used_id;
432
433                 if (last_used_id == startid)
434                         return 0;
435         }
436 }
437
438 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
439 {
440         assert(object); // Pre-condition
441         if(object->getId() == 0)
442         {
443                 u16 new_id = getFreeClientActiveObjectId(m_active_objects);
444                 if(new_id == 0)
445                 {
446                         infostream<<"ClientEnvironment::addActiveObject(): "
447                                 <<"no free ids available"<<std::endl;
448                         delete object;
449                         return 0;
450                 }
451                 object->setId(new_id);
452         }
453         if (!isFreeClientActiveObjectId(object->getId(), m_active_objects)) {
454                 infostream<<"ClientEnvironment::addActiveObject(): "
455                         <<"id is not free ("<<object->getId()<<")"<<std::endl;
456                 delete object;
457                 return 0;
458         }
459         infostream<<"ClientEnvironment::addActiveObject(): "
460                 <<"added (id="<<object->getId()<<")"<<std::endl;
461         m_active_objects[object->getId()] = object;
462         object->addToScene(m_smgr, m_texturesource, m_irr);
463         { // Update lighting immediately
464                 u8 light = 0;
465                 bool pos_ok;
466
467                 // Get node at head
468                 v3s16 p = object->getLightPosition();
469                 MapNode n = m_map->getNodeNoEx(p, &pos_ok);
470                 if (pos_ok)
471                         light = n.getLightBlend(getDayNightRatio(), m_client->ndef());
472                 else
473                         light = blend_light(getDayNightRatio(), LIGHT_SUN, 0);
474
475                 object->updateLight(light);
476         }
477         return object->getId();
478 }
479
480 void ClientEnvironment::addActiveObject(u16 id, u8 type,
481         const std::string &init_data)
482 {
483         ClientActiveObject* obj =
484                 ClientActiveObject::create((ActiveObjectType) type, m_client, this);
485         if(obj == NULL)
486         {
487                 infostream<<"ClientEnvironment::addActiveObject(): "
488                         <<"id="<<id<<" type="<<type<<": Couldn't create object"
489                         <<std::endl;
490                 return;
491         }
492
493         obj->setId(id);
494
495         try
496         {
497                 obj->initialize(init_data);
498         }
499         catch(SerializationError &e)
500         {
501                 errorstream<<"ClientEnvironment::addActiveObject():"
502                         <<" id="<<id<<" type="<<type
503                         <<": SerializationError in initialize(): "
504                         <<e.what()
505                         <<": init_data="<<serializeJsonString(init_data)
506                         <<std::endl;
507         }
508
509         addActiveObject(obj);
510 }
511
512 void ClientEnvironment::removeActiveObject(u16 id)
513 {
514         verbosestream<<"ClientEnvironment::removeActiveObject(): "
515                 <<"id="<<id<<std::endl;
516         ClientActiveObject* obj = getActiveObject(id);
517         if (obj == NULL) {
518                 infostream<<"ClientEnvironment::removeActiveObject(): "
519                         <<"id="<<id<<" not found"<<std::endl;
520                 return;
521         }
522         obj->removeFromScene(true);
523         delete obj;
524         m_active_objects.erase(id);
525 }
526
527 void ClientEnvironment::processActiveObjectMessage(u16 id, const std::string &data)
528 {
529         ClientActiveObject *obj = getActiveObject(id);
530         if (obj == NULL) {
531                 infostream << "ClientEnvironment::processActiveObjectMessage():"
532                         << " got message for id=" << id << ", which doesn't exist."
533                         << std::endl;
534                 return;
535         }
536
537         try {
538                 obj->processMessage(data);
539         } catch (SerializationError &e) {
540                 errorstream<<"ClientEnvironment::processActiveObjectMessage():"
541                         << " id=" << id << " type=" << obj->getType()
542                         << " SerializationError in processMessage(): " << e.what()
543                         << std::endl;
544         }
545 }
546
547 /*
548         Callbacks for activeobjects
549 */
550
551 void ClientEnvironment::damageLocalPlayer(u8 damage, bool handle_hp)
552 {
553         LocalPlayer *lplayer = getLocalPlayer();
554         assert(lplayer);
555
556         if (handle_hp) {
557                 if (lplayer->hp > damage)
558                         lplayer->hp -= damage;
559                 else
560                         lplayer->hp = 0;
561         }
562
563         ClientEnvEvent event;
564         event.type = CEE_PLAYER_DAMAGE;
565         event.player_damage.amount = damage;
566         event.player_damage.send_to_server = handle_hp;
567         m_client_event_queue.push(event);
568 }
569
570 void ClientEnvironment::updateLocalPlayerBreath(u16 breath)
571 {
572         ClientEnvEvent event;
573         event.type = CEE_PLAYER_BREATH;
574         event.player_breath.amount = breath;
575         m_client_event_queue.push(event);
576 }
577
578 /*
579         Client likes to call these
580 */
581
582 void ClientEnvironment::getActiveObjects(v3f origin, f32 max_d,
583         std::vector<DistanceSortedActiveObject> &dest)
584 {
585         for (UNORDERED_MAP<u16, ClientActiveObject*>::iterator i = m_active_objects.begin();
586                 i != m_active_objects.end(); ++i) {
587                 ClientActiveObject* obj = i->second;
588
589                 f32 d = (obj->getPosition() - origin).getLength();
590
591                 if(d > max_d)
592                         continue;
593
594                 DistanceSortedActiveObject dso(obj, d);
595
596                 dest.push_back(dso);
597         }
598 }
599
600 ClientEnvEvent ClientEnvironment::getClientEvent()
601 {
602         ClientEnvEvent event;
603         if(m_client_event_queue.empty())
604                 event.type = CEE_NONE;
605         else {
606                 event = m_client_event_queue.front();
607                 m_client_event_queue.pop();
608         }
609         return event;
610 }
611
612 ClientActiveObject * ClientEnvironment::getSelectedActiveObject(
613         const core::line3d<f32> &shootline_on_map, v3f *intersection_point,
614         v3s16 *intersection_normal)
615 {
616         std::vector<DistanceSortedActiveObject> objects;
617         getActiveObjects(shootline_on_map.start,
618                 shootline_on_map.getLength() + 3, objects);
619         const v3f line_vector = shootline_on_map.getVector();
620
621         // Sort them.
622         // After this, the closest object is the first in the array.
623         std::sort(objects.begin(), objects.end());
624
625         /* Because objects can have different nodebox sizes,
626          * the object whose center is the nearest isn't necessarily
627          * the closest one. If an object is found, don't stop
628          * immediately. */
629
630         f32 d_min = shootline_on_map.getLength();
631         ClientActiveObject *nearest_obj = NULL;
632         for (u32 i = 0; i < objects.size(); i++) {
633                 ClientActiveObject *obj = objects[i].obj;
634
635                 aabb3f *selection_box = obj->getSelectionBox();
636                 if (selection_box == NULL)
637                         continue;
638
639                 v3f pos = obj->getPosition();
640
641                 aabb3f offsetted_box(selection_box->MinEdge + pos,
642                         selection_box->MaxEdge + pos);
643
644                 if (offsetted_box.getCenter().getDistanceFrom(
645                         shootline_on_map.start) > d_min + 9.6f*BS) {
646                         // Probably there is no active object that has bigger nodebox than
647                         // (-5.5,-5.5,-5.5,5.5,5.5,5.5)
648                         // 9.6 > 5.5*sqrt(3)
649                         break;
650                 }
651
652                 v3f current_intersection;
653                 v3s16 current_normal;
654                 if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
655                         &current_intersection, &current_normal)) {
656                         f32 d_current = current_intersection.getDistanceFrom(
657                                 shootline_on_map.start);
658                         if (d_current <= d_min) {
659                                 d_min = d_current;
660                                 nearest_obj = obj;
661                                 *intersection_point = current_intersection;
662                                 *intersection_normal = current_normal;
663                         }
664                 }
665         }
666
667         return nearest_obj;
668 }
669
670 /*
671         Check if a node is pointable
672 */
673 static inline bool isPointableNode(const MapNode &n,
674         INodeDefManager *ndef, bool liquids_pointable)
675 {
676         const ContentFeatures &features = ndef->get(n);
677         return features.pointable ||
678                 (liquids_pointable && features.isLiquid());
679 }
680
681 PointedThing ClientEnvironment::getPointedThing(
682         core::line3d<f32> shootline,
683         bool liquids_pointable,
684         bool look_for_object)
685 {
686         PointedThing result;
687
688         INodeDefManager *nodedef = m_map->getNodeDefManager();
689
690         core::aabbox3d<s16> maximal_exceed = nodedef->getSelectionBoxIntUnion();
691         // The code needs to search these nodes
692         core::aabbox3d<s16> search_range(-maximal_exceed.MaxEdge,
693                 -maximal_exceed.MinEdge);
694         // If a node is found, there might be a larger node behind.
695         // To find it, we have to go further.
696         s16 maximal_overcheck =
697                 std::max(abs(search_range.MinEdge.X), abs(search_range.MaxEdge.X))
698                         + std::max(abs(search_range.MinEdge.Y), abs(search_range.MaxEdge.Y))
699                         + std::max(abs(search_range.MinEdge.Z), abs(search_range.MaxEdge.Z));
700
701         const v3f original_vector = shootline.getVector();
702         const f32 original_length = original_vector.getLength();
703
704         f32 min_distance = original_length;
705
706         // First try to find an active object
707         if (look_for_object) {
708                 ClientActiveObject *selected_object = getSelectedActiveObject(
709                         shootline, &result.intersection_point,
710                         &result.intersection_normal);
711
712                 if (selected_object != NULL) {
713                         min_distance =
714                                 (result.intersection_point - shootline.start).getLength();
715
716                         result.type = POINTEDTHING_OBJECT;
717                         result.object_id = selected_object->getId();
718                 }
719         }
720
721         // Reduce shootline
722         if (original_length > 0) {
723                 shootline.end = shootline.start
724                         + shootline.getVector() / original_length * min_distance;
725         }
726
727         // Try to find a node that is closer than the selected active
728         // object (if it exists).
729
730         voxalgo::VoxelLineIterator iterator(shootline.start / BS,
731                 shootline.getVector() / BS);
732         v3s16 oldnode = iterator.m_current_node_pos;
733         // Indicates that a node was found.
734         bool is_node_found = false;
735         // If a node is found, it is possible that there's a node
736         // behind it with a large nodebox, so continue the search.
737         u16 node_foundcounter = 0;
738         // If a node is found, this is the center of the
739         // first nodebox the shootline meets.
740         v3f found_boxcenter(0, 0, 0);
741         // The untested nodes are in this range.
742         core::aabbox3d<s16> new_nodes;
743         while (true) {
744                 // Test the nodes around the current node in search_range.
745                 new_nodes = search_range;
746                 new_nodes.MinEdge += iterator.m_current_node_pos;
747                 new_nodes.MaxEdge += iterator.m_current_node_pos;
748
749                 // Only check new nodes
750                 v3s16 delta = iterator.m_current_node_pos - oldnode;
751                 if (delta.X > 0)
752                         new_nodes.MinEdge.X = new_nodes.MaxEdge.X;
753                 else if (delta.X < 0)
754                         new_nodes.MaxEdge.X = new_nodes.MinEdge.X;
755                 else if (delta.Y > 0)
756                         new_nodes.MinEdge.Y = new_nodes.MaxEdge.Y;
757                 else if (delta.Y < 0)
758                         new_nodes.MaxEdge.Y = new_nodes.MinEdge.Y;
759                 else if (delta.Z > 0)
760                         new_nodes.MinEdge.Z = new_nodes.MaxEdge.Z;
761                 else if (delta.Z < 0)
762                         new_nodes.MaxEdge.Z = new_nodes.MinEdge.Z;
763
764                 // For each untested node
765                 for (s16 x = new_nodes.MinEdge.X; x <= new_nodes.MaxEdge.X; x++) {
766                         for (s16 y = new_nodes.MinEdge.Y; y <= new_nodes.MaxEdge.Y; y++) {
767                                 for (s16 z = new_nodes.MinEdge.Z; z <= new_nodes.MaxEdge.Z; z++) {
768                                         MapNode n;
769                                         v3s16 np(x, y, z);
770                                         bool is_valid_position;
771
772                                         n = m_map->getNodeNoEx(np, &is_valid_position);
773                                         if (!(is_valid_position &&
774                                                 isPointableNode(n, nodedef, liquids_pointable))) {
775                                                 continue;
776                                         }
777                                         std::vector<aabb3f> boxes;
778                                         n.getSelectionBoxes(nodedef, &boxes,
779                                                 n.getNeighbors(np, m_map));
780
781                                         v3f npf = intToFloat(np, BS);
782                                         for (std::vector<aabb3f>::const_iterator i = boxes.begin();
783                                                 i != boxes.end(); ++i) {
784                                                 aabb3f box = *i;
785                                                 box.MinEdge += npf;
786                                                 box.MaxEdge += npf;
787                                                 v3f intersection_point;
788                                                 v3s16 intersection_normal;
789                                                 if (!boxLineCollision(box, shootline.start, shootline.getVector(),
790                                                         &intersection_point, &intersection_normal)) {
791                                                         continue;
792                                                 }
793                                                 f32 distance = (intersection_point - shootline.start).getLength();
794                                                 if (distance >= min_distance) {
795                                                         continue;
796                                                 }
797                                                 result.type = POINTEDTHING_NODE;
798                                                 result.node_undersurface = np;
799                                                 result.intersection_point = intersection_point;
800                                                 result.intersection_normal = intersection_normal;
801                                                 found_boxcenter = box.getCenter();
802                                                 min_distance = distance;
803                                                 is_node_found = true;
804                                         }
805                                 }
806                         }
807                 }
808                 if (is_node_found) {
809                         node_foundcounter++;
810                         if (node_foundcounter > maximal_overcheck) {
811                                 break;
812                         }
813                 }
814                 // Next node
815                 if (iterator.hasNext()) {
816                         oldnode = iterator.m_current_node_pos;
817                         iterator.next();
818                 } else {
819                         break;
820                 }
821         }
822
823         if (is_node_found) {
824                 // Set undersurface and abovesurface nodes
825                 f32 d = 0.002 * BS;
826                 v3f fake_intersection = result.intersection_point;
827                 // Move intersection towards its source block.
828                 if (fake_intersection.X < found_boxcenter.X)
829                         fake_intersection.X += d;
830                 else
831                         fake_intersection.X -= d;
832
833                 if (fake_intersection.Y < found_boxcenter.Y)
834                         fake_intersection.Y += d;
835                 else
836                         fake_intersection.Y -= d;
837
838                 if (fake_intersection.Z < found_boxcenter.Z)
839                         fake_intersection.Z += d;
840                 else
841                         fake_intersection.Z -= d;
842
843                 result.node_real_undersurface = floatToInt(fake_intersection, BS);
844                 result.node_abovesurface = result.node_real_undersurface
845                         + result.intersection_normal;
846         }
847         return result;
848 }