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