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