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