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