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