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