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