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