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