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