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