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