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