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