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