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