Fix totally messed up 3d modes interlaced/topbottom/sidebyside
[oweals/minetest.git] / src / game.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 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 "game.h"
21 #include "irrlichttypes_extrabloated.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
26 #include <IGUIFont.h>
27 #include <IMaterialRendererServices.h>
28 #include "IMeshCache.h"
29 #include "client.h"
30 #include "server.h"
31 #include "guiPasswordChange.h"
32 #include "guiVolumeChange.h"
33 #include "guiFormSpecMenu.h"
34 #include "tool.h"
35 #include "guiChatConsole.h"
36 #include "config.h"
37 #include "version.h"
38 #include "clouds.h"
39 #include "particles.h"
40 #include "camera.h"
41 #include "mapblock.h"
42 #include "settings.h"
43 #include "profiler.h"
44 #include "mainmenumanager.h"
45 #include "gettext.h"
46 #include "log.h"
47 #include "filesys.h"
48 // Needed for determining pointing to nodes
49 #include "nodedef.h"
50 #include "nodemetadata.h"
51 #include "main.h" // For g_settings
52 #include "itemdef.h"
53 #include "tile.h" // For TextureSource
54 #include "shader.h" // For ShaderSource
55 #include "logoutputbuffer.h"
56 #include "subgame.h"
57 #include "quicktune_shortcutter.h"
58 #include "clientmap.h"
59 #include "hud.h"
60 #include "sky.h"
61 #include "sound.h"
62 #if USE_SOUND
63         #include "sound_openal.h"
64 #endif
65 #include "event_manager.h"
66 #include <iomanip>
67 #include <list>
68 #include "util/directiontables.h"
69 #include "util/pointedthing.h"
70 #include "drawscene.h"
71 #include "content_cao.h"
72
73 #ifdef HAVE_TOUCHSCREENGUI
74 #include "touchscreengui.h"
75 #endif
76
77 /*
78         Text input system
79 */
80
81 struct TextDestNodeMetadata : public TextDest
82 {
83         TextDestNodeMetadata(v3s16 p, Client *client)
84         {
85                 m_p = p;
86                 m_client = client;
87         }
88         // This is deprecated I guess? -celeron55
89         void gotText(std::wstring text)
90         {
91                 std::string ntext = wide_to_narrow(text);
92                 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
93                                 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
94                 std::map<std::string, std::string> fields;
95                 fields["text"] = ntext;
96                 m_client->sendNodemetaFields(m_p, "", fields);
97         }
98         void gotText(std::map<std::string, std::string> fields)
99         {
100                 m_client->sendNodemetaFields(m_p, "", fields);
101         }
102
103         v3s16 m_p;
104         Client *m_client;
105 };
106
107 struct TextDestPlayerInventory : public TextDest
108 {
109         TextDestPlayerInventory(Client *client)
110         {
111                 m_client = client;
112                 m_formname = "";
113         }
114         TextDestPlayerInventory(Client *client, std::string formname)
115         {
116                 m_client = client;
117                 m_formname = formname;
118         }
119         void gotText(std::map<std::string, std::string> fields)
120         {
121                 m_client->sendInventoryFields(m_formname, fields);
122         }
123
124         Client *m_client;
125 };
126
127 struct LocalFormspecHandler : public TextDest
128 {
129         LocalFormspecHandler();
130         LocalFormspecHandler(std::string formname) :
131                 m_client(0)
132         {
133                 m_formname = formname;
134         }
135
136         LocalFormspecHandler(std::string formname, Client *client) :
137                 m_client(client)
138         {
139                 m_formname = formname;
140         }
141
142         void gotText(std::wstring message) {
143                 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
144         }
145
146         void gotText(std::map<std::string, std::string> fields)
147         {
148                 if (m_formname == "MT_PAUSE_MENU") {
149                         if (fields.find("btn_sound") != fields.end()) {
150                                 g_gamecallback->changeVolume();
151                                 return;
152                         }
153
154                         if (fields.find("btn_exit_menu") != fields.end()) {
155                                 g_gamecallback->disconnect();
156                                 return;
157                         }
158
159                         if (fields.find("btn_exit_os") != fields.end()) {
160                                 g_gamecallback->exitToOS();
161                                 return;
162                         }
163
164                         if (fields.find("btn_change_password") != fields.end()) {
165                                 g_gamecallback->changePassword();
166                                 return;
167                         }
168
169                         if (fields.find("quit") != fields.end()) {
170                                 return;
171                         }
172
173                         if (fields.find("btn_continue") != fields.end()) {
174                                 return;
175                         }
176                 }
177                 if (m_formname == "MT_CHAT_MENU") {
178                         assert(m_client != 0);
179                         if ((fields.find("btn_send") != fields.end()) ||
180                                         (fields.find("quit") != fields.end())) {
181                                 if (fields.find("f_text") != fields.end()) {
182                                         m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
183                                 }
184                                 return;
185                         }
186                 }
187
188                 if (m_formname == "MT_DEATH_SCREEN") {
189                         assert(m_client != 0);
190                         if ((fields.find("btn_respawn") != fields.end())) {
191                                 m_client->sendRespawn();
192                                 return;
193                         }
194
195                         if (fields.find("quit") != fields.end()) {
196                                 m_client->sendRespawn();
197                                 return;
198                         }
199                 }
200
201                 // don't show error message for unhandled cursor keys
202                 if ( (fields.find("key_up") != fields.end()) ||
203                         (fields.find("key_down") != fields.end()) ||
204                         (fields.find("key_left") != fields.end()) ||
205                         (fields.find("key_right") != fields.end())) {
206                         return;
207                 }
208
209                 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
210                 int i = 0;
211                 for (std::map<std::string,std::string>::iterator iter = fields.begin();
212                                 iter != fields.end(); iter++) {
213                         errorstream << "\t"<< i << ": " << iter->first << "=" << iter->second << std::endl;
214                         i++;
215                 }
216         }
217
218         Client *m_client;
219 };
220
221 /* Form update callback */
222
223 class NodeMetadataFormSource: public IFormSource
224 {
225 public:
226         NodeMetadataFormSource(ClientMap *map, v3s16 p):
227                 m_map(map),
228                 m_p(p)
229         {
230         }
231         std::string getForm()
232         {
233                 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
234                 if(!meta)
235                         return "";
236                 return meta->getString("formspec");
237         }
238         std::string resolveText(std::string str)
239         {
240                 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
241                 if(!meta)
242                         return str;
243                 return meta->resolveString(str);
244         }
245
246         ClientMap *m_map;
247         v3s16 m_p;
248 };
249
250 class PlayerInventoryFormSource: public IFormSource
251 {
252 public:
253         PlayerInventoryFormSource(Client *client):
254                 m_client(client)
255         {
256         }
257         std::string getForm()
258         {
259                 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
260                 return player->inventory_formspec;
261         }
262
263         Client *m_client;
264 };
265
266 /*
267         Check if a node is pointable
268 */
269 inline bool isPointableNode(const MapNode& n,
270                 Client *client, bool liquids_pointable)
271 {
272         const ContentFeatures &features = client->getNodeDefManager()->get(n);
273         return features.pointable ||
274                 (liquids_pointable && features.isLiquid());
275 }
276
277 /*
278         Find what the player is pointing at
279 */
280 PointedThing getPointedThing(Client *client, v3f player_position,
281                 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
282                 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
283                 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
284 {
285         PointedThing result;
286
287         hilightboxes.clear();
288         selected_object = NULL;
289
290         INodeDefManager *nodedef = client->getNodeDefManager();
291         ClientMap &map = client->getEnv().getClientMap();
292
293         f32 mindistance = BS * 1001;
294
295         // First try to find a pointed at active object
296         if(look_for_object)
297         {
298                 selected_object = client->getSelectedActiveObject(d*BS,
299                                 camera_position, shootline);
300
301                 if(selected_object != NULL)
302                 {
303                         if(selected_object->doShowSelectionBox())
304                         {
305                                 aabb3f *selection_box = selected_object->getSelectionBox();
306                                 // Box should exist because object was
307                                 // returned in the first place
308                                 assert(selection_box);
309
310                                 v3f pos = selected_object->getPosition();
311                                 hilightboxes.push_back(aabb3f(
312                                                 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
313                                                 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
314                         }
315
316                         mindistance = (selected_object->getPosition() - camera_position).getLength();
317
318                         result.type = POINTEDTHING_OBJECT;
319                         result.object_id = selected_object->getId();
320                 }
321         }
322
323         // That didn't work, try to find a pointed at node
324
325
326         v3s16 pos_i = floatToInt(player_position, BS);
327
328         /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
329                         <<std::endl;*/
330
331         s16 a = d;
332         s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
333         s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
334         s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
335         s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
336         s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
337         s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
338
339         // Prevent signed number overflow
340         if(yend==32767)
341                 yend=32766;
342         if(zend==32767)
343                 zend=32766;
344         if(xend==32767)
345                 xend=32766;
346
347         for(s16 y = ystart; y <= yend; y++)
348         for(s16 z = zstart; z <= zend; z++)
349         for(s16 x = xstart; x <= xend; x++)
350         {
351                 MapNode n;
352                 try
353                 {
354                         n = map.getNode(v3s16(x,y,z));
355                 }
356                 catch(InvalidPositionException &e)
357                 {
358                         continue;
359                 }
360                 if(!isPointableNode(n, client, liquids_pointable))
361                         continue;
362
363                 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
364
365                 v3s16 np(x,y,z);
366                 v3f npf = intToFloat(np, BS);
367
368                 for(std::vector<aabb3f>::const_iterator
369                                 i = boxes.begin();
370                                 i != boxes.end(); i++)
371                 {
372                         aabb3f box = *i;
373                         box.MinEdge += npf;
374                         box.MaxEdge += npf;
375
376                         for(u16 j=0; j<6; j++)
377                         {
378                                 v3s16 facedir = g_6dirs[j];
379                                 aabb3f facebox = box;
380
381                                 f32 d = 0.001*BS;
382                                 if(facedir.X > 0)
383                                         facebox.MinEdge.X = facebox.MaxEdge.X-d;
384                                 else if(facedir.X < 0)
385                                         facebox.MaxEdge.X = facebox.MinEdge.X+d;
386                                 else if(facedir.Y > 0)
387                                         facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
388                                 else if(facedir.Y < 0)
389                                         facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
390                                 else if(facedir.Z > 0)
391                                         facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
392                                 else if(facedir.Z < 0)
393                                         facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
394
395                                 v3f centerpoint = facebox.getCenter();
396                                 f32 distance = (centerpoint - camera_position).getLength();
397                                 if(distance >= mindistance)
398                                         continue;
399                                 if(!facebox.intersectsWithLine(shootline))
400                                         continue;
401
402                                 v3s16 np_above = np + facedir;
403
404                                 result.type = POINTEDTHING_NODE;
405                                 result.node_undersurface = np;
406                                 result.node_abovesurface = np_above;
407                                 mindistance = distance;
408
409                                 hilightboxes.clear();
410                                 if (!g_settings->getBool("enable_node_highlighting")) {
411                                         for(std::vector<aabb3f>::const_iterator
412                                                         i2 = boxes.begin();
413                                                         i2 != boxes.end(); i2++)
414                                         {
415                                                 aabb3f box = *i2;
416                                                 box.MinEdge += npf + v3f(-d,-d,-d) - intToFloat(camera_offset, BS);
417                                                 box.MaxEdge += npf + v3f(d,d,d) - intToFloat(camera_offset, BS);
418                                                 hilightboxes.push_back(box);
419                                         }
420                                 }
421                         }
422                 }
423         } // for coords
424
425         return result;
426 }
427
428 /* Profiler display */
429
430 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
431                 gui::IGUIFont *font, u32 text_height, u32 show_profiler,
432                 u32 show_profiler_max)
433 {
434         if(show_profiler == 0)
435         {
436                 guitext_profiler->setVisible(false);
437         }
438         else
439         {
440
441                 std::ostringstream os(std::ios_base::binary);
442                 g_profiler->printPage(os, show_profiler, show_profiler_max);
443                 std::wstring text = narrow_to_wide(os.str());
444                 guitext_profiler->setText(text.c_str());
445                 guitext_profiler->setVisible(true);
446
447                 s32 w = font->getDimension(text.c_str()).Width;
448                 if(w < 400)
449                         w = 400;
450                 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
451                                 8+(text_height+5)*2 +
452                                 font->getDimension(text.c_str()).Height);
453                 guitext_profiler->setRelativePosition(rect);
454                 guitext_profiler->setVisible(true);
455         }
456 }
457
458 class ProfilerGraph
459 {
460 private:
461         struct Piece{
462                 Profiler::GraphValues values;
463         };
464         struct Meta{
465                 float min;
466                 float max;
467                 video::SColor color;
468                 Meta(float initial=0, video::SColor color=
469                                 video::SColor(255,255,255,255)):
470                         min(initial),
471                         max(initial),
472                         color(color)
473                 {}
474         };
475         std::list<Piece> m_log;
476 public:
477         u32 m_log_max_size;
478
479         ProfilerGraph():
480                 m_log_max_size(200)
481         {}
482
483         void put(const Profiler::GraphValues &values)
484         {
485                 Piece piece;
486                 piece.values = values;
487                 m_log.push_back(piece);
488                 while(m_log.size() > m_log_max_size)
489                         m_log.erase(m_log.begin());
490         }
491
492         void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
493                         gui::IGUIFont* font) const
494         {
495                 std::map<std::string, Meta> m_meta;
496                 for(std::list<Piece>::const_iterator k = m_log.begin();
497                                 k != m_log.end(); k++)
498                 {
499                         const Piece &piece = *k;
500                         for(Profiler::GraphValues::const_iterator i = piece.values.begin();
501                                         i != piece.values.end(); i++){
502                                 const std::string &id = i->first;
503                                 const float &value = i->second;
504                                 std::map<std::string, Meta>::iterator j =
505                                                 m_meta.find(id);
506                                 if(j == m_meta.end()){
507                                         m_meta[id] = Meta(value);
508                                         continue;
509                                 }
510                                 if(value < j->second.min)
511                                         j->second.min = value;
512                                 if(value > j->second.max)
513                                         j->second.max = value;
514                         }
515                 }
516
517                 // Assign colors
518                 static const video::SColor usable_colors[] = {
519                         video::SColor(255,255,100,100),
520                         video::SColor(255,90,225,90),
521                         video::SColor(255,100,100,255),
522                         video::SColor(255,255,150,50),
523                         video::SColor(255,220,220,100)
524                 };
525                 static const u32 usable_colors_count =
526                                 sizeof(usable_colors) / sizeof(*usable_colors);
527                 u32 next_color_i = 0;
528                 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
529                                 i != m_meta.end(); i++){
530                         Meta &meta = i->second;
531                         video::SColor color(255,200,200,200);
532                         if(next_color_i < usable_colors_count)
533                                 color = usable_colors[next_color_i++];
534                         meta.color = color;
535                 }
536
537                 s32 graphh = 50;
538                 s32 textx = x_left + m_log_max_size + 15;
539                 s32 textx2 = textx + 200 - 15;
540
541                 // Draw background
542                 /*{
543                         u32 num_graphs = m_meta.size();
544                         core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
545                                         textx2, y_bottom);
546                         video::SColor bgcolor(120,0,0,0);
547                         driver->draw2DRectangle(bgcolor, rect, NULL);
548                 }*/
549
550                 s32 meta_i = 0;
551                 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
552                                 i != m_meta.end(); i++){
553                         const std::string &id = i->first;
554                         const Meta &meta = i->second;
555                         s32 x = x_left;
556                         s32 y = y_bottom - meta_i * 50;
557                         float show_min = meta.min;
558                         float show_max = meta.max;
559                         if(show_min >= -0.0001 && show_max >= -0.0001){
560                                 if(show_min <= show_max * 0.5)
561                                         show_min = 0;
562                         }
563                         s32 texth = 15;
564                         char buf[10];
565                         snprintf(buf, 10, "%.3g", show_max);
566                         font->draw(narrow_to_wide(buf).c_str(),
567                                         core::rect<s32>(textx, y - graphh,
568                                         textx2, y - graphh + texth),
569                                         meta.color);
570                         snprintf(buf, 10, "%.3g", show_min);
571                         font->draw(narrow_to_wide(buf).c_str(),
572                                         core::rect<s32>(textx, y - texth,
573                                         textx2, y),
574                                         meta.color);
575                         font->draw(narrow_to_wide(id).c_str(),
576                                         core::rect<s32>(textx, y - graphh/2 - texth/2,
577                                         textx2, y - graphh/2 + texth/2),
578                                         meta.color);
579                         s32 graph1y = y;
580                         s32 graph1h = graphh;
581                         bool relativegraph = (show_min != 0 && show_min != show_max);
582                         float lastscaledvalue = 0.0;
583                         bool lastscaledvalue_exists = false;
584                         for(std::list<Piece>::const_iterator j = m_log.begin();
585                                         j != m_log.end(); j++)
586                         {
587                                 const Piece &piece = *j;
588                                 float value = 0;
589                                 bool value_exists = false;
590                                 Profiler::GraphValues::const_iterator k =
591                                                 piece.values.find(id);
592                                 if(k != piece.values.end()){
593                                         value = k->second;
594                                         value_exists = true;
595                                 }
596                                 if(!value_exists){
597                                         x++;
598                                         lastscaledvalue_exists = false;
599                                         continue;
600                                 }
601                                 float scaledvalue = 1.0;
602                                 if(show_max != show_min)
603                                         scaledvalue = (value - show_min) / (show_max - show_min);
604                                 if(scaledvalue == 1.0 && value == 0){
605                                         x++;
606                                         lastscaledvalue_exists = false;
607                                         continue;
608                                 }
609                                 if(relativegraph){
610                                         if(lastscaledvalue_exists){
611                                                 s32 ivalue1 = lastscaledvalue * graph1h;
612                                                 s32 ivalue2 = scaledvalue * graph1h;
613                                                 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
614                                                                 v2s32(x, graph1y - ivalue2), meta.color);
615                                         }
616                                         lastscaledvalue = scaledvalue;
617                                         lastscaledvalue_exists = true;
618                                 } else{
619                                         s32 ivalue = scaledvalue * graph1h;
620                                         driver->draw2DLine(v2s32(x, graph1y),
621                                                         v2s32(x, graph1y - ivalue), meta.color);
622                                 }
623                                 x++;
624                         }
625                         meta_i++;
626                 }
627         }
628 };
629
630 class NodeDugEvent: public MtEvent
631 {
632 public:
633         v3s16 p;
634         MapNode n;
635
636         NodeDugEvent(v3s16 p, MapNode n):
637                 p(p),
638                 n(n)
639         {}
640         const char* getType() const
641         {return "NodeDug";}
642 };
643
644 class SoundMaker
645 {
646         ISoundManager *m_sound;
647         INodeDefManager *m_ndef;
648 public:
649         float m_player_step_timer;
650
651         SimpleSoundSpec m_player_step_sound;
652         SimpleSoundSpec m_player_leftpunch_sound;
653         SimpleSoundSpec m_player_rightpunch_sound;
654
655         SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
656                 m_sound(sound),
657                 m_ndef(ndef),
658                 m_player_step_timer(0)
659         {
660         }
661
662         void playPlayerStep()
663         {
664                 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
665                         m_player_step_timer = 0.03;
666                         m_sound->playSound(m_player_step_sound, false);
667                 }
668         }
669
670         static void viewBobbingStep(MtEvent *e, void *data)
671         {
672                 SoundMaker *sm = (SoundMaker*)data;
673                 sm->playPlayerStep();
674         }
675
676         static void playerRegainGround(MtEvent *e, void *data)
677         {
678                 SoundMaker *sm = (SoundMaker*)data;
679                 sm->playPlayerStep();
680         }
681
682         static void playerJump(MtEvent *e, void *data)
683         {
684                 //SoundMaker *sm = (SoundMaker*)data;
685         }
686
687         static void cameraPunchLeft(MtEvent *e, void *data)
688         {
689                 SoundMaker *sm = (SoundMaker*)data;
690                 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
691         }
692
693         static void cameraPunchRight(MtEvent *e, void *data)
694         {
695                 SoundMaker *sm = (SoundMaker*)data;
696                 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
697         }
698
699         static void nodeDug(MtEvent *e, void *data)
700         {
701                 SoundMaker *sm = (SoundMaker*)data;
702                 NodeDugEvent *nde = (NodeDugEvent*)e;
703                 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
704         }
705
706         static void playerDamage(MtEvent *e, void *data)
707         {
708                 SoundMaker *sm = (SoundMaker*)data;
709                 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
710         }
711
712         static void playerFallingDamage(MtEvent *e, void *data)
713         {
714                 SoundMaker *sm = (SoundMaker*)data;
715                 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
716         }
717
718         void registerReceiver(MtEventManager *mgr)
719         {
720                 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
721                 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
722                 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
723                 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
724                 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
725                 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
726                 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
727                 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
728         }
729
730         void step(float dtime)
731         {
732                 m_player_step_timer -= dtime;
733         }
734 };
735
736 // Locally stored sounds don't need to be preloaded because of this
737 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
738 {
739         std::set<std::string> m_fetched;
740 public:
741
742         void fetchSounds(const std::string &name,
743                         std::set<std::string> &dst_paths,
744                         std::set<std::string> &dst_datas)
745         {
746                 if(m_fetched.count(name))
747                         return;
748                 m_fetched.insert(name);
749                 std::string base = porting::path_share + DIR_DELIM + "testsounds";
750                 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
751                 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
752                 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
753                 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
754                 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
755                 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
756                 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
757                 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
758                 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
759                 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
760                 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
761         }
762 };
763
764 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
765 {
766         Sky *m_sky;
767         bool *m_force_fog_off;
768         f32 *m_fog_range;
769         Client *m_client;
770
771 public:
772         GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
773                         f32 *fog_range, Client *client):
774                 m_sky(sky),
775                 m_force_fog_off(force_fog_off),
776                 m_fog_range(fog_range),
777                 m_client(client)
778         {}
779         ~GameGlobalShaderConstantSetter() {}
780
781         virtual void onSetConstants(video::IMaterialRendererServices *services,
782                         bool is_highlevel)
783         {
784                 if(!is_highlevel)
785                         return;
786
787                 // Background color
788                 video::SColor bgcolor = m_sky->getBgColor();
789                 video::SColorf bgcolorf(bgcolor);
790                 float bgcolorfa[4] = {
791                         bgcolorf.r,
792                         bgcolorf.g,
793                         bgcolorf.b,
794                         bgcolorf.a,
795                 };
796                 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
797
798                 // Fog distance
799                 float fog_distance = 10000*BS;
800                 if(g_settings->getBool("enable_fog") && !*m_force_fog_off)
801                         fog_distance = *m_fog_range;
802                 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
803
804                 // Day-night ratio
805                 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
806                 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
807                 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
808
809                 u32 animation_timer = porting::getTimeMs() % 100000;
810                 float animation_timer_f = (float)animation_timer / 100000.0;
811                 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
812                 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
813
814                 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
815                 v3f eye_position = player->getEyePosition();
816                 services->setPixelShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
817                 services->setVertexShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
818
819                 // Uniform sampler layers
820                 int layer0 = 0;
821                 int layer1 = 1;
822                 int layer2 = 2;
823                 // before 1.8 there isn't a "integer interface", only float
824 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
825                 services->setPixelShaderConstant("baseTexture" , (irr::f32*)&layer0, 1);
826                 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer1, 1);
827                 services->setPixelShaderConstant("useNormalmap" , (irr::f32*)&layer2, 1);
828 #else
829                 services->setPixelShaderConstant("baseTexture" , (irr::s32*)&layer0, 1);
830                 services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer1, 1);
831                 services->setPixelShaderConstant("useNormalmap" , (irr::s32*)&layer2, 1);
832 #endif
833         }
834 };
835
836 bool nodePlacementPrediction(Client &client,
837                 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
838 {
839         std::string prediction = playeritem_def.node_placement_prediction;
840         INodeDefManager *nodedef = client.ndef();
841         ClientMap &map = client.getEnv().getClientMap();
842
843         if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
844         {
845                 verbosestream<<"Node placement prediction for "
846                                 <<playeritem_def.name<<" is "
847                                 <<prediction<<std::endl;
848                 v3s16 p = neighbourpos;
849                 // Place inside node itself if buildable_to
850                 try{
851                         MapNode n_under = map.getNode(nodepos);
852                         if(nodedef->get(n_under).buildable_to)
853                                 p = nodepos;
854                         else if (!nodedef->get(map.getNode(p)).buildable_to)
855                                 return false;
856                 }catch(InvalidPositionException &e){}
857                 // Find id of predicted node
858                 content_t id;
859                 bool found = nodedef->getId(prediction, id);
860                 if(!found){
861                         errorstream<<"Node placement prediction failed for "
862                                         <<playeritem_def.name<<" (places "
863                                         <<prediction
864                                         <<") - Name not known"<<std::endl;
865                         return false;
866                 }
867                 // Predict param2 for facedir and wallmounted nodes
868                 u8 param2 = 0;
869                 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
870                         v3s16 dir = nodepos - neighbourpos;
871                         if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
872                                 param2 = dir.Y < 0 ? 1 : 0;
873                         } else if(abs(dir.X) > abs(dir.Z)){
874                                 param2 = dir.X < 0 ? 3 : 2;
875                         } else {
876                                 param2 = dir.Z < 0 ? 5 : 4;
877                         }
878                 }
879                 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
880                         v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
881                         if(abs(dir.X) > abs(dir.Z)){
882                                 param2 = dir.X < 0 ? 3 : 1;
883                         } else {
884                                 param2 = dir.Z < 0 ? 2 : 0;
885                         }
886                 }
887                 assert(param2 >= 0 && param2 <= 5);
888                 //Check attachment if node is in group attached_node
889                 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
890                         static v3s16 wallmounted_dirs[8] = {
891                                 v3s16(0,1,0),
892                                 v3s16(0,-1,0),
893                                 v3s16(1,0,0),
894                                 v3s16(-1,0,0),
895                                 v3s16(0,0,1),
896                                 v3s16(0,0,-1),
897                         };
898                         v3s16 pp;
899                         if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
900                                 pp = p + wallmounted_dirs[param2];
901                         else
902                                 pp = p + v3s16(0,-1,0);
903                         if(!nodedef->get(map.getNode(pp)).walkable)
904                                 return false;
905                 }
906                 // Add node to client map
907                 MapNode n(id, 0, param2);
908                 try{
909                         LocalPlayer* player = client.getEnv().getLocalPlayer();
910
911                         // Dont place node when player would be inside new node
912                         // NOTE: This is to be eventually implemented by a mod as client-side Lua
913                         if (!nodedef->get(n).walkable ||
914                                 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
915                                 (nodedef->get(n).walkable &&
916                                 neighbourpos != player->getStandingNodePos() + v3s16(0,1,0) &&
917                                 neighbourpos != player->getStandingNodePos() + v3s16(0,2,0))) {
918
919                                         // This triggers the required mesh update too
920                                         client.addNode(p, n);
921                                         return true;
922                                 }
923                 }catch(InvalidPositionException &e){
924                         errorstream<<"Node placement prediction failed for "
925                                         <<playeritem_def.name<<" (places "
926                                         <<prediction
927                                         <<") - Position not loaded"<<std::endl;
928                 }
929         }
930         return false;
931 }
932
933 static inline void create_formspec_menu(GUIFormSpecMenu** cur_formspec,
934                 InventoryManager *invmgr, IGameDef *gamedef,
935                 IWritableTextureSource* tsrc, IrrlichtDevice * device,
936                 IFormSource* fs_src, TextDest* txt_dest, Client* client
937                 ) {
938
939         if (*cur_formspec == 0) {
940                 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
941                                 invmgr, gamedef, tsrc, fs_src, txt_dest, cur_formspec, client);
942                 (*cur_formspec)->doPause = false;
943                 (*cur_formspec)->drop();
944         }
945         else {
946                 (*cur_formspec)->setFormSource(fs_src);
947                 (*cur_formspec)->setTextDest(txt_dest);
948         }
949 }
950
951 #ifdef __ANDROID__
952 #define SIZE_TAG "size[11,5.5]"
953 #else
954 #define SIZE_TAG "size[11,5.5,true]"
955 #endif
956
957 static void show_chat_menu(GUIFormSpecMenu** cur_formspec,
958                 InventoryManager *invmgr, IGameDef *gamedef,
959                 IWritableTextureSource* tsrc, IrrlichtDevice * device,
960                 Client* client, std::string text)
961 {
962         std::string formspec =
963                 FORMSPEC_VERSION_STRING
964                 SIZE_TAG
965                 "field[3,2.35;6,0.5;f_text;;" + text + "]"
966                 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
967                 ;
968
969         /* Create menu */
970         /* Note: FormspecFormSource and LocalFormspecHandler
971          * are deleted by guiFormSpecMenu                     */
972         FormspecFormSource* fs_src = new FormspecFormSource(formspec);
973         LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
974
975         create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
976 }
977
978 static void show_deathscreen(GUIFormSpecMenu** cur_formspec,
979                 InventoryManager *invmgr, IGameDef *gamedef,
980                 IWritableTextureSource* tsrc, IrrlichtDevice * device, Client* client)
981 {
982         std::string formspec =
983                 std::string(FORMSPEC_VERSION_STRING) +
984                 SIZE_TAG
985                 "bgcolor[#320000b4;true]"
986                 "label[4.85,1.35;You died.]"
987                 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
988                 ;
989
990         /* Create menu */
991         /* Note: FormspecFormSource and LocalFormspecHandler
992          * are deleted by guiFormSpecMenu                     */
993         FormspecFormSource* fs_src = new FormspecFormSource(formspec);
994         LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
995
996         create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,  fs_src, txt_dst, NULL);
997 }
998
999 /******************************************************************************/
1000 static void show_pause_menu(GUIFormSpecMenu** cur_formspec,
1001                 InventoryManager *invmgr, IGameDef *gamedef,
1002                 IWritableTextureSource* tsrc, IrrlichtDevice * device,
1003                 bool singleplayermode)
1004 {
1005 #ifdef __ANDROID__
1006         std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1007                         "No menu visible:\n"
1008                         "- single tap: button activate\n"
1009                         "- double tap: place/use\n"
1010                         "- slide finger: look around\n"
1011                         "Menu/Inventory visible:\n"
1012                         "- double tap (outside):\n"
1013                         " -->close\n"
1014                         "- touch stack, touch slot:\n"
1015                         " --> move stack\n"
1016                         "- touch&drag, tap 2nd finger\n"
1017                         " --> place single item to slot\n"
1018                         ));
1019 #else
1020         std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1021                         "- WASD: move\n"
1022                         "- Space: jump/climb\n"
1023                         "- Shift: sneak/go down\n"
1024                         "- Q: drop item\n"
1025                         "- I: inventory\n"
1026                         "- Mouse: turn/look\n"
1027                         "- Mouse left: dig/punch\n"
1028                         "- Mouse right: place/use\n"
1029                         "- Mouse wheel: select item\n"
1030                         "- T: chat\n"
1031                         ));
1032 #endif
1033         float ypos = singleplayermode ? 1.0 : 0.5;
1034         std::ostringstream os;
1035
1036         os << FORMSPEC_VERSION_STRING  << SIZE_TAG
1037                         << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1038                                         << wide_to_narrow(wstrgettext("Continue"))     << "]";
1039
1040         if (!singleplayermode) {
1041                 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1042                                         << wide_to_narrow(wstrgettext("Change Password")) << "]";
1043                 }
1044
1045         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1046                                         << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1047         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1048                                         << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1049         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1050                                         << wide_to_narrow(wstrgettext("Exit to OS"))   << "]"
1051                         << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1052                         << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1053                         << minetest_build_info << "\n"
1054                         << "path_user = " << wrap_rows(porting::path_user, 20)
1055                         << "\n;]";
1056
1057         /* Create menu */
1058         /* Note: FormspecFormSource and LocalFormspecHandler  *
1059          * are deleted by guiFormSpecMenu                     */
1060         FormspecFormSource* fs_src = new FormspecFormSource(os.str());
1061         LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1062
1063         create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,  fs_src, txt_dst, NULL);
1064
1065         (*cur_formspec)->doPause = true;
1066 }
1067
1068 /******************************************************************************/
1069 static void updateChat(Client& client, f32 dtime, bool show_debug,
1070                 const v2u32& screensize, bool show_chat, u32 show_profiler,
1071                 ChatBackend& chat_backend, gui::IGUIStaticText* guitext_chat,
1072                 gui::IGUIFont* font)
1073 {
1074         // Add chat log output for errors to be shown in chat
1075         static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1076
1077         // Get new messages from error log buffer
1078         while(!chat_log_error_buf.empty()) {
1079                 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1080         }
1081
1082         // Get new messages from client
1083         std::wstring message;
1084         while (client.getChatMessage(message)) {
1085                 chat_backend.addUnparsedMessage(message);
1086         }
1087
1088         // Remove old messages
1089         chat_backend.step(dtime);
1090
1091         // Display all messages in a static text element
1092         unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1093         std::wstring recent_chat       = chat_backend.getRecentChat();
1094
1095         // TODO replace by fontengine fcts
1096         unsigned int line_height       = font->getDimension(L"Ay").Height + font->getKerningHeight();
1097
1098         guitext_chat->setText(recent_chat.c_str());
1099
1100         // Update gui element size and position
1101         s32 chat_y = 5 + line_height;
1102         if (show_debug)
1103                 chat_y += line_height;
1104
1105         // first pass to calculate height of text to be set
1106         s32 width = std::min(font->getDimension(recent_chat.c_str()).Width + 10,
1107                         porting::getWindowSize().X - 20);
1108         core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1109         guitext_chat->setRelativePosition(rect);
1110
1111         //now use real height of text and adjust rect according to this size    
1112         rect = core::rect<s32>(10, chat_y, width,
1113                         chat_y + guitext_chat->getTextHeight());
1114
1115
1116         guitext_chat->setRelativePosition(rect);
1117         // Don't show chat if disabled or empty or profiler is enabled
1118         guitext_chat->setVisible(
1119                         show_chat && recent_chat_count != 0 && !show_profiler);
1120 }
1121
1122 /******************************************************************************/
1123 void the_game(bool &kill, bool random_input, InputHandler *input,
1124         IrrlichtDevice *device, gui::IGUIFont* font, std::string map_dir,
1125         std::string playername, std::string password,
1126         std::string address /* If "", local server is used */,
1127         u16 port, std::wstring &error_message, ChatBackend &chat_backend,
1128         const SubgameSpec &gamespec /* Used for local game */,
1129         bool simple_singleplayer_mode)
1130 {
1131         GUIFormSpecMenu* current_formspec = 0;
1132         video::IVideoDriver* driver = device->getVideoDriver();
1133         scene::ISceneManager* smgr = device->getSceneManager();
1134
1135         // Calculate text height using the font
1136         u32 text_height = font->getDimension(L"Random test string").Height;
1137
1138         /*
1139                 Draw "Loading" screen
1140         */
1141
1142         {
1143                 wchar_t* text = wgettext("Loading...");
1144                 draw_load_screen(text, device, guienv, font, 0, 0);
1145                 delete[] text;
1146         }
1147
1148         // Create texture source
1149         IWritableTextureSource *tsrc = createTextureSource(device);
1150
1151         // Create shader source
1152         IWritableShaderSource *shsrc = createShaderSource(device);
1153
1154         // These will be filled by data received from the server
1155         // Create item definition manager
1156         IWritableItemDefManager *itemdef = createItemDefManager();
1157         // Create node definition manager
1158         IWritableNodeDefManager *nodedef = createNodeDefManager();
1159
1160         // Sound fetcher (useful when testing)
1161         GameOnDemandSoundFetcher soundfetcher;
1162
1163         // Sound manager
1164         ISoundManager *sound = NULL;
1165         bool sound_is_dummy = false;
1166 #if USE_SOUND
1167         if(g_settings->getBool("enable_sound")){
1168                 infostream<<"Attempting to use OpenAL audio"<<std::endl;
1169                 sound = createOpenALSoundManager(&soundfetcher);
1170                 if(!sound)
1171                         infostream<<"Failed to initialize OpenAL audio"<<std::endl;
1172         } else {
1173                 infostream<<"Sound disabled."<<std::endl;
1174         }
1175 #endif
1176         if(!sound){
1177                 infostream<<"Using dummy audio."<<std::endl;
1178                 sound = &dummySoundManager;
1179                 sound_is_dummy = true;
1180         }
1181
1182         Server *server = NULL;
1183
1184         try{
1185         // Event manager
1186         EventManager eventmgr;
1187
1188         // Sound maker
1189         SoundMaker soundmaker(sound, nodedef);
1190         soundmaker.registerReceiver(&eventmgr);
1191
1192         // Create UI for modifying quicktune values
1193         QuicktuneShortcutter quicktune;
1194
1195         /*
1196                 Create server.
1197         */
1198
1199         if(address == ""){
1200                 wchar_t* text = wgettext("Creating server....");
1201                 draw_load_screen(text, device, guienv, font, 0, 25);
1202                 delete[] text;
1203                 infostream<<"Creating server"<<std::endl;
1204
1205                 std::string bind_str = g_settings->get("bind_address");
1206                 Address bind_addr(0,0,0,0, port);
1207
1208                 if (g_settings->getBool("ipv6_server")) {
1209                         bind_addr.setAddress((IPv6AddressBytes*) NULL);
1210                 }
1211                 try {
1212                         bind_addr.Resolve(bind_str.c_str());
1213                         address = bind_str;
1214                 } catch (ResolveError &e) {
1215                         infostream << "Resolving bind address \"" << bind_str
1216                                            << "\" failed: " << e.what()
1217                                            << " -- Listening on all addresses." << std::endl;
1218                 }
1219
1220                 if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1221                         error_message = L"Unable to listen on " +
1222                                 narrow_to_wide(bind_addr.serializeString()) +
1223                                 L" because IPv6 is disabled";
1224                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1225                         // Break out of client scope
1226                         return;
1227                 }
1228
1229                 server = new Server(map_dir, gamespec,
1230                                 simple_singleplayer_mode,
1231                                 bind_addr.isIPv6());
1232
1233                 server->start(bind_addr);
1234         }
1235
1236         do{ // Client scope (breakable do-while(0))
1237
1238         /*
1239                 Create client
1240         */
1241
1242         {
1243                 wchar_t* text = wgettext("Creating client...");
1244                 draw_load_screen(text, device, guienv, font, 0, 50);
1245                 delete[] text;
1246         }
1247         infostream<<"Creating client"<<std::endl;
1248
1249         MapDrawControl draw_control;
1250
1251         {
1252                 wchar_t* text = wgettext("Resolving address...");
1253                 draw_load_screen(text, device, guienv, font, 0, 75);
1254                 delete[] text;
1255         }
1256         Address connect_address(0,0,0,0, port);
1257         try {
1258                 connect_address.Resolve(address.c_str());
1259                 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1260                         //connect_address.Resolve("localhost");
1261                         if (connect_address.isIPv6()) {
1262                                 IPv6AddressBytes addr_bytes;
1263                                 addr_bytes.bytes[15] = 1;
1264                                 connect_address.setAddress(&addr_bytes);
1265                         } else {
1266                                 connect_address.setAddress(127,0,0,1);
1267                         }
1268                 }
1269         }
1270         catch(ResolveError &e) {
1271                 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1272                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1273                 // Break out of client scope
1274                 break;
1275         }
1276         if(connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1277                 error_message = L"Unable to connect to " +
1278                         narrow_to_wide(connect_address.serializeString()) +
1279                         L" because IPv6 is disabled";
1280                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1281                 // Break out of client scope
1282                 break;
1283         }
1284
1285         /*
1286                 Create client
1287         */
1288         Client client(device, playername.c_str(), password, draw_control,
1289                 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1290                 connect_address.isIPv6());
1291
1292         // Client acts as our GameDef
1293         IGameDef *gamedef = &client;
1294
1295         /*
1296                 Attempt to connect to the server
1297         */
1298
1299         infostream<<"Connecting to server at ";
1300         connect_address.print(&infostream);
1301         infostream<<std::endl;
1302         client.connect(connect_address);
1303
1304         /*
1305                 Wait for server to accept connection
1306         */
1307         bool could_connect = false;
1308         bool connect_aborted = false;
1309         try{
1310                 float time_counter = 0.0;
1311                 input->clear();
1312                 float fps_max = g_settings->getFloat("fps_max");
1313                 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1314                 u32 lasttime = device->getTimer()->getTime();
1315                 while(device->run())
1316                 {
1317                         f32 dtime = 0.033; // in seconds
1318                         if (cloud_menu_background) {
1319                                 u32 time = device->getTimer()->getTime();
1320                                 if(time > lasttime)
1321                                         dtime = (time - lasttime) / 1000.0;
1322                                 else
1323                                         dtime = 0;
1324                                 lasttime = time;
1325                         }
1326                         // Update client and server
1327                         client.step(dtime);
1328                         if(server != NULL)
1329                                 server->step(dtime);
1330
1331                         // End condition
1332                         if(client.getState() == LC_Init) {
1333                                 could_connect = true;
1334                                 break;
1335                         }
1336                         // Break conditions
1337                         if(client.accessDenied()) {
1338                                 error_message = L"Access denied. Reason: "
1339                                                 +client.accessDeniedReason();
1340                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1341                                 break;
1342                         }
1343                         if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1344                                 connect_aborted = true;
1345                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1346                                 break;
1347                         }
1348
1349                         // Display status
1350                         {
1351                                 wchar_t* text = wgettext("Connecting to server...");
1352                                 draw_load_screen(text, device, guienv, font, dtime, 100);
1353                                 delete[] text;
1354                         }
1355
1356                         // On some computers framerate doesn't seem to be
1357                         // automatically limited
1358                         if (cloud_menu_background) {
1359                                 // Time of frame without fps limit
1360                                 float busytime;
1361                                 u32 busytime_u32;
1362                                 // not using getRealTime is necessary for wine
1363                                 u32 time = device->getTimer()->getTime();
1364                                 if(time > lasttime)
1365                                         busytime_u32 = time - lasttime;
1366                                 else
1367                                         busytime_u32 = 0;
1368                                 busytime = busytime_u32 / 1000.0;
1369
1370                                 // FPS limiter
1371                                 u32 frametime_min = 1000./fps_max;
1372
1373                                 if(busytime_u32 < frametime_min) {
1374                                         u32 sleeptime = frametime_min - busytime_u32;
1375                                         device->sleep(sleeptime);
1376                                 }
1377                         } else {
1378                                 sleep_ms(25);
1379                         }
1380                         time_counter += dtime;
1381                 }
1382         }
1383         catch(con::PeerNotFoundException &e)
1384         {}
1385
1386         /*
1387                 Handle failure to connect
1388         */
1389         if(!could_connect) {
1390                 if(error_message == L"" && !connect_aborted) {
1391                         error_message = L"Connection failed";
1392                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1393                 }
1394                 // Break out of client scope
1395                 break;
1396         }
1397
1398         /*
1399                 Wait until content has been received
1400         */
1401         bool got_content = false;
1402         bool content_aborted = false;
1403         {
1404                 float time_counter = 0.0;
1405                 input->clear();
1406                 float fps_max = g_settings->getFloat("fps_max");
1407                 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1408                 u32 lasttime = device->getTimer()->getTime();
1409                 while (device->run()) {
1410                         f32 dtime = 0.033; // in seconds
1411                         if (cloud_menu_background) {
1412                                 u32 time = device->getTimer()->getTime();
1413                                 if(time > lasttime)
1414                                         dtime = (time - lasttime) / 1000.0;
1415                                 else
1416                                         dtime = 0;
1417                                 lasttime = time;
1418                         }
1419                         // Update client and server
1420                         client.step(dtime);
1421                         if (server != NULL)
1422                                 server->step(dtime);
1423
1424                         // End condition
1425                         if (client.mediaReceived() &&
1426                                         client.itemdefReceived() &&
1427                                         client.nodedefReceived()) {
1428                                 got_content = true;
1429                                 break;
1430                         }
1431                         // Break conditions
1432                         if (client.accessDenied()) {
1433                                 error_message = L"Access denied. Reason: "
1434                                                 +client.accessDeniedReason();
1435                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1436                                 break;
1437                         }
1438                         if (client.getState() < LC_Init) {
1439                                 error_message = L"Client disconnected";
1440                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1441                                 break;
1442                         }
1443                         if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1444                                 content_aborted = true;
1445                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1446                                 break;
1447                         }
1448
1449                         // Display status
1450                         int progress=0;
1451                         if (!client.itemdefReceived())
1452                         {
1453                                 wchar_t* text = wgettext("Item definitions...");
1454                                 progress = 0;
1455                                 draw_load_screen(text, device, guienv, font, dtime, progress);
1456                                 delete[] text;
1457                         }
1458                         else if (!client.nodedefReceived())
1459                         {
1460                                 wchar_t* text = wgettext("Node definitions...");
1461                                 progress = 25;
1462                                 draw_load_screen(text, device, guienv, font, dtime, progress);
1463                                 delete[] text;
1464                         }
1465                         else
1466                         {
1467
1468                                 std::stringstream message;
1469                                 message.precision(3);
1470                                 message << gettext("Media...");
1471
1472                                 if ( ( USE_CURL == 0) ||
1473                                                 (!g_settings->getBool("enable_remote_media_server"))) {
1474                                         float cur = client.getCurRate();
1475                                         std::string cur_unit = gettext(" KB/s");
1476
1477                                         if (cur > 900) {
1478                                                 cur /= 1024.0;
1479                                                 cur_unit = gettext(" MB/s");
1480                                         }
1481                                         message << " ( " << cur << cur_unit << " )";
1482                                 }
1483                                 progress = 50+client.mediaReceiveProgress()*50+0.5;
1484                                 draw_load_screen(narrow_to_wide(message.str().c_str()), device,
1485                                                 guienv, font, dtime, progress);
1486                         }
1487
1488                         // On some computers framerate doesn't seem to be
1489                         // automatically limited
1490                         if (cloud_menu_background) {
1491                                 // Time of frame without fps limit
1492                                 float busytime;
1493                                 u32 busytime_u32;
1494                                 // not using getRealTime is necessary for wine
1495                                 u32 time = device->getTimer()->getTime();
1496                                 if(time > lasttime)
1497                                         busytime_u32 = time - lasttime;
1498                                 else
1499                                         busytime_u32 = 0;
1500                                 busytime = busytime_u32 / 1000.0;
1501
1502                                 // FPS limiter
1503                                 u32 frametime_min = 1000./fps_max;
1504
1505                                 if(busytime_u32 < frametime_min) {
1506                                         u32 sleeptime = frametime_min - busytime_u32;
1507                                         device->sleep(sleeptime);
1508                                 }
1509                         } else {
1510                                 sleep_ms(25);
1511                         }
1512                         time_counter += dtime;
1513                 }
1514         }
1515
1516         if(!got_content){
1517                 if(error_message == L"" && !content_aborted){
1518                         error_message = L"Something failed";
1519                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1520                 }
1521                 // Break out of client scope
1522                 break;
1523         }
1524
1525         /*
1526                 After all content has been received:
1527                 Update cached textures, meshes and materials
1528         */
1529         client.afterContentReceived(device,font);
1530
1531         /*
1532                 Create the camera node
1533         */
1534         Camera camera(smgr, draw_control, gamedef);
1535         if (!camera.successfullyCreated(error_message))
1536                 return;
1537
1538         f32 camera_yaw = 0; // "right/left"
1539         f32 camera_pitch = 0; // "up/down"
1540
1541         /*
1542                 Clouds
1543         */
1544
1545         Clouds *clouds = NULL;
1546         if(g_settings->getBool("enable_clouds"))
1547         {
1548                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1549         }
1550
1551         /*
1552                 Skybox thingy
1553         */
1554
1555         Sky *sky = NULL;
1556         sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1557
1558         scene::ISceneNode* skybox = NULL;
1559
1560         /*
1561                 A copy of the local inventory
1562         */
1563         Inventory local_inventory(itemdef);
1564
1565         /*
1566                 Find out size of crack animation
1567         */
1568         int crack_animation_length = 5;
1569         {
1570                 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1571                 v2u32 size = t->getOriginalSize();
1572                 crack_animation_length = size.Y / size.X;
1573         }
1574
1575         /*
1576                 Add some gui stuff
1577         */
1578
1579         // First line of debug text
1580         gui::IGUIStaticText *guitext = guienv->addStaticText(
1581                         L"Minetest",
1582                         core::rect<s32>(0, 0, 0, 0),
1583                         false, false, guiroot);
1584         // Second line of debug text
1585         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1586                         L"",
1587                         core::rect<s32>(0, 0, 0, 0),
1588                         false, false, guiroot);
1589         // At the middle of the screen
1590         // Object infos are shown in this
1591         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1592                         L"",
1593                         core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1594                         false, true, guiroot);
1595
1596         // Status text (displays info when showing and hiding GUI stuff, etc.)
1597         gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1598                         L"<Status>",
1599                         core::rect<s32>(0,0,0,0),
1600                         false, false, guiroot);
1601         guitext_status->setVisible(false);
1602
1603         std::wstring statustext;
1604         float statustext_time = 0;
1605
1606         // Chat text
1607         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1608                         L"",
1609                         core::rect<s32>(0,0,0,0),
1610                         //false, false); // Disable word wrap as of now
1611                         false, true, guiroot);
1612         // Remove stale "recent" chat messages from previous connections
1613         chat_backend.clearRecentChat();
1614         // Chat backend and console
1615         GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1616
1617         // Profiler text (size is updated when text is updated)
1618         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1619                         L"<Profiler>",
1620                         core::rect<s32>(0,0,0,0),
1621                         false, false, guiroot);
1622         guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1623         guitext_profiler->setVisible(false);
1624         guitext_profiler->setWordWrap(true);
1625
1626 #ifdef HAVE_TOUCHSCREENGUI
1627         if (g_touchscreengui)
1628                 g_touchscreengui->init(tsrc,porting::getDisplayDensity());
1629 #endif
1630
1631         /*
1632                 Some statistics are collected in these
1633         */
1634         u32 drawtime = 0;
1635         u32 beginscenetime = 0;
1636         u32 endscenetime = 0;
1637
1638         float recent_turn_speed = 0.0;
1639
1640         ProfilerGraph graph;
1641         // Initially clear the profiler
1642         Profiler::GraphValues dummyvalues;
1643         g_profiler->graphGet(dummyvalues);
1644
1645         float nodig_delay_timer = 0.0;
1646         float dig_time = 0.0;
1647         u16 dig_index = 0;
1648         PointedThing pointed_old;
1649         bool digging = false;
1650         bool ldown_for_dig = false;
1651
1652         float damage_flash = 0;
1653
1654         float jump_timer = 0;
1655         bool reset_jump_timer = false;
1656
1657         const float object_hit_delay = 0.2;
1658         float object_hit_delay_timer = 0.0;
1659         float time_from_last_punch = 10;
1660
1661         float update_draw_list_timer = 0.0;
1662         v3f update_draw_list_last_cam_dir;
1663
1664         bool invert_mouse = g_settings->getBool("invert_mouse");
1665
1666         bool update_wielded_item_trigger = true;
1667
1668         bool show_hud = true;
1669         bool show_chat = true;
1670         bool force_fog_off = false;
1671         f32 fog_range = 100*BS;
1672         bool disable_camera_update = false;
1673         bool show_debug = g_settings->getBool("show_debug");
1674         bool show_profiler_graph = false;
1675         u32 show_profiler = 0;
1676         u32 show_profiler_max = 3;  // Number of pages
1677
1678         float time_of_day = 0;
1679         float time_of_day_smooth = 0;
1680
1681         float repeat_rightclick_timer = 0;
1682
1683         /*
1684                 Shader constants
1685         */
1686         shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1687                         sky, &force_fog_off, &fog_range, &client));
1688
1689         /*
1690                 Main loop
1691         */
1692
1693         bool first_loop_after_window_activation = true;
1694
1695         // TODO: Convert the static interval timers to these
1696         // Interval limiter for profiler
1697         IntervalLimiter m_profiler_interval;
1698
1699         // Time is in milliseconds
1700         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1701         // NOTE: So we have to use getTime() and call run()s between them
1702         u32 lasttime = device->getTimer()->getTime();
1703
1704         LocalPlayer* player = client.getEnv().getLocalPlayer();
1705         player->hurt_tilt_timer = 0;
1706         player->hurt_tilt_strength = 0;
1707
1708         /*
1709                 HUD object
1710         */
1711         Hud hud(driver, smgr, guienv, font, text_height,
1712                         gamedef, player, &local_inventory);
1713
1714         core::stringw str = L"Minetest [";
1715         str += driver->getName();
1716         str += "]";
1717         device->setWindowCaption(str.c_str());
1718
1719         // Info text
1720         std::wstring infotext;
1721
1722         for(;;)
1723         {
1724                 if(device->run() == false || kill == true ||
1725                                 g_gamecallback->shutdown_requested)
1726                         break;
1727
1728                 v2u32 screensize = driver->getScreenSize();
1729
1730                 // Time of frame without fps limit
1731                 float busytime;
1732                 u32 busytime_u32;
1733                 {
1734                         // not using getRealTime is necessary for wine
1735                         u32 time = device->getTimer()->getTime();
1736                         if(time > lasttime)
1737                                 busytime_u32 = time - lasttime;
1738                         else
1739                                 busytime_u32 = 0;
1740                         busytime = busytime_u32 / 1000.0;
1741                 }
1742
1743                 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1744
1745                 // Necessary for device->getTimer()->getTime()
1746                 device->run();
1747
1748                 /*
1749                         FPS limiter
1750                 */
1751
1752                 {
1753                         float fps_max = g_menumgr.pausesGame() ?
1754                                         g_settings->getFloat("pause_fps_max") :
1755                                         g_settings->getFloat("fps_max");
1756                         u32 frametime_min = 1000./fps_max;
1757
1758                         if(busytime_u32 < frametime_min)
1759                         {
1760                                 u32 sleeptime = frametime_min - busytime_u32;
1761                                 device->sleep(sleeptime);
1762                                 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1763                         }
1764                 }
1765
1766                 // Necessary for device->getTimer()->getTime()
1767                 device->run();
1768
1769                 /*
1770                         Time difference calculation
1771                 */
1772                 f32 dtime; // in seconds
1773
1774                 u32 time = device->getTimer()->getTime();
1775                 if(time > lasttime)
1776                         dtime = (time - lasttime) / 1000.0;
1777                 else
1778                         dtime = 0;
1779                 lasttime = time;
1780
1781                 g_profiler->graphAdd("mainloop_dtime", dtime);
1782
1783                 /* Run timers */
1784
1785                 if(nodig_delay_timer >= 0)
1786                         nodig_delay_timer -= dtime;
1787                 if(object_hit_delay_timer >= 0)
1788                         object_hit_delay_timer -= dtime;
1789                 time_from_last_punch += dtime;
1790
1791                 g_profiler->add("Elapsed time", dtime);
1792                 g_profiler->avg("FPS", 1./dtime);
1793
1794                 /*
1795                         Time average and jitter calculation
1796                 */
1797
1798                 static f32 dtime_avg1 = 0.0;
1799                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1800                 f32 dtime_jitter1 = dtime - dtime_avg1;
1801
1802                 static f32 dtime_jitter1_max_sample = 0.0;
1803                 static f32 dtime_jitter1_max_fraction = 0.0;
1804                 {
1805                         static f32 jitter1_max = 0.0;
1806                         static f32 counter = 0.0;
1807                         if(dtime_jitter1 > jitter1_max)
1808                                 jitter1_max = dtime_jitter1;
1809                         counter += dtime;
1810                         if(counter > 0.0)
1811                         {
1812                                 counter -= 3.0;
1813                                 dtime_jitter1_max_sample = jitter1_max;
1814                                 dtime_jitter1_max_fraction
1815                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1816                                 jitter1_max = 0.0;
1817                         }
1818                 }
1819
1820                 /*
1821                         Busytime average and jitter calculation
1822                 */
1823
1824                 static f32 busytime_avg1 = 0.0;
1825                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1826                 f32 busytime_jitter1 = busytime - busytime_avg1;
1827
1828                 static f32 busytime_jitter1_max_sample = 0.0;
1829                 static f32 busytime_jitter1_min_sample = 0.0;
1830                 {
1831                         static f32 jitter1_max = 0.0;
1832                         static f32 jitter1_min = 0.0;
1833                         static f32 counter = 0.0;
1834                         if(busytime_jitter1 > jitter1_max)
1835                                 jitter1_max = busytime_jitter1;
1836                         if(busytime_jitter1 < jitter1_min)
1837                                 jitter1_min = busytime_jitter1;
1838                         counter += dtime;
1839                         if(counter > 0.0){
1840                                 counter -= 3.0;
1841                                 busytime_jitter1_max_sample = jitter1_max;
1842                                 busytime_jitter1_min_sample = jitter1_min;
1843                                 jitter1_max = 0.0;
1844                                 jitter1_min = 0.0;
1845                         }
1846                 }
1847
1848                 /*
1849                         Handle miscellaneous stuff
1850                 */
1851
1852                 if(client.accessDenied())
1853                 {
1854                         error_message = L"Access denied. Reason: "
1855                                         +client.accessDeniedReason();
1856                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1857                         break;
1858                 }
1859
1860                 if(g_gamecallback->disconnect_requested)
1861                 {
1862                         g_gamecallback->disconnect_requested = false;
1863                         break;
1864                 }
1865
1866                 if(g_gamecallback->changepassword_requested)
1867                 {
1868                         (new GUIPasswordChange(guienv, guiroot, -1,
1869                                 &g_menumgr, &client))->drop();
1870                         g_gamecallback->changepassword_requested = false;
1871                 }
1872
1873                 if(g_gamecallback->changevolume_requested)
1874                 {
1875                         (new GUIVolumeChange(guienv, guiroot, -1,
1876                                 &g_menumgr, &client))->drop();
1877                         g_gamecallback->changevolume_requested = false;
1878                 }
1879
1880                 /* Process TextureSource's queue */
1881                 tsrc->processQueue();
1882
1883                 /* Process ItemDefManager's queue */
1884                 itemdef->processQueue(gamedef);
1885
1886                 /*
1887                         Process ShaderSource's queue
1888                 */
1889                 shsrc->processQueue();
1890
1891                 /*
1892                         Random calculations
1893                 */
1894                 hud.resizeHotbar();
1895
1896                 // Hilight boxes collected during the loop and displayed
1897                 std::vector<aabb3f> hilightboxes;
1898
1899                 /* reset infotext */
1900                 infotext = L"";
1901                 /*
1902                         Profiler
1903                 */
1904                 float profiler_print_interval =
1905                                 g_settings->getFloat("profiler_print_interval");
1906                 bool print_to_log = true;
1907                 if(profiler_print_interval == 0){
1908                         print_to_log = false;
1909                         profiler_print_interval = 5;
1910                 }
1911                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1912                 {
1913                         if(print_to_log){
1914                                 infostream<<"Profiler:"<<std::endl;
1915                                 g_profiler->print(infostream);
1916                         }
1917
1918                         update_profiler_gui(guitext_profiler, font, text_height,
1919                                         show_profiler, show_profiler_max);
1920
1921                         g_profiler->clear();
1922                 }
1923
1924                 /*
1925                         Direct handling of user input
1926                 */
1927
1928                 // Reset input if window not active or some menu is active
1929                 if(device->isWindowActive() == false
1930                                 || noMenuActive() == false
1931                                 || guienv->hasFocus(gui_chat_console))
1932                 {
1933                         input->clear();
1934                 }
1935                 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1936                 {
1937                         gui_chat_console->closeConsoleAtOnce();
1938                 }
1939
1940                 // Input handler step() (used by the random input generator)
1941                 input->step(dtime);
1942 #ifdef HAVE_TOUCHSCREENGUI
1943                 if (g_touchscreengui) {
1944                         g_touchscreengui->step(dtime);
1945                 }
1946 #endif
1947 #ifdef __ANDROID__
1948                 if (current_formspec != 0)
1949                         current_formspec->getAndroidUIInput();
1950 #endif
1951
1952                 // Increase timer for doubleclick of "jump"
1953                 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1954                         jump_timer += dtime;
1955
1956                 /*
1957                         Launch menus and trigger stuff according to keys
1958                 */
1959                 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1960                 {
1961                         // drop selected item
1962                         IDropAction *a = new IDropAction();
1963                         a->count = 0;
1964                         a->from_inv.setCurrentPlayer();
1965                         a->from_list = "main";
1966                         a->from_i = client.getPlayerItem();
1967                         client.inventoryAction(a);
1968                 }
1969                 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1970                 {
1971                         infostream<<"the_game: "
1972                                         <<"Launching inventory"<<std::endl;
1973
1974                         PlayerInventoryFormSource* fs_src = new PlayerInventoryFormSource(&client);
1975                         TextDest* txt_dst = new TextDestPlayerInventory(&client);
1976
1977                         create_formspec_menu(&current_formspec, &client, gamedef, tsrc, device, fs_src, txt_dst, &client);
1978
1979                         InventoryLocation inventoryloc;
1980                         inventoryloc.setCurrentPlayer();
1981                         current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
1982                 }
1983                 else if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey))
1984                 {
1985                         show_pause_menu(&current_formspec, &client, gamedef, tsrc, device,
1986                                         simple_singleplayer_mode);
1987                 }
1988                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1989                 {
1990                         show_chat_menu(&current_formspec, &client, gamedef, tsrc, device,
1991                                         &client,"");
1992                 }
1993                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1994                 {
1995                         show_chat_menu(&current_formspec, &client, gamedef, tsrc, device,
1996                                         &client,"/");
1997                 }
1998                 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1999                 {
2000                         if (!gui_chat_console->isOpenInhibited())
2001                         {
2002                                 // Open up to over half of the screen
2003                                 gui_chat_console->openConsole(0.6);
2004                                 guienv->setFocus(gui_chat_console);
2005                         }
2006                 }
2007                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
2008                 {
2009                         if(g_settings->getBool("free_move"))
2010                         {
2011                                 g_settings->set("free_move","false");
2012                                 statustext = L"free_move disabled";
2013                                 statustext_time = 0;
2014                         }
2015                         else
2016                         {
2017                                 g_settings->set("free_move","true");
2018                                 statustext = L"free_move enabled";
2019                                 statustext_time = 0;
2020                                 if(!client.checkPrivilege("fly"))
2021                                         statustext += L" (note: no 'fly' privilege)";
2022                         }
2023                 }
2024                 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
2025                 {
2026                         if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
2027                         {
2028                                 if(g_settings->getBool("free_move"))
2029                                 {
2030                                         g_settings->set("free_move","false");
2031                                         statustext = L"free_move disabled";
2032                                         statustext_time = 0;
2033                                 }
2034                                 else
2035                                 {
2036                                         g_settings->set("free_move","true");
2037                                         statustext = L"free_move enabled";
2038                                         statustext_time = 0;
2039                                         if(!client.checkPrivilege("fly"))
2040                                                 statustext += L" (note: no 'fly' privilege)";
2041                                 }
2042                         }
2043                         reset_jump_timer = true;
2044                 }
2045                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
2046                 {
2047                         if(g_settings->getBool("fast_move"))
2048                         {
2049                                 g_settings->set("fast_move","false");
2050                                 statustext = L"fast_move disabled";
2051                                 statustext_time = 0;
2052                         }
2053                         else
2054                         {
2055                                 g_settings->set("fast_move","true");
2056                                 statustext = L"fast_move enabled";
2057                                 statustext_time = 0;
2058                                 if(!client.checkPrivilege("fast"))
2059                                         statustext += L" (note: no 'fast' privilege)";
2060                         }
2061                 }
2062                 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
2063                 {
2064                         if(g_settings->getBool("noclip"))
2065                         {
2066                                 g_settings->set("noclip","false");
2067                                 statustext = L"noclip disabled";
2068                                 statustext_time = 0;
2069                         }
2070                         else
2071                         {
2072                                 g_settings->set("noclip","true");
2073                                 statustext = L"noclip enabled";
2074                                 statustext_time = 0;
2075                                 if(!client.checkPrivilege("noclip"))
2076                                         statustext += L" (note: no 'noclip' privilege)";
2077                         }
2078                 }
2079                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
2080                 {
2081                         client.makeScreenshot(device);
2082                 }
2083                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
2084                 {
2085                         show_hud = !show_hud;
2086                         if(show_hud) {
2087                                 statustext = L"HUD shown";
2088                                 client.setHighlighted(client.getHighlighted(), true);
2089                         } else {
2090                                 statustext = L"HUD hidden";
2091                                 client.setHighlighted(client.getHighlighted(), false);
2092                         }
2093                         statustext_time = 0;
2094                 }
2095                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
2096                 {
2097                         show_chat = !show_chat;
2098                         if(show_chat)
2099                                 statustext = L"Chat shown";
2100                         else
2101                                 statustext = L"Chat hidden";
2102                         statustext_time = 0;
2103                 }
2104                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
2105                 {
2106                         force_fog_off = !force_fog_off;
2107                         if(force_fog_off)
2108                                 statustext = L"Fog disabled";
2109                         else
2110                                 statustext = L"Fog enabled";
2111                         statustext_time = 0;
2112                 }
2113                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
2114                 {
2115                         disable_camera_update = !disable_camera_update;
2116                         if(disable_camera_update)
2117                                 statustext = L"Camera update disabled";
2118                         else
2119                                 statustext = L"Camera update enabled";
2120                         statustext_time = 0;
2121                 }
2122                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
2123                 {
2124                         // Initial / 3x toggle: Chat only
2125                         // 1x toggle: Debug text with chat
2126                         // 2x toggle: Debug text with profiler graph
2127                         if(!show_debug)
2128                         {
2129                                 show_debug = true;
2130                                 show_profiler_graph = false;
2131                                 statustext = L"Debug info shown";
2132                                 statustext_time = 0;
2133                         }
2134                         else if(show_profiler_graph)
2135                         {
2136                                 show_debug = false;
2137                                 show_profiler_graph = false;
2138                                 statustext = L"Debug info and profiler graph hidden";
2139                                 statustext_time = 0;
2140                         }
2141                         else
2142                         {
2143                                 show_profiler_graph = true;
2144                                 statustext = L"Profiler graph shown";
2145                                 statustext_time = 0;
2146                         }
2147                 }
2148                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2149                 {
2150                         show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2151
2152                         // FIXME: This updates the profiler with incomplete values
2153                         update_profiler_gui(guitext_profiler, font, text_height,
2154                                         show_profiler, show_profiler_max);
2155
2156                         if(show_profiler != 0)
2157                         {
2158                                 std::wstringstream sstr;
2159                                 sstr<<"Profiler shown (page "<<show_profiler
2160                                         <<" of "<<show_profiler_max<<")";
2161                                 statustext = sstr.str();
2162                                 statustext_time = 0;
2163                         }
2164                         else
2165                         {
2166                                 statustext = L"Profiler hidden";
2167                                 statustext_time = 0;
2168                         }
2169                 }
2170                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2171                 {
2172                         s16 range = g_settings->getS16("viewing_range_nodes_min");
2173                         s16 range_new = range + 10;
2174                         g_settings->set("viewing_range_nodes_min", itos(range_new));
2175                         statustext = narrow_to_wide(
2176                                         "Minimum viewing range changed to "
2177                                         + itos(range_new));
2178                         statustext_time = 0;
2179                 }
2180                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2181                 {
2182                         s16 range = g_settings->getS16("viewing_range_nodes_min");
2183                         s16 range_new = range - 10;
2184                         if(range_new < 0)
2185                                 range_new = range;
2186                         g_settings->set("viewing_range_nodes_min",
2187                                         itos(range_new));
2188                         statustext = narrow_to_wide(
2189                                         "Minimum viewing range changed to "
2190                                         + itos(range_new));
2191                         statustext_time = 0;
2192                 }
2193
2194                 // Reset jump_timer
2195                 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2196                 {
2197                         reset_jump_timer = false;
2198                         jump_timer = 0.0;
2199                 }
2200
2201                 // Handle QuicktuneShortcutter
2202                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2203                         quicktune.next();
2204                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2205                         quicktune.prev();
2206                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2207                         quicktune.inc();
2208                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2209                         quicktune.dec();
2210                 {
2211                         std::string msg = quicktune.getMessage();
2212                         if(msg != ""){
2213                                 statustext = narrow_to_wide(msg);
2214                                 statustext_time = 0;
2215                         }
2216                 }
2217
2218                 // Item selection with mouse wheel
2219                 u16 new_playeritem = client.getPlayerItem();
2220                 {
2221                         s32 wheel = input->getMouseWheel();
2222                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2223                                         player->hud_hotbar_itemcount-1);
2224
2225                         if(wheel < 0)
2226                         {
2227                                 if(new_playeritem < max_item)
2228                                         new_playeritem++;
2229                                 else
2230                                         new_playeritem = 0;
2231                         }
2232                         else if(wheel > 0)
2233                         {
2234                                 if(new_playeritem > 0)
2235                                         new_playeritem--;
2236                                 else
2237                                         new_playeritem = max_item;
2238                         }
2239                 }
2240
2241                 // Item selection
2242                 for(u16 i=0; i<10; i++)
2243                 {
2244                         const KeyPress *kp = NumberKey + (i + 1) % 10;
2245                         if(input->wasKeyDown(*kp))
2246                         {
2247                                 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2248                                 {
2249                                         new_playeritem = i;
2250
2251                                         infostream<<"Selected item: "
2252                                                         <<new_playeritem<<std::endl;
2253                                 }
2254                         }
2255                 }
2256
2257                 // Viewing range selection
2258                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2259                 {
2260                         draw_control.range_all = !draw_control.range_all;
2261                         if(draw_control.range_all)
2262                         {
2263                                 infostream<<"Enabled full viewing range"<<std::endl;
2264                                 statustext = L"Enabled full viewing range";
2265                                 statustext_time = 0;
2266                         }
2267                         else
2268                         {
2269                                 infostream<<"Disabled full viewing range"<<std::endl;
2270                                 statustext = L"Disabled full viewing range";
2271                                 statustext_time = 0;
2272                         }
2273                 }
2274
2275                 // Print debug stacks
2276                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2277                 {
2278                         dstream<<"-----------------------------------------"
2279                                         <<std::endl;
2280                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2281                         dstream<<"-----------------------------------------"
2282                                         <<std::endl;
2283                         debug_stacks_print();
2284                 }
2285
2286                 /*
2287                         Mouse and camera control
2288                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2289                 */
2290
2291                 float turn_amount = 0;
2292                 if((device->isWindowActive() && noMenuActive()) || random_input)
2293                 {
2294 #ifndef __ANDROID__
2295                         if(!random_input)
2296                         {
2297                                 // Mac OSX gets upset if this is set every frame
2298                                 if(device->getCursorControl()->isVisible())
2299                                         device->getCursorControl()->setVisible(false);
2300                         }
2301 #endif
2302
2303                         if(first_loop_after_window_activation){
2304                                 //infostream<<"window active, first loop"<<std::endl;
2305                                 first_loop_after_window_activation = false;
2306                         } else {
2307 #ifdef HAVE_TOUCHSCREENGUI
2308                                 if (g_touchscreengui) {
2309                                         camera_yaw   = g_touchscreengui->getYaw();
2310                                         camera_pitch = g_touchscreengui->getPitch();
2311                                 } else {
2312 #endif
2313                                         s32 dx = input->getMousePos().X - (driver->getScreenSize().Width/2);
2314                                         s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height/2);
2315                                 if ((invert_mouse)
2316                                                 || (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)) {
2317                                         dy = -dy;
2318                                 }
2319                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2320
2321                                 /*const float keyspeed = 500;
2322                                 if(input->isKeyDown(irr::KEY_UP))
2323                                         dy -= dtime * keyspeed;
2324                                 if(input->isKeyDown(irr::KEY_DOWN))
2325                                         dy += dtime * keyspeed;
2326                                 if(input->isKeyDown(irr::KEY_LEFT))
2327                                         dx -= dtime * keyspeed;
2328                                 if(input->isKeyDown(irr::KEY_RIGHT))
2329                                         dx += dtime * keyspeed;*/
2330
2331                                 float d = g_settings->getFloat("mouse_sensitivity");
2332                                 d = rangelim(d, 0.01, 100.0);
2333                                 camera_yaw -= dx*d;
2334                                 camera_pitch += dy*d;
2335                                 turn_amount = v2f(dx, dy).getLength() * d;
2336
2337 #ifdef HAVE_TOUCHSCREENGUI
2338                                 }
2339 #endif
2340                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
2341                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
2342                         }
2343                         input->setMousePos((driver->getScreenSize().Width/2),
2344                                         (driver->getScreenSize().Height/2));
2345                 }
2346                 else{
2347 #ifndef ANDROID
2348                         // Mac OSX gets upset if this is set every frame
2349                         if(device->getCursorControl()->isVisible() == false)
2350                                 device->getCursorControl()->setVisible(true);
2351 #endif
2352
2353                         //infostream<<"window inactive"<<std::endl;
2354                         first_loop_after_window_activation = true;
2355                 }
2356                 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2357                 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2358
2359                 /*
2360                         Player speed control
2361                 */
2362                 {
2363                         /*bool a_up,
2364                         bool a_down,
2365                         bool a_left,
2366                         bool a_right,
2367                         bool a_jump,
2368                         bool a_superspeed,
2369                         bool a_sneak,
2370                         bool a_LMB,
2371                         bool a_RMB,
2372                         float a_pitch,
2373                         float a_yaw*/
2374                         PlayerControl control(
2375                                 input->isKeyDown(getKeySetting("keymap_forward")),
2376                                 input->isKeyDown(getKeySetting("keymap_backward")),
2377                                 input->isKeyDown(getKeySetting("keymap_left")),
2378                                 input->isKeyDown(getKeySetting("keymap_right")),
2379                                 input->isKeyDown(getKeySetting("keymap_jump")),
2380                                 input->isKeyDown(getKeySetting("keymap_special1")),
2381                                 input->isKeyDown(getKeySetting("keymap_sneak")),
2382                                 input->getLeftState(),
2383                                 input->getRightState(),
2384                                 camera_pitch,
2385                                 camera_yaw
2386                         );
2387                         client.setPlayerControl(control);
2388                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2389                         player->keyPressed=
2390                         (((int)input->isKeyDown(getKeySetting("keymap_forward"))  & 0x1) << 0) |
2391                         (((int)input->isKeyDown(getKeySetting("keymap_backward")) & 0x1) << 1) |
2392                         (((int)input->isKeyDown(getKeySetting("keymap_left"))     & 0x1) << 2) |
2393                         (((int)input->isKeyDown(getKeySetting("keymap_right"))    & 0x1) << 3) |
2394                         (((int)input->isKeyDown(getKeySetting("keymap_jump"))     & 0x1) << 4) |
2395                         (((int)input->isKeyDown(getKeySetting("keymap_special1")) & 0x1) << 5) |
2396                         (((int)input->isKeyDown(getKeySetting("keymap_sneak"))    & 0x1) << 6) |
2397                         (((int)input->getLeftState()  & 0x1) << 7) |
2398                         (((int)input->getRightState() & 0x1) << 8);
2399                 }
2400
2401                 /*
2402                         Run server, client (and process environments)
2403                 */
2404                 bool can_be_and_is_paused =
2405                                 (simple_singleplayer_mode && g_menumgr.pausesGame());
2406                 if(can_be_and_is_paused)
2407                 {
2408                         // No time passes
2409                         dtime = 0;
2410                 }
2411                 else
2412                 {
2413                         if(server != NULL)
2414                         {
2415                                 //TimeTaker timer("server->step(dtime)");
2416                                 server->step(dtime);
2417                         }
2418                         {
2419                                 //TimeTaker timer("client.step(dtime)");
2420                                 client.step(dtime);
2421                         }
2422                 }
2423
2424                 {
2425                         // Read client events
2426                         for(;;) {
2427                                 ClientEvent event = client.getClientEvent();
2428                                 if(event.type == CE_NONE) {
2429                                         break;
2430                                 }
2431                                 else if(event.type == CE_PLAYER_DAMAGE &&
2432                                                 client.getHP() != 0) {
2433                                         //u16 damage = event.player_damage.amount;
2434                                         //infostream<<"Player damage: "<<damage<<std::endl;
2435
2436                                         damage_flash += 100.0;
2437                                         damage_flash += 8.0 * event.player_damage.amount;
2438
2439                                         player->hurt_tilt_timer = 1.5;
2440                                         player->hurt_tilt_strength = event.player_damage.amount/4;
2441                                         player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
2442
2443                                         MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2444                                         gamedef->event()->put(e);
2445                                 }
2446                                 else if(event.type == CE_PLAYER_FORCE_MOVE) {
2447                                         camera_yaw = event.player_force_move.yaw;
2448                                         camera_pitch = event.player_force_move.pitch;
2449                                 }
2450                                 else if(event.type == CE_DEATHSCREEN) {
2451                                         show_deathscreen(&current_formspec, &client, gamedef, tsrc,
2452                                                         device, &client);
2453
2454                                         chat_backend.addMessage(L"", L"You died.");
2455
2456                                         /* Handle visualization */
2457                                         damage_flash = 0;
2458
2459                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2460                                         player->hurt_tilt_timer = 0;
2461                                         player->hurt_tilt_strength = 0;
2462
2463                                 }
2464                                 else if (event.type == CE_SHOW_FORMSPEC) {
2465                                         FormspecFormSource* fs_src =
2466                                                         new FormspecFormSource(*(event.show_formspec.formspec));
2467                                         TextDestPlayerInventory* txt_dst =
2468                                                         new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2469
2470                                         create_formspec_menu(&current_formspec, &client, gamedef,
2471                                                         tsrc, device, fs_src, txt_dst, &client);
2472
2473                                         delete(event.show_formspec.formspec);
2474                                         delete(event.show_formspec.formname);
2475                                 }
2476                                 else if(event.type == CE_SPAWN_PARTICLE) {
2477                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2478                                         video::ITexture *texture =
2479                                                 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2480
2481                                         new Particle(gamedef, smgr, player, client.getEnv(),
2482                                                 *event.spawn_particle.pos,
2483                                                 *event.spawn_particle.vel,
2484                                                 *event.spawn_particle.acc,
2485                                                  event.spawn_particle.expirationtime,
2486                                                  event.spawn_particle.size,
2487                                                  event.spawn_particle.collisiondetection,
2488                                                  event.spawn_particle.vertical,
2489                                                  texture,
2490                                                  v2f(0.0, 0.0),
2491                                                  v2f(1.0, 1.0));
2492                                 }
2493                                 else if(event.type == CE_ADD_PARTICLESPAWNER) {
2494                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2495                                         video::ITexture *texture =
2496                                                 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2497
2498                                         new ParticleSpawner(gamedef, smgr, player,
2499                                                  event.add_particlespawner.amount,
2500                                                  event.add_particlespawner.spawntime,
2501                                                 *event.add_particlespawner.minpos,
2502                                                 *event.add_particlespawner.maxpos,
2503                                                 *event.add_particlespawner.minvel,
2504                                                 *event.add_particlespawner.maxvel,
2505                                                 *event.add_particlespawner.minacc,
2506                                                 *event.add_particlespawner.maxacc,
2507                                                  event.add_particlespawner.minexptime,
2508                                                  event.add_particlespawner.maxexptime,
2509                                                  event.add_particlespawner.minsize,
2510                                                  event.add_particlespawner.maxsize,
2511                                                  event.add_particlespawner.collisiondetection,
2512                                                  event.add_particlespawner.vertical,
2513                                                  texture,
2514                                                  event.add_particlespawner.id);
2515                                 }
2516                                 else if(event.type == CE_DELETE_PARTICLESPAWNER) {
2517                                         delete_particlespawner (event.delete_particlespawner.id);
2518                                 }
2519                                 else if (event.type == CE_HUDADD) {
2520                                         u32 id = event.hudadd.id;
2521
2522                                         HudElement *e = player->getHud(id);
2523
2524                                         if (e != NULL) {
2525                                                 delete event.hudadd.pos;
2526                                                 delete event.hudadd.name;
2527                                                 delete event.hudadd.scale;
2528                                                 delete event.hudadd.text;
2529                                                 delete event.hudadd.align;
2530                                                 delete event.hudadd.offset;
2531                                                 delete event.hudadd.world_pos;
2532                                                 delete event.hudadd.size;
2533                                                 continue;
2534                                         }
2535
2536                                         e = new HudElement;
2537                                         e->type   = (HudElementType)event.hudadd.type;
2538                                         e->pos    = *event.hudadd.pos;
2539                                         e->name   = *event.hudadd.name;
2540                                         e->scale  = *event.hudadd.scale;
2541                                         e->text   = *event.hudadd.text;
2542                                         e->number = event.hudadd.number;
2543                                         e->item   = event.hudadd.item;
2544                                         e->dir    = event.hudadd.dir;
2545                                         e->align  = *event.hudadd.align;
2546                                         e->offset = *event.hudadd.offset;
2547                                         e->world_pos = *event.hudadd.world_pos;
2548                                         e->size = *event.hudadd.size;
2549
2550                                         u32 new_id = player->addHud(e);
2551                                         //if this isn't true our huds aren't consistent
2552                                         assert(new_id == id);
2553
2554                                         delete event.hudadd.pos;
2555                                         delete event.hudadd.name;
2556                                         delete event.hudadd.scale;
2557                                         delete event.hudadd.text;
2558                                         delete event.hudadd.align;
2559                                         delete event.hudadd.offset;
2560                                         delete event.hudadd.world_pos;
2561                                         delete event.hudadd.size;
2562                                 }
2563                                 else if (event.type == CE_HUDRM) {
2564                                         HudElement* e = player->removeHud(event.hudrm.id);
2565
2566                                         if (e != NULL)
2567                                                 delete (e);
2568                                 }
2569                                 else if (event.type == CE_HUDCHANGE) {
2570                                         u32 id = event.hudchange.id;
2571                                         HudElement* e = player->getHud(id);
2572                                         if (e == NULL)
2573                                         {
2574                                                 delete event.hudchange.v3fdata;
2575                                                 delete event.hudchange.v2fdata;
2576                                                 delete event.hudchange.sdata;
2577                                                 delete event.hudchange.v2s32data;
2578                                                 continue;
2579                                         }
2580
2581                                         switch (event.hudchange.stat) {
2582                                                 case HUD_STAT_POS:
2583                                                         e->pos = *event.hudchange.v2fdata;
2584                                                         break;
2585                                                 case HUD_STAT_NAME:
2586                                                         e->name = *event.hudchange.sdata;
2587                                                         break;
2588                                                 case HUD_STAT_SCALE:
2589                                                         e->scale = *event.hudchange.v2fdata;
2590                                                         break;
2591                                                 case HUD_STAT_TEXT:
2592                                                         e->text = *event.hudchange.sdata;
2593                                                         break;
2594                                                 case HUD_STAT_NUMBER:
2595                                                         e->number = event.hudchange.data;
2596                                                         break;
2597                                                 case HUD_STAT_ITEM:
2598                                                         e->item = event.hudchange.data;
2599                                                         break;
2600                                                 case HUD_STAT_DIR:
2601                                                         e->dir = event.hudchange.data;
2602                                                         break;
2603                                                 case HUD_STAT_ALIGN:
2604                                                         e->align = *event.hudchange.v2fdata;
2605                                                         break;
2606                                                 case HUD_STAT_OFFSET:
2607                                                         e->offset = *event.hudchange.v2fdata;
2608                                                         break;
2609                                                 case HUD_STAT_WORLD_POS:
2610                                                         e->world_pos = *event.hudchange.v3fdata;
2611                                                         break;
2612                                                 case HUD_STAT_SIZE:
2613                                                         e->size = *event.hudchange.v2s32data;
2614                                                         break;
2615                                         }
2616
2617                                         delete event.hudchange.v3fdata;
2618                                         delete event.hudchange.v2fdata;
2619                                         delete event.hudchange.sdata;
2620                                         delete event.hudchange.v2s32data;
2621                                 }
2622                                 else if (event.type == CE_SET_SKY) {
2623                                         sky->setVisible(false);
2624                                         if(skybox){
2625                                                 skybox->remove();
2626                                                 skybox = NULL;
2627                                         }
2628                                         // Handle according to type
2629                                         if(*event.set_sky.type == "regular") {
2630                                                 sky->setVisible(true);
2631                                         }
2632                                         else if(*event.set_sky.type == "skybox" &&
2633                                                         event.set_sky.params->size() == 6) {
2634                                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2635                                                 skybox = smgr->addSkyBoxSceneNode(
2636                                                                 tsrc->getTexture((*event.set_sky.params)[0]),
2637                                                                 tsrc->getTexture((*event.set_sky.params)[1]),
2638                                                                 tsrc->getTexture((*event.set_sky.params)[2]),
2639                                                                 tsrc->getTexture((*event.set_sky.params)[3]),
2640                                                                 tsrc->getTexture((*event.set_sky.params)[4]),
2641                                                                 tsrc->getTexture((*event.set_sky.params)[5]));
2642                                         }
2643                                         // Handle everything else as plain color
2644                                         else {
2645                                                 if(*event.set_sky.type != "plain")
2646                                                         infostream<<"Unknown sky type: "
2647                                                                         <<(*event.set_sky.type)<<std::endl;
2648                                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2649                                         }
2650
2651                                         delete event.set_sky.bgcolor;
2652                                         delete event.set_sky.type;
2653                                         delete event.set_sky.params;
2654                                 }
2655                                 else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
2656                                         bool enable = event.override_day_night_ratio.do_override;
2657                                         u32 value = event.override_day_night_ratio.ratio_f * 1000;
2658                                         client.getEnv().setDayNightRatioOverride(enable, value);
2659                                 }
2660                         }
2661                 }
2662
2663                 //TimeTaker //timer2("//timer2");
2664
2665                 /*
2666                         For interaction purposes, get info about the held item
2667                         - What item is it?
2668                         - Is it a usable item?
2669                         - Can it point to liquids?
2670                 */
2671                 ItemStack playeritem;
2672                 {
2673                         InventoryList *mlist = local_inventory.getList("main");
2674                         if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
2675                                 playeritem = mlist->getItem(client.getPlayerItem());
2676                 }
2677                 const ItemDefinition &playeritem_def =
2678                                 playeritem.getDefinition(itemdef);
2679                 ToolCapabilities playeritem_toolcap =
2680                                 playeritem.getToolCapabilities(itemdef);
2681
2682                 /*
2683                         Update camera
2684                 */
2685
2686                 v3s16 old_camera_offset = camera.getOffset();
2687
2688                 LocalPlayer* player = client.getEnv().getLocalPlayer();
2689                 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2690                 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2691
2692                 if(input->wasKeyDown(getKeySetting("keymap_camera_mode"))) {
2693                         camera.toggleCameraMode();
2694                         GenericCAO* playercao = player->getCAO();
2695
2696                         assert( playercao != NULL );
2697                         if (camera.getCameraMode() > CAMERA_MODE_FIRST) {
2698                                 playercao->setVisible(true);
2699                         }
2700                         else {
2701                                 playercao->setVisible(false);
2702                         }
2703                 }
2704                 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2705                 camera.update(player, dtime, busytime, tool_reload_ratio,
2706                                 client.getEnv());
2707                 camera.step(dtime);
2708
2709                 v3f player_position = player->getPosition();
2710                 v3f camera_position = camera.getPosition();
2711                 v3f camera_direction = camera.getDirection();
2712                 f32 camera_fov = camera.getFovMax();
2713                 v3s16 camera_offset = camera.getOffset();
2714
2715                 bool camera_offset_changed = (camera_offset != old_camera_offset);
2716
2717                 if(!disable_camera_update){
2718                         client.getEnv().getClientMap().updateCamera(camera_position,
2719                                 camera_direction, camera_fov, camera_offset);
2720                         if (camera_offset_changed){
2721                                 client.updateCameraOffset(camera_offset);
2722                                 client.getEnv().updateCameraOffset(camera_offset);
2723                                 if (clouds)
2724                                         clouds->updateCameraOffset(camera_offset);
2725                         }
2726                 }
2727
2728                 // Update sound listener
2729                 sound->updateListener(camera.getCameraNode()->getPosition()+intToFloat(camera_offset, BS),
2730                                 v3f(0,0,0), // velocity
2731                                 camera.getDirection(),
2732                                 camera.getCameraNode()->getUpVector());
2733                 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2734
2735                 /*
2736                         Update sound maker
2737                 */
2738                 {
2739                         soundmaker.step(dtime);
2740
2741                         ClientMap &map = client.getEnv().getClientMap();
2742                         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2743                         soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2744                 }
2745
2746                 /*
2747                         Calculate what block is the crosshair pointing to
2748                 */
2749
2750                 //u32 t1 = device->getTimer()->getRealTime();
2751
2752                 f32 d = playeritem_def.range; // max. distance
2753                 f32 d_hand = itemdef->get("").range;
2754                 if(d < 0 && d_hand >= 0)
2755                         d = d_hand;
2756                 else if(d < 0)
2757                         d = 4.0;
2758                 core::line3d<f32> shootline(camera_position,
2759                                 camera_position + camera_direction * BS * (d+1));
2760
2761
2762                 // prevent player pointing anything in front-view
2763                 if (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)
2764                         shootline = core::line3d<f32>(0,0,0,0,0,0);
2765
2766 #ifdef HAVE_TOUCHSCREENGUI
2767                 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2768                         shootline = g_touchscreengui->getShootline();
2769                         shootline.start += intToFloat(camera_offset,BS);
2770                         shootline.end += intToFloat(camera_offset,BS);
2771                 }
2772 #endif
2773
2774                 ClientActiveObject *selected_object = NULL;
2775
2776                 PointedThing pointed = getPointedThing(
2777                                 // input
2778                                 &client, player_position, camera_direction,
2779                                 camera_position, shootline, d,
2780                                 playeritem_def.liquids_pointable, !ldown_for_dig,
2781                                 camera_offset,
2782                                 // output
2783                                 hilightboxes,
2784                                 selected_object);
2785
2786                 if(pointed != pointed_old)
2787                 {
2788                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2789                         if (g_settings->getBool("enable_node_highlighting"))
2790                                 client.setHighlighted(pointed.node_undersurface, show_hud);
2791                 }
2792
2793                 /*
2794                         Stop digging when
2795                         - releasing left mouse button
2796                         - pointing away from node
2797                 */
2798                 if(digging)
2799                 {
2800                         if(input->getLeftReleased())
2801                         {
2802                                 infostream<<"Left button released"
2803                                         <<" (stopped digging)"<<std::endl;
2804                                 digging = false;
2805                         }
2806                         else if(pointed != pointed_old)
2807                         {
2808                                 if (pointed.type == POINTEDTHING_NODE
2809                                         && pointed_old.type == POINTEDTHING_NODE
2810                                         && pointed.node_undersurface == pointed_old.node_undersurface)
2811                                 {
2812                                         // Still pointing to the same node,
2813                                         // but a different face. Don't reset.
2814                                 }
2815                                 else
2816                                 {
2817                                         infostream<<"Pointing away from node"
2818                                                 <<" (stopped digging)"<<std::endl;
2819                                         digging = false;
2820                                 }
2821                         }
2822                         if(!digging)
2823                         {
2824                                 client.interact(1, pointed_old);
2825                                 client.setCrack(-1, v3s16(0,0,0));
2826                                 dig_time = 0.0;
2827                         }
2828                 }
2829                 if(!digging && ldown_for_dig && !input->getLeftState())
2830                 {
2831                         ldown_for_dig = false;
2832                 }
2833
2834                 bool left_punch = false;
2835                 soundmaker.m_player_leftpunch_sound.name = "";
2836
2837                 if(input->getRightState())
2838                         repeat_rightclick_timer += dtime;
2839                 else
2840                         repeat_rightclick_timer = 0;
2841
2842                 if(playeritem_def.usable && input->getLeftState())
2843                 {
2844                         if(input->getLeftClicked())
2845                                 client.interact(4, pointed);
2846                 }
2847                 else if(pointed.type == POINTEDTHING_NODE)
2848                 {
2849                         v3s16 nodepos = pointed.node_undersurface;
2850                         v3s16 neighbourpos = pointed.node_abovesurface;
2851
2852                         /*
2853                                 Check information text of node
2854                         */
2855
2856                         ClientMap &map = client.getEnv().getClientMap();
2857                         NodeMetadata *meta = map.getNodeMetadata(nodepos);
2858                         if(meta){
2859                                 infotext = narrow_to_wide(meta->getString("infotext"));
2860                         } else {
2861                                 MapNode n = map.getNode(nodepos);
2862                                 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2863                                         infotext = L"Unknown node: ";
2864                                         infotext += narrow_to_wide(nodedef->get(n).name);
2865                                 }
2866                         }
2867
2868                         /*
2869                                 Handle digging
2870                         */
2871
2872                         if(nodig_delay_timer <= 0.0 && input->getLeftState()
2873                                         && client.checkPrivilege("interact"))
2874                         {
2875                                 if(!digging)
2876                                 {
2877                                         infostream<<"Started digging"<<std::endl;
2878                                         client.interact(0, pointed);
2879                                         digging = true;
2880                                         ldown_for_dig = true;
2881                                 }
2882                                 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2883
2884                                 // NOTE: Similar piece of code exists on the server side for
2885                                 // cheat detection.
2886                                 // Get digging parameters
2887                                 DigParams params = getDigParams(nodedef->get(n).groups,
2888                                                 &playeritem_toolcap);
2889                                 // If can't dig, try hand
2890                                 if(!params.diggable){
2891                                         const ItemDefinition &hand = itemdef->get("");
2892                                         const ToolCapabilities *tp = hand.tool_capabilities;
2893                                         if(tp)
2894                                                 params = getDigParams(nodedef->get(n).groups, tp);
2895                                 }
2896
2897                                 float dig_time_complete = 0.0;
2898
2899                                 if(params.diggable == false)
2900                                 {
2901                                         // I guess nobody will wait for this long
2902                                         dig_time_complete = 10000000.0;
2903                                 }
2904                                 else
2905                                 {
2906                                         dig_time_complete = params.time;
2907                                         if (g_settings->getBool("enable_particles"))
2908                                         {
2909                                                 const ContentFeatures &features =
2910                                                         client.getNodeDefManager()->get(n);
2911                                                 addPunchingParticles
2912                                                         (gamedef, smgr, player, client.getEnv(),
2913                                                          nodepos, features.tiles);
2914                                         }
2915                                 }
2916
2917                                 if(dig_time_complete >= 0.001)
2918                                 {
2919                                         dig_index = (u16)((float)crack_animation_length
2920                                                         * dig_time/dig_time_complete);
2921                                 }
2922                                 // This is for torches
2923                                 else
2924                                 {
2925                                         dig_index = crack_animation_length;
2926                                 }
2927
2928                                 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2929                                 if(sound_dig.exists() && params.diggable){
2930                                         if(sound_dig.name == "__group"){
2931                                                 if(params.main_group != ""){
2932                                                         soundmaker.m_player_leftpunch_sound.gain = 0.5;
2933                                                         soundmaker.m_player_leftpunch_sound.name =
2934                                                                         std::string("default_dig_") +
2935                                                                                         params.main_group;
2936                                                 }
2937                                         } else{
2938                                                 soundmaker.m_player_leftpunch_sound = sound_dig;
2939                                         }
2940                                 }
2941
2942                                 // Don't show cracks if not diggable
2943                                 if(dig_time_complete >= 100000.0)
2944                                 {
2945                                 }
2946                                 else if(dig_index < crack_animation_length)
2947                                 {
2948                                         //TimeTaker timer("client.setTempMod");
2949                                         //infostream<<"dig_index="<<dig_index<<std::endl;
2950                                         client.setCrack(dig_index, nodepos);
2951                                 }
2952                                 else
2953                                 {
2954                                         infostream<<"Digging completed"<<std::endl;
2955                                         client.interact(2, pointed);
2956                                         client.setCrack(-1, v3s16(0,0,0));
2957                                         MapNode wasnode = map.getNode(nodepos);
2958                                         client.removeNode(nodepos);
2959
2960                                         if (g_settings->getBool("enable_particles"))
2961                                         {
2962                                                 const ContentFeatures &features =
2963                                                         client.getNodeDefManager()->get(wasnode);
2964                                                 addDiggingParticles
2965                                                         (gamedef, smgr, player, client.getEnv(),
2966                                                          nodepos, features.tiles);
2967                                         }
2968
2969                                         dig_time = 0;
2970                                         digging = false;
2971
2972                                         nodig_delay_timer = dig_time_complete
2973                                                         / (float)crack_animation_length;
2974
2975                                         // We don't want a corresponding delay to
2976                                         // very time consuming nodes
2977                                         if(nodig_delay_timer > 0.3)
2978                                                 nodig_delay_timer = 0.3;
2979                                         // We want a slight delay to very little
2980                                         // time consuming nodes
2981                                         float mindelay = 0.15;
2982                                         if(nodig_delay_timer < mindelay)
2983                                                 nodig_delay_timer = mindelay;
2984
2985                                         // Send event to trigger sound
2986                                         MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2987                                         gamedef->event()->put(e);
2988                                 }
2989
2990                                 if(dig_time_complete < 100000.0)
2991                                         dig_time += dtime;
2992                                 else {
2993                                         dig_time = 0;
2994                                         client.setCrack(-1, nodepos);
2995                                 }
2996
2997                                 camera.setDigging(0);  // left click animation
2998                         }
2999
3000                         if((input->getRightClicked() ||
3001                                         repeat_rightclick_timer >=
3002                                                 g_settings->getFloat("repeat_rightclick_time")) &&
3003                                         client.checkPrivilege("interact"))
3004                         {
3005                                 repeat_rightclick_timer = 0;
3006                                 infostream<<"Ground right-clicked"<<std::endl;
3007
3008                                 if(meta && meta->getString("formspec") != "" && !random_input
3009                                                 && !input->isKeyDown(getKeySetting("keymap_sneak")))
3010                                 {
3011                                         infostream<<"Launching custom inventory view"<<std::endl;
3012
3013                                         InventoryLocation inventoryloc;
3014                                         inventoryloc.setNodeMeta(nodepos);
3015
3016                                         NodeMetadataFormSource* fs_src = new NodeMetadataFormSource(
3017                                                         &client.getEnv().getClientMap(), nodepos);
3018                                         TextDest* txt_dst = new TextDestNodeMetadata(nodepos, &client);
3019
3020                                         create_formspec_menu(&current_formspec, &client, gamedef,
3021                                                         tsrc, device, fs_src, txt_dst, &client);
3022
3023                                         current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3024                                 }
3025                                 // Otherwise report right click to server
3026                                 else
3027                                 {
3028                                         camera.setDigging(1);  // right click animation (always shown for feedback)
3029
3030                                         // If the wielded item has node placement prediction,
3031                                         // make that happen
3032                                         bool placed = nodePlacementPrediction(client,
3033                                                 playeritem_def,
3034                                                 nodepos, neighbourpos);
3035
3036                                         if(placed) {
3037                                                 // Report to server
3038                                                 client.interact(3, pointed);
3039                                                 // Read the sound
3040                                                 soundmaker.m_player_rightpunch_sound =
3041                                                         playeritem_def.sound_place;
3042                                         } else {
3043                                                 soundmaker.m_player_rightpunch_sound =
3044                                                         SimpleSoundSpec();
3045                                         }
3046
3047                                         if (playeritem_def.node_placement_prediction == "" ||
3048                                                 nodedef->get(map.getNode(nodepos)).rightclickable)
3049                                                 client.interact(3, pointed); // Report to server
3050                                 }
3051                         }
3052                 }
3053                 else if(pointed.type == POINTEDTHING_OBJECT)
3054                 {
3055                         infotext = narrow_to_wide(selected_object->infoText());
3056
3057                         if(infotext == L"" && show_debug){
3058                                 infotext = narrow_to_wide(selected_object->debugInfoText());
3059                         }
3060
3061                         //if(input->getLeftClicked())
3062                         if(input->getLeftState())
3063                         {
3064                                 bool do_punch = false;
3065                                 bool do_punch_damage = false;
3066                                 if(object_hit_delay_timer <= 0.0){
3067                                         do_punch = true;
3068                                         do_punch_damage = true;
3069                                         object_hit_delay_timer = object_hit_delay;
3070                                 }
3071                                 if(input->getLeftClicked()){
3072                                         do_punch = true;
3073                                 }
3074                                 if(do_punch){
3075                                         infostream<<"Left-clicked object"<<std::endl;
3076                                         left_punch = true;
3077                                 }
3078                                 if(do_punch_damage){
3079                                         // Report direct punch
3080                                         v3f objpos = selected_object->getPosition();
3081                                         v3f dir = (objpos - player_position).normalize();
3082
3083                                         bool disable_send = selected_object->directReportPunch(
3084                                                         dir, &playeritem, time_from_last_punch);
3085                                         time_from_last_punch = 0;
3086                                         if(!disable_send)
3087                                                 client.interact(0, pointed);
3088                                 }
3089                         }
3090                         else if(input->getRightClicked())
3091                         {
3092                                 infostream<<"Right-clicked object"<<std::endl;
3093                                 client.interact(3, pointed);  // place
3094                         }
3095                 }
3096                 else if(input->getLeftState())
3097                 {
3098                         // When button is held down in air, show continuous animation
3099                         left_punch = true;
3100                 }
3101
3102                 pointed_old = pointed;
3103
3104                 if(left_punch || input->getLeftClicked())
3105                 {
3106                         camera.setDigging(0); // left click animation
3107                 }
3108
3109                 input->resetLeftClicked();
3110                 input->resetRightClicked();
3111
3112                 input->resetLeftReleased();
3113                 input->resetRightReleased();
3114
3115                 /*
3116                         Calculate stuff for drawing
3117                 */
3118
3119                 /*
3120                         Fog range
3121                 */
3122
3123                 if(draw_control.range_all)
3124                         fog_range = 100000*BS;
3125                 else {
3126                         fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
3127                         fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
3128                         fog_range *= 0.9;
3129                 }
3130
3131                 /*
3132                         Calculate general brightness
3133                 */
3134                 u32 daynight_ratio = client.getEnv().getDayNightRatio();
3135                 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
3136                 float direct_brightness = 0;
3137                 bool sunlight_seen = false;
3138                 if(g_settings->getBool("free_move")){
3139                         direct_brightness = time_brightness;
3140                         sunlight_seen = true;
3141                 } else {
3142                         ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3143                         float old_brightness = sky->getBrightness();
3144                         direct_brightness = (float)client.getEnv().getClientMap()
3145                                         .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
3146                                         daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
3147                                         / 255.0;
3148                 }
3149
3150                 time_of_day = client.getEnv().getTimeOfDayF();
3151                 float maxsm = 0.05;
3152                 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
3153                                 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3154                                 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3155                         time_of_day_smooth = time_of_day;
3156                 float todsm = 0.05;
3157                 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
3158                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3159                                         + (time_of_day+1.0) * todsm;
3160                 else
3161                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3162                                         + time_of_day * todsm;
3163
3164                 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3165                                 sunlight_seen,camera.getCameraMode(), player->getYaw(),
3166                                 player->getPitch());
3167
3168                 video::SColor bgcolor = sky->getBgColor();
3169                 video::SColor skycolor = sky->getSkyColor();
3170
3171                 /*
3172                         Update clouds
3173                 */
3174                 if(clouds){
3175                         if(sky->getCloudsVisible()){
3176                                 clouds->setVisible(true);
3177                                 clouds->step(dtime);
3178                                 clouds->update(v2f(player_position.X, player_position.Z),
3179                                                 sky->getCloudColor());
3180                         } else{
3181                                 clouds->setVisible(false);
3182                         }
3183                 }
3184
3185                 /*
3186                         Update particles
3187                 */
3188
3189                 allparticles_step(dtime);
3190                 allparticlespawners_step(dtime, client.getEnv());
3191
3192                 /*
3193                         Fog
3194                 */
3195
3196                 if(g_settings->getBool("enable_fog") && !force_fog_off)
3197                 {
3198                         driver->setFog(
3199                                 bgcolor,
3200                                 video::EFT_FOG_LINEAR,
3201                                 fog_range*0.4,
3202                                 fog_range*1.0,
3203                                 0.01,
3204                                 false, // pixel fog
3205                                 false // range fog
3206                         );
3207                 }
3208                 else
3209                 {
3210                         driver->setFog(
3211                                 bgcolor,
3212                                 video::EFT_FOG_LINEAR,
3213                                 100000*BS,
3214                                 110000*BS,
3215                                 0.01,
3216                                 false, // pixel fog
3217                                 false // range fog
3218                         );
3219                 }
3220
3221                 /*
3222                         Update gui stuff (0ms)
3223                 */
3224
3225                 //TimeTaker guiupdatetimer("Gui updating");
3226
3227                 if(show_debug)
3228                 {
3229                         static float drawtime_avg = 0;
3230                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3231                         /*static float beginscenetime_avg = 0;
3232                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3233                         static float scenetime_avg = 0;
3234                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3235                         static float endscenetime_avg = 0;
3236                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3237
3238                         u16 fps = (1.0/dtime_avg1);
3239
3240                         std::ostringstream os(std::ios_base::binary);
3241                         os<<std::fixed
3242                                 <<"Minetest "<<minetest_version_hash
3243                                 <<" FPS = "<<fps
3244                                 <<" (R: range_all="<<draw_control.range_all<<")"
3245                                 <<std::setprecision(0)
3246                                 <<" drawtime = "<<drawtime_avg
3247                                 <<std::setprecision(1)
3248                                 <<", dtime_jitter = "
3249                                 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3250                                 <<std::setprecision(1)
3251                                 <<", v_range = "<<draw_control.wanted_range
3252                                 <<std::setprecision(3)
3253                                 <<", RTT = "<<client.getRTT();
3254                         guitext->setText(narrow_to_wide(os.str()).c_str());
3255                         guitext->setVisible(true);
3256                 }
3257                 else if(show_hud || show_chat)
3258                 {
3259                         std::ostringstream os(std::ios_base::binary);
3260                         os<<"Minetest "<<minetest_version_hash;
3261                         guitext->setText(narrow_to_wide(os.str()).c_str());
3262                         guitext->setVisible(true);
3263                 }
3264                 else
3265                 {
3266                         guitext->setVisible(false);
3267                 }
3268
3269                 if (guitext->isVisible())
3270                 {
3271                         core::rect<s32> rect(
3272                                 5,
3273                                 5,
3274                                 screensize.X,
3275                                 5 + text_height
3276                         );
3277                         guitext->setRelativePosition(rect);
3278                 }
3279
3280                 if(show_debug)
3281                 {
3282                         std::ostringstream os(std::ios_base::binary);
3283                         os<<std::setprecision(1)<<std::fixed
3284                                 <<"(" <<(player_position.X/BS)
3285                                 <<", "<<(player_position.Y/BS)
3286                                 <<", "<<(player_position.Z/BS)
3287                                 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3288                                 <<") (seed = "<<((u64)client.getMapSeed())
3289                                 <<")";
3290                         guitext2->setText(narrow_to_wide(os.str()).c_str());
3291                         guitext2->setVisible(true);
3292
3293                         core::rect<s32> rect(
3294                                 5,
3295                                 5 + text_height,
3296                                 screensize.X,
3297                                 5 + (text_height * 2)
3298                         );
3299                         guitext2->setRelativePosition(rect);
3300                 }
3301                 else
3302                 {
3303                         guitext2->setVisible(false);
3304                 }
3305
3306                 {
3307                         guitext_info->setText(infotext.c_str());
3308                         guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3309                 }
3310
3311                 {
3312                         float statustext_time_max = 1.5;
3313                         if(!statustext.empty())
3314                         {
3315                                 statustext_time += dtime;
3316                                 if(statustext_time >= statustext_time_max)
3317                                 {
3318                                         statustext = L"";
3319                                         statustext_time = 0;
3320                                 }
3321                         }
3322                         guitext_status->setText(statustext.c_str());
3323                         guitext_status->setVisible(!statustext.empty());
3324
3325                         if(!statustext.empty())
3326                         {
3327                                 s32 status_y = screensize.Y - 130;
3328                                 core::rect<s32> rect(
3329                                                 10,
3330                                                 status_y - guitext_status->getTextHeight(),
3331                                                 10 + guitext_status->getTextWidth(),
3332                                                 status_y
3333                                 );
3334                                 guitext_status->setRelativePosition(rect);
3335
3336                                 // Fade out
3337                                 video::SColor initial_color(255,0,0,0);
3338                                 if(guienv->getSkin())
3339                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3340                                 video::SColor final_color = initial_color;
3341                                 final_color.setAlpha(0);
3342                                 video::SColor fade_color =
3343                                         initial_color.getInterpolated_quadratic(
3344                                                 initial_color,
3345                                                 final_color,
3346                                                 pow(statustext_time / (float)statustext_time_max, 2.0f));
3347                                 guitext_status->setOverrideColor(fade_color);
3348                                 guitext_status->enableOverrideColor(true);
3349                         }
3350                 }
3351
3352                 /*
3353                         Get chat messages from client
3354                 */
3355                 updateChat(client, dtime, show_debug, screensize, show_chat,
3356                                 show_profiler, chat_backend, guitext_chat, font);
3357
3358                 /*
3359                         Inventory
3360                 */
3361
3362                 if(client.getPlayerItem() != new_playeritem)
3363                 {
3364                         client.selectPlayerItem(new_playeritem);
3365                 }
3366                 if(client.getLocalInventoryUpdated())
3367                 {
3368                         //infostream<<"Updating local inventory"<<std::endl;
3369                         client.getLocalInventory(local_inventory);
3370
3371                         update_wielded_item_trigger = true;
3372                 }
3373                 if(update_wielded_item_trigger)
3374                 {
3375                         update_wielded_item_trigger = false;
3376                         // Update wielded tool
3377                         InventoryList *mlist = local_inventory.getList("main");
3378                         ItemStack item;
3379                         if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
3380                                 item = mlist->getItem(client.getPlayerItem());
3381                         camera.wield(item, client.getPlayerItem());
3382                 }
3383
3384                 /*
3385                         Update block draw list every 200ms or when camera direction has
3386                         changed much
3387                 */
3388                 update_draw_list_timer += dtime;
3389                 if(update_draw_list_timer >= 0.2 ||
3390                                 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 ||
3391                                 camera_offset_changed){
3392                         update_draw_list_timer = 0;
3393                         client.getEnv().getClientMap().updateDrawList(driver);
3394                         update_draw_list_last_cam_dir = camera_direction;
3395                 }
3396
3397                 /*
3398                         make sure menu is on top
3399                 */
3400                 if ((!noMenuActive()) && (current_formspec)) {
3401                                 guiroot->bringToFront(current_formspec);
3402                 }
3403
3404                 /*
3405                         Drawing begins
3406                 */
3407                 TimeTaker tt_draw("mainloop: draw");
3408                 {
3409                         TimeTaker timer("beginScene");
3410                         driver->beginScene(true, true, skycolor);
3411                         beginscenetime = timer.stop(true);
3412                 }
3413
3414
3415                 draw_scene(driver, smgr, camera, client, player, hud, guienv,
3416                                 hilightboxes, screensize, skycolor, show_hud);
3417
3418                 /*
3419                         Profiler graph
3420                 */
3421                 if(show_profiler_graph)
3422                 {
3423                         graph.draw(10, screensize.Y - 10, driver, font);
3424                 }
3425
3426                 /*
3427                         Damage flash
3428                 */
3429                 if(damage_flash > 0.0)
3430                 {
3431                         video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3432                         driver->draw2DRectangle(color,
3433                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
3434                                         NULL);
3435
3436                         damage_flash -= 100.0*dtime;
3437                 }
3438
3439                 /*
3440                         Damage camera tilt
3441                 */
3442                 if(player->hurt_tilt_timer > 0.0)
3443                 {
3444                         player->hurt_tilt_timer -= dtime*5;
3445                         if(player->hurt_tilt_timer < 0)
3446                                 player->hurt_tilt_strength = 0;
3447                 }
3448
3449                 /*
3450                         End scene
3451                 */
3452                 {
3453                         TimeTaker timer("endScene");
3454                         driver->endScene();
3455                         endscenetime = timer.stop(true);
3456                 }
3457
3458                 drawtime = tt_draw.stop(true);
3459                 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3460
3461                 /*
3462                         End of drawing
3463                 */
3464
3465                 /*
3466                         Log times and stuff for visualization
3467                 */
3468                 Profiler::GraphValues values;
3469                 g_profiler->graphGet(values);
3470                 graph.put(values);
3471         }
3472
3473         /*
3474                 Drop stuff
3475         */
3476         if (clouds)
3477                 clouds->drop();
3478         if (gui_chat_console)
3479                 gui_chat_console->drop();
3480         if (sky)
3481                 sky->drop();
3482         clear_particles();
3483
3484         /* cleanup menus */
3485         while (g_menumgr.menuCount() > 0)
3486         {
3487                 g_menumgr.m_stack.front()->setVisible(false);
3488                 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
3489         }
3490         /*
3491                 Draw a "shutting down" screen, which will be shown while the map
3492                 generator and other stuff quits
3493         */
3494         {
3495                 wchar_t* text = wgettext("Shutting down stuff...");
3496                 draw_load_screen(text, device, guienv, font, 0, -1, false);
3497                 delete[] text;
3498         }
3499
3500         chat_backend.addMessage(L"", L"# Disconnected.");
3501         chat_backend.addMessage(L"", L"");
3502
3503         client.Stop();
3504
3505         //force answer all texture and shader jobs (TODO return empty values)
3506
3507         while(!client.isShutdown()) {
3508                 tsrc->processQueue();
3509                 shsrc->processQueue();
3510                 sleep_ms(100);
3511         }
3512
3513         // Client scope (client is destructed before destructing *def and tsrc)
3514         }while(0);
3515         } // try-catch
3516         catch(SerializationError &e)
3517         {
3518                 error_message = L"A serialization error occurred:\n"
3519                                 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3520                                 L" running a different version of Minetest.";
3521                 errorstream<<wide_to_narrow(error_message)<<std::endl;
3522         }
3523         catch(ServerError &e) {
3524                 error_message = narrow_to_wide(e.what());
3525                 errorstream << "ServerError: " << e.what() << std::endl;
3526         }
3527         catch(ModError &e) {
3528                 errorstream << "ModError: " << e.what() << std::endl;
3529                 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3530         }
3531
3532
3533
3534         if(!sound_is_dummy)
3535                 delete sound;
3536
3537         //has to be deleted first to stop all server threads
3538         delete server;
3539
3540         delete tsrc;
3541         delete shsrc;
3542         delete nodedef;
3543         delete itemdef;
3544
3545         //extended resource accounting
3546         infostream << "Irrlicht resources after cleanup:" << std::endl;
3547         infostream << "\tRemaining meshes   : "
3548                 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3549         infostream << "\tRemaining textures : "
3550                 << driver->getTextureCount() << std::endl;
3551         for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3552                 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3553                 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3554                                 << std::endl;
3555         }
3556         clearTextureNameCache();
3557         infostream << "\tRemaining materials: "
3558                 << driver-> getMaterialRendererCount ()
3559                 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;
3560 }