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