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