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