0c1a2137008bdcec0b3265ffe37a93db5219085c
[oweals/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
845 public:
846         GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
847                         f32 *fog_range):
848                 m_sky(sky),
849                 m_force_fog_off(force_fog_off),
850                 m_fog_range(fog_range)
851         {}
852         ~GameGlobalShaderConstantSetter() {}
853
854         virtual void onSetConstants(video::IMaterialRendererServices *services,
855                         bool is_highlevel)
856         {
857                 if(!is_highlevel)
858                         return;
859
860                 // Background color
861                 video::SColor bgcolor = m_sky->getBgColor();
862                 video::SColorf bgcolorf(bgcolor);
863                 float bgcolorfa[4] = {
864                         bgcolorf.r,
865                         bgcolorf.g,
866                         bgcolorf.b,
867                         bgcolorf.a,
868                 };
869                 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
870
871                 // Fog distance
872                 float fog_distance = *m_fog_range;
873                 if(*m_force_fog_off)
874                         fog_distance = 10000*BS;
875                 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
876         }
877
878 private:
879         IrrlichtDevice *m_device;
880 };
881
882 void the_game(
883         bool &kill,
884         bool random_input,
885         InputHandler *input,
886         IrrlichtDevice *device,
887         gui::IGUIFont* font,
888         std::string map_dir,
889         std::string playername,
890         std::string password,
891         std::string address, // If "", local server is used
892         u16 port,
893         std::wstring &error_message,
894         std::string configpath,
895         ChatBackend &chat_backend,
896         const SubgameSpec &gamespec, // Used for local game,
897         bool simple_singleplayer_mode
898 )
899 {
900         video::IVideoDriver* driver = device->getVideoDriver();
901         scene::ISceneManager* smgr = device->getSceneManager();
902         
903         // Calculate text height using the font
904         u32 text_height = font->getDimension(L"Random test string").Height;
905
906         v2u32 screensize(0,0);
907         v2u32 last_screensize(0,0);
908         screensize = driver->getScreenSize();
909
910         const s32 hotbar_itemcount = 8;
911         //const s32 hotbar_imagesize = 36;
912         //const s32 hotbar_imagesize = 64;
913         s32 hotbar_imagesize = 48;
914         
915         /*
916                 Draw "Loading" screen
917         */
918
919         draw_load_screen(L"Loading...", driver, font);
920         
921         // Create texture source
922         IWritableTextureSource *tsrc = createTextureSource(device);
923         
924         // Create shader source
925         IWritableShaderSource *shsrc = createShaderSource(device);
926         
927         // These will be filled by data received from the server
928         // Create item definition manager
929         IWritableItemDefManager *itemdef = createItemDefManager();
930         // Create node definition manager
931         IWritableNodeDefManager *nodedef = createNodeDefManager();
932         
933         // Sound fetcher (useful when testing)
934         GameOnDemandSoundFetcher soundfetcher;
935
936         // Sound manager
937         ISoundManager *sound = NULL;
938         bool sound_is_dummy = false;
939 #if USE_SOUND
940         if(g_settings->getBool("enable_sound")){
941                 infostream<<"Attempting to use OpenAL audio"<<std::endl;
942                 sound = createOpenALSoundManager(&soundfetcher);
943                 if(!sound)
944                         infostream<<"Failed to initialize OpenAL audio"<<std::endl;
945         } else {
946                 infostream<<"Sound disabled."<<std::endl;
947         }
948 #endif
949         if(!sound){
950                 infostream<<"Using dummy audio."<<std::endl;
951                 sound = &dummySoundManager;
952                 sound_is_dummy = true;
953         }
954
955         // Event manager
956         EventManager eventmgr;
957
958         // Sound maker
959         SoundMaker soundmaker(sound, nodedef);
960         soundmaker.registerReceiver(&eventmgr);
961         
962         // Add chat log output for errors to be shown in chat
963         LogOutputBuffer chat_log_error_buf(LMT_ERROR);
964
965         // Create UI for modifying quicktune values
966         QuicktuneShortcutter quicktune;
967
968         /*
969                 Create server.
970                 SharedPtr will delete it when it goes out of scope.
971         */
972         SharedPtr<Server> server;
973         if(address == ""){
974                 draw_load_screen(L"Creating server...", driver, font);
975                 infostream<<"Creating server"<<std::endl;
976                 server = new Server(map_dir, configpath, gamespec,
977                                 simple_singleplayer_mode);
978                 server->start(port);
979         }
980
981         try{
982         do{ // Client scope (breakable do-while(0))
983         
984         /*
985                 Create client
986         */
987
988         draw_load_screen(L"Creating client...", driver, font);
989         infostream<<"Creating client"<<std::endl;
990         
991         MapDrawControl draw_control;
992
993         Client client(device, playername.c_str(), password, draw_control,
994                         tsrc, shsrc, itemdef, nodedef, sound, &eventmgr);
995         
996         // Client acts as our GameDef
997         IGameDef *gamedef = &client;
998                         
999         draw_load_screen(L"Resolving address...", driver, font);
1000         Address connect_address(0,0,0,0, port);
1001         try{
1002                 if(address == "")
1003                         //connect_address.Resolve("localhost");
1004                         connect_address.setAddress(127,0,0,1);
1005                 else
1006                         connect_address.Resolve(address.c_str());
1007         }
1008         catch(ResolveError &e)
1009         {
1010                 error_message = L"Couldn't resolve address";
1011                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1012                 // Break out of client scope
1013                 break;
1014         }
1015
1016         /*
1017                 Attempt to connect to the server
1018         */
1019         
1020         infostream<<"Connecting to server at ";
1021         connect_address.print(&infostream);
1022         infostream<<std::endl;
1023         client.connect(connect_address);
1024         
1025         /*
1026                 Wait for server to accept connection
1027         */
1028         bool could_connect = false;
1029         bool connect_aborted = false;
1030         try{
1031                 float frametime = 0.033;
1032                 float time_counter = 0.0;
1033                 input->clear();
1034                 while(device->run())
1035                 {
1036                         // Update client and server
1037                         client.step(frametime);
1038                         if(server != NULL)
1039                                 server->step(frametime);
1040                         
1041                         // End condition
1042                         if(client.connectedAndInitialized()){
1043                                 could_connect = true;
1044                                 break;
1045                         }
1046                         // Break conditions
1047                         if(client.accessDenied()){
1048                                 error_message = L"Access denied. Reason: "
1049                                                 +client.accessDeniedReason();
1050                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1051                                 break;
1052                         }
1053                         if(input->wasKeyDown(EscapeKey)){
1054                                 connect_aborted = true;
1055                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1056                                 break;
1057                         }
1058                         
1059                         // Display status
1060                         std::wostringstream ss;
1061                         ss<<L"Connecting to server... (press Escape to cancel)\n";
1062                         std::wstring animation = L"/-\\|";
1063                         ss<<animation[(int)(time_counter/0.2)%4];
1064                         draw_load_screen(ss.str(), driver, font);
1065                         
1066                         // Delay a bit
1067                         sleep_ms(1000*frametime);
1068                         time_counter += frametime;
1069                 }
1070         }
1071         catch(con::PeerNotFoundException &e)
1072         {}
1073         
1074         /*
1075                 Handle failure to connect
1076         */
1077         if(!could_connect){
1078                 if(error_message == L"" && !connect_aborted){
1079                         error_message = L"Connection failed";
1080                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1081                 }
1082                 // Break out of client scope
1083                 break;
1084         }
1085         
1086         /*
1087                 Wait until content has been received
1088         */
1089         bool got_content = false;
1090         bool content_aborted = false;
1091         {
1092                 float frametime = 0.033;
1093                 float time_counter = 0.0;
1094                 input->clear();
1095                 while(device->run())
1096                 {
1097                         // Update client and server
1098                         client.step(frametime);
1099                         if(server != NULL)
1100                                 server->step(frametime);
1101                         
1102                         // End condition
1103                         if(client.texturesReceived() &&
1104                                         client.itemdefReceived() &&
1105                                         client.nodedefReceived()){
1106                                 got_content = true;
1107                                 break;
1108                         }
1109                         // Break conditions
1110                         if(!client.connectedAndInitialized()){
1111                                 error_message = L"Client disconnected";
1112                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1113                                 break;
1114                         }
1115                         if(input->wasKeyDown(EscapeKey)){
1116                                 content_aborted = true;
1117                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1118                                 break;
1119                         }
1120                         
1121                         // Display status
1122                         std::wostringstream ss;
1123                         ss<<L"Waiting content... (press Escape to cancel)\n";
1124
1125                         ss<<(client.itemdefReceived()?L"[X]":L"[  ]");
1126                         ss<<L" Item definitions\n";
1127                         ss<<(client.nodedefReceived()?L"[X]":L"[  ]");
1128                         ss<<L" Node definitions\n";
1129                         ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1130                         ss<<L" Media\n";
1131
1132                         draw_load_screen(ss.str(), driver, font);
1133                         
1134                         // Delay a bit
1135                         sleep_ms(1000*frametime);
1136                         time_counter += frametime;
1137                 }
1138         }
1139
1140         if(!got_content){
1141                 if(error_message == L"" && !content_aborted){
1142                         error_message = L"Something failed";
1143                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1144                 }
1145                 // Break out of client scope
1146                 break;
1147         }
1148
1149         /*
1150                 After all content has been received:
1151                 Update cached textures, meshes and materials
1152         */
1153         client.afterContentReceived();
1154
1155         /*
1156                 Create the camera node
1157         */
1158         Camera camera(smgr, draw_control, gamedef);
1159         if (!camera.successfullyCreated(error_message))
1160                 return;
1161
1162         f32 camera_yaw = 0; // "right/left"
1163         f32 camera_pitch = 0; // "up/down"
1164
1165         /*
1166                 Clouds
1167         */
1168         
1169         Clouds *clouds = NULL;
1170         if(g_settings->getBool("enable_clouds"))
1171         {
1172                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1173         }
1174
1175         /*
1176                 Skybox thingy
1177         */
1178
1179         Sky *sky = NULL;
1180         sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1181         
1182         /*
1183                 FarMesh
1184         */
1185
1186         FarMesh *farmesh = NULL;
1187         if(g_settings->getBool("enable_farmesh"))
1188         {
1189                 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1190         }
1191
1192         /*
1193                 A copy of the local inventory
1194         */
1195         Inventory local_inventory(itemdef);
1196
1197         /*
1198                 Find out size of crack animation
1199         */
1200         int crack_animation_length = 5;
1201         {
1202                 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1203                 v2u32 size = t->getOriginalSize();
1204                 crack_animation_length = size.Y / size.X;
1205         }
1206
1207         /*
1208                 Add some gui stuff
1209         */
1210
1211         // First line of debug text
1212         gui::IGUIStaticText *guitext = guienv->addStaticText(
1213                         L"Minetest-c55",
1214                         core::rect<s32>(5, 5, 795, 5+text_height),
1215                         false, false);
1216         // Second line of debug text
1217         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1218                         L"",
1219                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1220                         false, false);
1221         // At the middle of the screen
1222         // Object infos are shown in this
1223         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1224                         L"",
1225                         core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1226                         false, false);
1227         
1228         // Status text (displays info when showing and hiding GUI stuff, etc.)
1229         gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1230                         L"<Status>",
1231                         core::rect<s32>(0,0,0,0),
1232                         false, false);
1233         guitext_status->setVisible(false);
1234         
1235         std::wstring statustext;
1236         float statustext_time = 0;
1237         
1238         // Chat text
1239         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1240                         L"",
1241                         core::rect<s32>(0,0,0,0),
1242                         //false, false); // Disable word wrap as of now
1243                         false, true);
1244         // Remove stale "recent" chat messages from previous connections
1245         chat_backend.clearRecentChat();
1246         // Chat backend and console
1247         GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1248         
1249         // Profiler text (size is updated when text is updated)
1250         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1251                         L"<Profiler>",
1252                         core::rect<s32>(0,0,0,0),
1253                         false, false);
1254         guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1255         guitext_profiler->setVisible(false);
1256         
1257         /*
1258                 Some statistics are collected in these
1259         */
1260         u32 drawtime = 0;
1261         u32 beginscenetime = 0;
1262         u32 scenetime = 0;
1263         u32 endscenetime = 0;
1264         
1265         float recent_turn_speed = 0.0;
1266         
1267         ProfilerGraph graph;
1268         // Initially clear the profiler
1269         Profiler::GraphValues dummyvalues;
1270         g_profiler->graphGet(dummyvalues);
1271
1272         float nodig_delay_timer = 0.0;
1273         float dig_time = 0.0;
1274         u16 dig_index = 0;
1275         PointedThing pointed_old;
1276         bool digging = false;
1277         bool ldown_for_dig = false;
1278
1279         float damage_flash_timer = 0;
1280         s16 farmesh_range = 20*MAP_BLOCKSIZE;
1281
1282         const float object_hit_delay = 0.2;
1283         float object_hit_delay_timer = 0.0;
1284         float time_from_last_punch = 10;
1285
1286         float update_draw_list_timer = 0.0;
1287         v3f update_draw_list_last_cam_dir;
1288
1289         bool invert_mouse = g_settings->getBool("invert_mouse");
1290
1291         bool respawn_menu_active = false;
1292         bool update_wielded_item_trigger = false;
1293
1294         bool show_hud = true;
1295         bool show_chat = true;
1296         bool force_fog_off = false;
1297         f32 fog_range = 100*BS;
1298         bool disable_camera_update = false;
1299         bool show_debug = g_settings->getBool("show_debug");
1300         bool show_profiler_graph = false;
1301         u32 show_profiler = 0;
1302         u32 show_profiler_max = 3;  // Number of pages
1303
1304         float time_of_day = 0;
1305         float time_of_day_smooth = 0;
1306
1307         /*
1308                 Shader constants
1309         */
1310         shsrc->addGlobalConstantSetter(
1311                         new GameGlobalShaderConstantSetter(sky, &force_fog_off, &fog_range));
1312
1313         /*
1314                 Main loop
1315         */
1316
1317         bool first_loop_after_window_activation = true;
1318
1319         // TODO: Convert the static interval timers to these
1320         // Interval limiter for profiler
1321         IntervalLimiter m_profiler_interval;
1322
1323         // Time is in milliseconds
1324         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1325         // NOTE: So we have to use getTime() and call run()s between them
1326         u32 lasttime = device->getTimer()->getTime();
1327
1328         for(;;)
1329         {
1330                 if(device->run() == false || kill == true)
1331                         break;
1332
1333                 // Time of frame without fps limit
1334                 float busytime;
1335                 u32 busytime_u32;
1336                 {
1337                         // not using getRealTime is necessary for wine
1338                         u32 time = device->getTimer()->getTime();
1339                         if(time > lasttime)
1340                                 busytime_u32 = time - lasttime;
1341                         else
1342                                 busytime_u32 = 0;
1343                         busytime = busytime_u32 / 1000.0;
1344                 }
1345                 
1346                 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1347
1348                 // Necessary for device->getTimer()->getTime()
1349                 device->run();
1350
1351                 /*
1352                         FPS limiter
1353                 */
1354
1355                 {
1356                         float fps_max = g_settings->getFloat("fps_max");
1357                         u32 frametime_min = 1000./fps_max;
1358                         
1359                         if(busytime_u32 < frametime_min)
1360                         {
1361                                 u32 sleeptime = frametime_min - busytime_u32;
1362                                 device->sleep(sleeptime);
1363                                 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1364                         }
1365                 }
1366
1367                 // Necessary for device->getTimer()->getTime()
1368                 device->run();
1369
1370                 /*
1371                         Time difference calculation
1372                 */
1373                 f32 dtime; // in seconds
1374                 
1375                 u32 time = device->getTimer()->getTime();
1376                 if(time > lasttime)
1377                         dtime = (time - lasttime) / 1000.0;
1378                 else
1379                         dtime = 0;
1380                 lasttime = time;
1381
1382                 g_profiler->graphAdd("mainloop_dtime", dtime);
1383
1384                 /* Run timers */
1385
1386                 if(nodig_delay_timer >= 0)
1387                         nodig_delay_timer -= dtime;
1388                 if(object_hit_delay_timer >= 0)
1389                         object_hit_delay_timer -= dtime;
1390                 time_from_last_punch += dtime;
1391                 
1392                 g_profiler->add("Elapsed time", dtime);
1393                 g_profiler->avg("FPS", 1./dtime);
1394
1395                 /*
1396                         Time average and jitter calculation
1397                 */
1398
1399                 static f32 dtime_avg1 = 0.0;
1400                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1401                 f32 dtime_jitter1 = dtime - dtime_avg1;
1402
1403                 static f32 dtime_jitter1_max_sample = 0.0;
1404                 static f32 dtime_jitter1_max_fraction = 0.0;
1405                 {
1406                         static f32 jitter1_max = 0.0;
1407                         static f32 counter = 0.0;
1408                         if(dtime_jitter1 > jitter1_max)
1409                                 jitter1_max = dtime_jitter1;
1410                         counter += dtime;
1411                         if(counter > 0.0)
1412                         {
1413                                 counter -= 3.0;
1414                                 dtime_jitter1_max_sample = jitter1_max;
1415                                 dtime_jitter1_max_fraction
1416                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1417                                 jitter1_max = 0.0;
1418                         }
1419                 }
1420                 
1421                 /*
1422                         Busytime average and jitter calculation
1423                 */
1424
1425                 static f32 busytime_avg1 = 0.0;
1426                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1427                 f32 busytime_jitter1 = busytime - busytime_avg1;
1428                 
1429                 static f32 busytime_jitter1_max_sample = 0.0;
1430                 static f32 busytime_jitter1_min_sample = 0.0;
1431                 {
1432                         static f32 jitter1_max = 0.0;
1433                         static f32 jitter1_min = 0.0;
1434                         static f32 counter = 0.0;
1435                         if(busytime_jitter1 > jitter1_max)
1436                                 jitter1_max = busytime_jitter1;
1437                         if(busytime_jitter1 < jitter1_min)
1438                                 jitter1_min = busytime_jitter1;
1439                         counter += dtime;
1440                         if(counter > 0.0){
1441                                 counter -= 3.0;
1442                                 busytime_jitter1_max_sample = jitter1_max;
1443                                 busytime_jitter1_min_sample = jitter1_min;
1444                                 jitter1_max = 0.0;
1445                                 jitter1_min = 0.0;
1446                         }
1447                 }
1448
1449                 /*
1450                         Handle miscellaneous stuff
1451                 */
1452                 
1453                 if(client.accessDenied())
1454                 {
1455                         error_message = L"Access denied. Reason: "
1456                                         +client.accessDeniedReason();
1457                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1458                         break;
1459                 }
1460
1461                 if(g_gamecallback->disconnect_requested)
1462                 {
1463                         g_gamecallback->disconnect_requested = false;
1464                         break;
1465                 }
1466
1467                 if(g_gamecallback->changepassword_requested)
1468                 {
1469                         (new GUIPasswordChange(guienv, guiroot, -1,
1470                                 &g_menumgr, &client))->drop();
1471                         g_gamecallback->changepassword_requested = false;
1472                 }
1473
1474                 /* Process TextureSource's queue */
1475                 tsrc->processQueue();
1476
1477                 /* Process ItemDefManager's queue */
1478                 itemdef->processQueue(gamedef);
1479
1480                 /*
1481                         Process ShaderSource's queue
1482                 */
1483                 shsrc->processQueue();
1484
1485                 /*
1486                         Random calculations
1487                 */
1488                 last_screensize = screensize;
1489                 screensize = driver->getScreenSize();
1490                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1491                 //bool screensize_changed = screensize != last_screensize;
1492
1493                 // Resize hotbar
1494                 if(screensize.Y <= 800)
1495                         hotbar_imagesize = 32;
1496                 else if(screensize.Y <= 1280)
1497                         hotbar_imagesize = 48;
1498                 else
1499                         hotbar_imagesize = 64;
1500                 
1501                 // Hilight boxes collected during the loop and displayed
1502                 std::vector<aabb3f> hilightboxes;
1503                 
1504                 // Info text
1505                 std::wstring infotext;
1506
1507                 /*
1508                         Debug info for client
1509                 */
1510                 {
1511                         static float counter = 0.0;
1512                         counter -= dtime;
1513                         if(counter < 0)
1514                         {
1515                                 counter = 30.0;
1516                                 client.printDebugInfo(infostream);
1517                         }
1518                 }
1519
1520                 /*
1521                         Profiler
1522                 */
1523                 float profiler_print_interval =
1524                                 g_settings->getFloat("profiler_print_interval");
1525                 bool print_to_log = true;
1526                 if(profiler_print_interval == 0){
1527                         print_to_log = false;
1528                         profiler_print_interval = 5;
1529                 }
1530                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1531                 {
1532                         if(print_to_log){
1533                                 infostream<<"Profiler:"<<std::endl;
1534                                 g_profiler->print(infostream);
1535                         }
1536
1537                         update_profiler_gui(guitext_profiler, font, text_height,
1538                                         show_profiler, show_profiler_max);
1539
1540                         g_profiler->clear();
1541                 }
1542
1543                 /*
1544                         Direct handling of user input
1545                 */
1546                 
1547                 // Reset input if window not active or some menu is active
1548                 if(device->isWindowActive() == false
1549                                 || noMenuActive() == false
1550                                 || guienv->hasFocus(gui_chat_console))
1551                 {
1552                         input->clear();
1553                 }
1554
1555                 // Input handler step() (used by the random input generator)
1556                 input->step(dtime);
1557
1558                 /*
1559                         Launch menus and trigger stuff according to keys
1560                 */
1561                 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1562                 {
1563                         // drop selected item
1564                         IDropAction *a = new IDropAction();
1565                         a->count = 0;
1566                         a->from_inv.setCurrentPlayer();
1567                         a->from_list = "main";
1568                         a->from_i = client.getPlayerItem();
1569                         client.inventoryAction(a);
1570                 }
1571                 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1572                 {
1573                         infostream<<"the_game: "
1574                                         <<"Launching inventory"<<std::endl;
1575                         
1576                         GUIFormSpecMenu *menu =
1577                                 new GUIFormSpecMenu(device, guiroot, -1,
1578                                         &g_menumgr,
1579                                         &client, gamedef);
1580
1581                         InventoryLocation inventoryloc;
1582                         inventoryloc.setCurrentPlayer();
1583
1584                         PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1585                         assert(src);
1586                         menu->setFormSpec(src->getForm(), inventoryloc);
1587                         menu->setFormSource(src);
1588                         menu->setTextDest(new TextDestPlayerInventory(&client));
1589                         menu->drop();
1590                 }
1591                 else if(input->wasKeyDown(EscapeKey))
1592                 {
1593                         infostream<<"the_game: "
1594                                         <<"Launching pause menu"<<std::endl;
1595                         // It will delete itself by itself
1596                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1597                                         &g_menumgr, simple_singleplayer_mode))->drop();
1598
1599                         // Move mouse cursor on top of the disconnect button
1600                         if(simple_singleplayer_mode)
1601                                 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1602                         else
1603                                 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1604                 }
1605                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1606                 {
1607                         TextDest *dest = new TextDestChat(&client);
1608
1609                         (new GUITextInputMenu(guienv, guiroot, -1,
1610                                         &g_menumgr, dest,
1611                                         L""))->drop();
1612                 }
1613                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1614                 {
1615                         TextDest *dest = new TextDestChat(&client);
1616
1617                         (new GUITextInputMenu(guienv, guiroot, -1,
1618                                         &g_menumgr, dest,
1619                                         L"/"))->drop();
1620                 }
1621                 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1622                 {
1623                         if (!gui_chat_console->isOpenInhibited())
1624                         {
1625                                 // Open up to over half of the screen
1626                                 gui_chat_console->openConsole(0.6);
1627                                 guienv->setFocus(gui_chat_console);
1628                         }
1629                 }
1630                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1631                 {
1632                         if(g_settings->getBool("free_move"))
1633                         {
1634                                 g_settings->set("free_move","false");
1635                                 statustext = L"free_move disabled";
1636                                 statustext_time = 0;
1637                         }
1638                         else
1639                         {
1640                                 g_settings->set("free_move","true");
1641                                 statustext = L"free_move enabled";
1642                                 statustext_time = 0;
1643                                 if(!client.checkPrivilege("fly"))
1644                                         statustext += L" (note: no 'fly' privilege)";
1645                         }
1646                 }
1647                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1648                 {
1649                         if(g_settings->getBool("fast_move"))
1650                         {
1651                                 g_settings->set("fast_move","false");
1652                                 statustext = L"fast_move disabled";
1653                                 statustext_time = 0;
1654                         }
1655                         else
1656                         {
1657                                 g_settings->set("fast_move","true");
1658                                 statustext = L"fast_move enabled";
1659                                 statustext_time = 0;
1660                                 if(!client.checkPrivilege("fast"))
1661                                         statustext += L" (note: no 'fast' privilege)";
1662                         }
1663                 }
1664                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1665                 {
1666                         irr::video::IImage* const image = driver->createScreenShot(); 
1667                         if (image) { 
1668                                 irr::c8 filename[256]; 
1669                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1670                                                  g_settings->get("screenshot_path").c_str(),
1671                                                  device->getTimer()->getRealTime()); 
1672                                 if (driver->writeImageToFile(image, filename)) {
1673                                         std::wstringstream sstr;
1674                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1675                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1676                                         statustext = sstr.str();
1677                                         statustext_time = 0;
1678                                 } else{
1679                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1680                                 }
1681                                 image->drop(); 
1682                         }                        
1683                 }
1684                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1685                 {
1686                         show_hud = !show_hud;
1687                         if(show_hud)
1688                                 statustext = L"HUD shown";
1689                         else
1690                                 statustext = L"HUD hidden";
1691                         statustext_time = 0;
1692                 }
1693                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1694                 {
1695                         show_chat = !show_chat;
1696                         if(show_chat)
1697                                 statustext = L"Chat shown";
1698                         else
1699                                 statustext = L"Chat hidden";
1700                         statustext_time = 0;
1701                 }
1702                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1703                 {
1704                         force_fog_off = !force_fog_off;
1705                         if(force_fog_off)
1706                                 statustext = L"Fog disabled";
1707                         else
1708                                 statustext = L"Fog enabled";
1709                         statustext_time = 0;
1710                 }
1711                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1712                 {
1713                         disable_camera_update = !disable_camera_update;
1714                         if(disable_camera_update)
1715                                 statustext = L"Camera update disabled";
1716                         else
1717                                 statustext = L"Camera update enabled";
1718                         statustext_time = 0;
1719                 }
1720                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1721                 {
1722                         // Initial / 3x toggle: Chat only
1723                         // 1x toggle: Debug text with chat
1724                         // 2x toggle: Debug text with profiler graph
1725                         if(!show_debug)
1726                         {
1727                                 show_debug = true;
1728                                 show_profiler_graph = false;
1729                                 statustext = L"Debug info shown";
1730                                 statustext_time = 0;
1731                         }
1732                         else if(show_profiler_graph)
1733                         {
1734                                 show_debug = false;
1735                                 show_profiler_graph = false;
1736                                 statustext = L"Debug info and profiler graph hidden";
1737                                 statustext_time = 0;
1738                         }
1739                         else
1740                         {
1741                                 show_profiler_graph = true;
1742                                 statustext = L"Profiler graph shown";
1743                                 statustext_time = 0;
1744                         }
1745                 }
1746                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1747                 {
1748                         show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1749
1750                         // FIXME: This updates the profiler with incomplete values
1751                         update_profiler_gui(guitext_profiler, font, text_height,
1752                                         show_profiler, show_profiler_max);
1753
1754                         if(show_profiler != 0)
1755                         {
1756                                 std::wstringstream sstr;
1757                                 sstr<<"Profiler shown (page "<<show_profiler
1758                                         <<" of "<<show_profiler_max<<")";
1759                                 statustext = sstr.str();
1760                                 statustext_time = 0;
1761                         }
1762                         else
1763                         {
1764                                 statustext = L"Profiler hidden";
1765                                 statustext_time = 0;
1766                         }
1767                 }
1768                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1769                 {
1770                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1771                         s16 range_new = range + 10;
1772                         g_settings->set("viewing_range_nodes_min", itos(range_new));
1773                         statustext = narrow_to_wide(
1774                                         "Minimum viewing range changed to "
1775                                         + itos(range_new));
1776                         statustext_time = 0;
1777                 }
1778                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1779                 {
1780                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1781                         s16 range_new = range - 10;
1782                         if(range_new < 0)
1783                                 range_new = range;
1784                         g_settings->set("viewing_range_nodes_min",
1785                                         itos(range_new));
1786                         statustext = narrow_to_wide(
1787                                         "Minimum viewing range changed to "
1788                                         + itos(range_new));
1789                         statustext_time = 0;
1790                 }
1791                 
1792                 // Handle QuicktuneShortcutter
1793                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1794                         quicktune.next();
1795                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1796                         quicktune.prev();
1797                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1798                         quicktune.inc();
1799                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1800                         quicktune.dec();
1801                 {
1802                         std::string msg = quicktune.getMessage();
1803                         if(msg != ""){
1804                                 statustext = narrow_to_wide(msg);
1805                                 statustext_time = 0;
1806                         }
1807                 }
1808
1809                 // Item selection with mouse wheel
1810                 u16 new_playeritem = client.getPlayerItem();
1811                 {
1812                         s32 wheel = input->getMouseWheel();
1813                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1814                                         hotbar_itemcount-1);
1815
1816                         if(wheel < 0)
1817                         {
1818                                 if(new_playeritem < max_item)
1819                                         new_playeritem++;
1820                                 else
1821                                         new_playeritem = 0;
1822                         }
1823                         else if(wheel > 0)
1824                         {
1825                                 if(new_playeritem > 0)
1826                                         new_playeritem--;
1827                                 else
1828                                         new_playeritem = max_item;
1829                         }
1830                 }
1831                 
1832                 // Item selection
1833                 for(u16 i=0; i<10; i++)
1834                 {
1835                         const KeyPress *kp = NumberKey + (i + 1) % 10;
1836                         if(input->wasKeyDown(*kp))
1837                         {
1838                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1839                                 {
1840                                         new_playeritem = i;
1841
1842                                         infostream<<"Selected item: "
1843                                                         <<new_playeritem<<std::endl;
1844                                 }
1845                         }
1846                 }
1847
1848                 // Viewing range selection
1849                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1850                 {
1851                         draw_control.range_all = !draw_control.range_all;
1852                         if(draw_control.range_all)
1853                         {
1854                                 infostream<<"Enabled full viewing range"<<std::endl;
1855                                 statustext = L"Enabled full viewing range";
1856                                 statustext_time = 0;
1857                         }
1858                         else
1859                         {
1860                                 infostream<<"Disabled full viewing range"<<std::endl;
1861                                 statustext = L"Disabled full viewing range";
1862                                 statustext_time = 0;
1863                         }
1864                 }
1865
1866                 // Print debug stacks
1867                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1868                 {
1869                         dstream<<"-----------------------------------------"
1870                                         <<std::endl;
1871                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1872                         dstream<<"-----------------------------------------"
1873                                         <<std::endl;
1874                         debug_stacks_print();
1875                 }
1876
1877                 /*
1878                         Mouse and camera control
1879                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1880                 */
1881                 
1882                 float turn_amount = 0;
1883                 if((device->isWindowActive() && noMenuActive()) || random_input)
1884                 {
1885                         if(!random_input)
1886                         {
1887                                 // Mac OSX gets upset if this is set every frame
1888                                 if(device->getCursorControl()->isVisible())
1889                                         device->getCursorControl()->setVisible(false);
1890                         }
1891
1892                         if(first_loop_after_window_activation){
1893                                 //infostream<<"window active, first loop"<<std::endl;
1894                                 first_loop_after_window_activation = false;
1895                         }
1896                         else{
1897                                 s32 dx = input->getMousePos().X - displaycenter.X;
1898                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1899                                 if(invert_mouse)
1900                                         dy = -dy;
1901                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1902                                 
1903                                 /*const float keyspeed = 500;
1904                                 if(input->isKeyDown(irr::KEY_UP))
1905                                         dy -= dtime * keyspeed;
1906                                 if(input->isKeyDown(irr::KEY_DOWN))
1907                                         dy += dtime * keyspeed;
1908                                 if(input->isKeyDown(irr::KEY_LEFT))
1909                                         dx -= dtime * keyspeed;
1910                                 if(input->isKeyDown(irr::KEY_RIGHT))
1911                                         dx += dtime * keyspeed;*/
1912                                 
1913                                 float d = 0.2;
1914                                 camera_yaw -= dx*d;
1915                                 camera_pitch += dy*d;
1916                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1917                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1918                                 
1919                                 turn_amount = v2f(dx, dy).getLength() * d;
1920                         }
1921                         input->setMousePos(displaycenter.X, displaycenter.Y);
1922                 }
1923                 else{
1924                         // Mac OSX gets upset if this is set every frame
1925                         if(device->getCursorControl()->isVisible() == false)
1926                                 device->getCursorControl()->setVisible(true);
1927
1928                         //infostream<<"window inactive"<<std::endl;
1929                         first_loop_after_window_activation = true;
1930                 }
1931                 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1932                 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1933
1934                 /*
1935                         Player speed control
1936                 */
1937                 {
1938                         /*bool a_up,
1939                         bool a_down,
1940                         bool a_left,
1941                         bool a_right,
1942                         bool a_jump,
1943                         bool a_superspeed,
1944                         bool a_sneak,
1945                         bool a_LMB,
1946                         bool a_RMB,
1947                         float a_pitch,
1948                         float a_yaw*/
1949                         PlayerControl control(
1950                                 input->isKeyDown(getKeySetting("keymap_forward")),
1951                                 input->isKeyDown(getKeySetting("keymap_backward")),
1952                                 input->isKeyDown(getKeySetting("keymap_left")),
1953                                 input->isKeyDown(getKeySetting("keymap_right")),
1954                                 input->isKeyDown(getKeySetting("keymap_jump")),
1955                                 input->isKeyDown(getKeySetting("keymap_special1")),
1956                                 input->isKeyDown(getKeySetting("keymap_sneak")),
1957                                 input->getLeftState(),
1958                                 input->getRightState(),
1959                                 camera_pitch,
1960                                 camera_yaw
1961                         );
1962                         client.setPlayerControl(control);
1963                         u32 keyPressed=
1964                         1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
1965                         2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
1966                         4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
1967                         8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
1968                         16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
1969                         32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
1970                         64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
1971                         128*(int)input->getLeftState()+
1972                         256*(int)input->getRightState();
1973                         LocalPlayer* player = client.getEnv().getLocalPlayer();
1974                         player->keyPressed=keyPressed;
1975                 }
1976                 
1977                 /*
1978                         Run server
1979                 */
1980
1981                 if(server != NULL)
1982                 {
1983                         //TimeTaker timer("server->step(dtime)");
1984                         server->step(dtime);
1985                 }
1986
1987                 /*
1988                         Process environment
1989                 */
1990                 
1991                 {
1992                         //TimeTaker timer("client.step(dtime)");
1993                         client.step(dtime);
1994                         //client.step(dtime_avg1);
1995                 }
1996
1997                 {
1998                         // Read client events
1999                         for(;;)
2000                         {
2001                                 ClientEvent event = client.getClientEvent();
2002                                 if(event.type == CE_NONE)
2003                                 {
2004                                         break;
2005                                 }
2006                                 else if(event.type == CE_PLAYER_DAMAGE)
2007                                 {
2008                                         //u16 damage = event.player_damage.amount;
2009                                         //infostream<<"Player damage: "<<damage<<std::endl;
2010                                         damage_flash_timer = 0.05;
2011                                         if(event.player_damage.amount >= 2){
2012                                                 damage_flash_timer += 0.05 * event.player_damage.amount;
2013                                         }
2014                                 }
2015                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
2016                                 {
2017                                         camera_yaw = event.player_force_move.yaw;
2018                                         camera_pitch = event.player_force_move.pitch;
2019                                 }
2020                                 else if(event.type == CE_DEATHSCREEN)
2021                                 {
2022                                         if(respawn_menu_active)
2023                                                 continue;
2024
2025                                         /*bool set_camera_point_target =
2026                                                         event.deathscreen.set_camera_point_target;
2027                                         v3f camera_point_target;
2028                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
2029                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
2030                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2031                                         MainRespawnInitiator *respawner =
2032                                                         new MainRespawnInitiator(
2033                                                                         &respawn_menu_active, &client);
2034                                         GUIDeathScreen *menu =
2035                                                         new GUIDeathScreen(guienv, guiroot, -1, 
2036                                                                 &g_menumgr, respawner);
2037                                         menu->drop();
2038                                         
2039                                         chat_backend.addMessage(L"", L"You died.");
2040
2041                                         /* Handle visualization */
2042
2043                                         damage_flash_timer = 0;
2044
2045                                         /*LocalPlayer* player = client.getLocalPlayer();
2046                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
2047                                         camera.update(player, busytime, screensize);*/
2048                                 }
2049                                 else if(event.type == CE_TEXTURES_UPDATED)
2050                                 {
2051                                         update_wielded_item_trigger = true;
2052                                 }
2053                         }
2054                 }
2055                 
2056                 //TimeTaker //timer2("//timer2");
2057
2058                 /*
2059                         For interaction purposes, get info about the held item
2060                         - What item is it?
2061                         - Is it a usable item?
2062                         - Can it point to liquids?
2063                 */
2064                 ItemStack playeritem;
2065                 bool playeritem_usable = false;
2066                 bool playeritem_liquids_pointable = false;
2067                 {
2068                         InventoryList *mlist = local_inventory.getList("main");
2069                         if(mlist != NULL)
2070                         {
2071                                 playeritem = mlist->getItem(client.getPlayerItem());
2072                                 playeritem_usable = playeritem.getDefinition(itemdef).usable;
2073                                 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
2074                         }
2075                 }
2076                 ToolCapabilities playeritem_toolcap =
2077                                 playeritem.getToolCapabilities(itemdef);
2078                 
2079                 /*
2080                         Update camera
2081                 */
2082
2083                 LocalPlayer* player = client.getEnv().getLocalPlayer();
2084                 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2085                 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2086                 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2087                 camera.update(player, busytime, screensize, tool_reload_ratio);
2088                 camera.step(dtime);
2089
2090                 v3f player_position = player->getPosition();
2091                 v3f camera_position = camera.getPosition();
2092                 v3f camera_direction = camera.getDirection();
2093                 f32 camera_fov = camera.getFovMax();
2094                 
2095                 if(!disable_camera_update){
2096                         client.getEnv().getClientMap().updateCamera(camera_position,
2097                                 camera_direction, camera_fov);
2098                 }
2099                 
2100                 // Update sound listener
2101                 sound->updateListener(camera.getCameraNode()->getPosition(),
2102                                 v3f(0,0,0), // velocity
2103                                 camera.getDirection(),
2104                                 camera.getCameraNode()->getUpVector());
2105                 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2106
2107                 /*
2108                         Update sound maker
2109                 */
2110                 {
2111                         soundmaker.step(dtime);
2112                         
2113                         ClientMap &map = client.getEnv().getClientMap();
2114                         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2115                         soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2116                 }
2117
2118                 /*
2119                         Calculate what block is the crosshair pointing to
2120                 */
2121                 
2122                 //u32 t1 = device->getTimer()->getRealTime();
2123                 
2124                 f32 d = 4; // max. distance
2125                 core::line3d<f32> shootline(camera_position,
2126                                 camera_position + camera_direction * BS * (d+1));
2127
2128                 ClientActiveObject *selected_object = NULL;
2129
2130                 PointedThing pointed = getPointedThing(
2131                                 // input
2132                                 &client, player_position, camera_direction,
2133                                 camera_position, shootline, d,
2134                                 playeritem_liquids_pointable, !ldown_for_dig,
2135                                 // output
2136                                 hilightboxes,
2137                                 selected_object);
2138
2139                 if(pointed != pointed_old)
2140                 {
2141                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2142                         //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2143                 }
2144
2145                 /*
2146                         Stop digging when
2147                         - releasing left mouse button
2148                         - pointing away from node
2149                 */
2150                 if(digging)
2151                 {
2152                         if(input->getLeftReleased())
2153                         {
2154                                 infostream<<"Left button released"
2155                                         <<" (stopped digging)"<<std::endl;
2156                                 digging = false;
2157                         }
2158                         else if(pointed != pointed_old)
2159                         {
2160                                 if (pointed.type == POINTEDTHING_NODE
2161                                         && pointed_old.type == POINTEDTHING_NODE
2162                                         && pointed.node_undersurface == pointed_old.node_undersurface)
2163                                 {
2164                                         // Still pointing to the same node,
2165                                         // but a different face. Don't reset.
2166                                 }
2167                                 else
2168                                 {
2169                                         infostream<<"Pointing away from node"
2170                                                 <<" (stopped digging)"<<std::endl;
2171                                         digging = false;
2172                                 }
2173                         }
2174                         if(!digging)
2175                         {
2176                                 client.interact(1, pointed_old);
2177                                 client.setCrack(-1, v3s16(0,0,0));
2178                                 dig_time = 0.0;
2179                         }
2180                 }
2181                 if(!digging && ldown_for_dig && !input->getLeftState())
2182                 {
2183                         ldown_for_dig = false;
2184                 }
2185
2186                 bool left_punch = false;
2187                 soundmaker.m_player_leftpunch_sound.name = "";
2188
2189                 if(playeritem_usable && input->getLeftState())
2190                 {
2191                         if(input->getLeftClicked())
2192                                 client.interact(4, pointed);
2193                 }
2194                 else if(pointed.type == POINTEDTHING_NODE)
2195                 {
2196                         v3s16 nodepos = pointed.node_undersurface;
2197                         v3s16 neighbourpos = pointed.node_abovesurface;
2198
2199                         /*
2200                                 Check information text of node
2201                         */
2202                         
2203                         ClientMap &map = client.getEnv().getClientMap();
2204                         NodeMetadata *meta = map.getNodeMetadata(nodepos);
2205                         if(meta){
2206                                 infotext = narrow_to_wide(meta->getString("infotext"));
2207                         } else {
2208                                 MapNode n = map.getNode(nodepos);
2209                                 if(nodedef->get(n).tiledef[0].name == "unknown_block.png"){
2210                                         infotext = L"Unknown node: ";
2211                                         infotext += narrow_to_wide(nodedef->get(n).name);
2212                                 }
2213                         }
2214                         
2215                         // We can't actually know, but assume the sound of right-clicking
2216                         // to be the sound of placing a node
2217                         soundmaker.m_player_rightpunch_sound.gain = 0.5;
2218                         soundmaker.m_player_rightpunch_sound.name = "default_place_node";
2219                         
2220                         /*
2221                                 Handle digging
2222                         */
2223                         
2224                         if(nodig_delay_timer <= 0.0 && input->getLeftState())
2225                         {
2226                                 if(!digging)
2227                                 {
2228                                         infostream<<"Started digging"<<std::endl;
2229                                         client.interact(0, pointed);
2230                                         digging = true;
2231                                         ldown_for_dig = true;
2232                                 }
2233                                 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2234                                 
2235                                 // NOTE: Similar piece of code exists on the server side for
2236                                 // cheat detection.
2237                                 // Get digging parameters
2238                                 DigParams params = getDigParams(nodedef->get(n).groups,
2239                                                 &playeritem_toolcap);
2240                                 // If can't dig, try hand
2241                                 if(!params.diggable){
2242                                         const ItemDefinition &hand = itemdef->get("");
2243                                         const ToolCapabilities *tp = hand.tool_capabilities;
2244                                         if(tp)
2245                                                 params = getDigParams(nodedef->get(n).groups, tp);
2246                                 }
2247                                 
2248                                 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2249                                 if(sound_dig.exists()){
2250                                         if(sound_dig.name == "__group"){
2251                                                 if(params.main_group != ""){
2252                                                         soundmaker.m_player_leftpunch_sound.gain = 0.5;
2253                                                         soundmaker.m_player_leftpunch_sound.name =
2254                                                                         std::string("default_dig_") +
2255                                                                                         params.main_group;
2256                                                 }
2257                                         } else{
2258                                                 soundmaker.m_player_leftpunch_sound = sound_dig;
2259                                         }
2260                                 }
2261
2262                                 float dig_time_complete = 0.0;
2263
2264                                 if(params.diggable == false)
2265                                 {
2266                                         // I guess nobody will wait for this long
2267                                         dig_time_complete = 10000000.0;
2268                                 }
2269                                 else
2270                                 {
2271                                         dig_time_complete = params.time;
2272                                 }
2273
2274                                 if(dig_time_complete >= 0.001)
2275                                 {
2276                                         dig_index = (u16)((float)crack_animation_length
2277                                                         * dig_time/dig_time_complete);
2278                                 }
2279                                 // This is for torches
2280                                 else
2281                                 {
2282                                         dig_index = crack_animation_length;
2283                                 }
2284
2285                                 // Don't show cracks if not diggable
2286                                 if(dig_time_complete >= 100000.0)
2287                                 {
2288                                 }
2289                                 else if(dig_index < crack_animation_length)
2290                                 {
2291                                         //TimeTaker timer("client.setTempMod");
2292                                         //infostream<<"dig_index="<<dig_index<<std::endl;
2293                                         client.setCrack(dig_index, nodepos);
2294                                 }
2295                                 else
2296                                 {
2297                                         infostream<<"Digging completed"<<std::endl;
2298                                         client.interact(2, pointed);
2299                                         client.setCrack(-1, v3s16(0,0,0));
2300                                         MapNode wasnode = map.getNode(nodepos);
2301                                         client.removeNode(nodepos);
2302
2303                                         dig_time = 0;
2304                                         digging = false;
2305
2306                                         nodig_delay_timer = dig_time_complete
2307                                                         / (float)crack_animation_length;
2308
2309                                         // We don't want a corresponding delay to
2310                                         // very time consuming nodes
2311                                         if(nodig_delay_timer > 0.3)
2312                                                 nodig_delay_timer = 0.3;
2313                                         // We want a slight delay to very little
2314                                         // time consuming nodes
2315                                         float mindelay = 0.15;
2316                                         if(nodig_delay_timer < mindelay)
2317                                                 nodig_delay_timer = mindelay;
2318                                         
2319                                         // Send event to trigger sound
2320                                         MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2321                                         gamedef->event()->put(e);
2322                                 }
2323
2324                                 dig_time += dtime;
2325
2326                                 camera.setDigging(0);  // left click animation
2327                         }
2328
2329                         if(input->getRightClicked())
2330                         {
2331                                 infostream<<"Ground right-clicked"<<std::endl;
2332                                 
2333                                 // Sign special case, at least until formspec is properly implemented.
2334                                 // Deprecated?
2335                                 if(meta && meta->getString("formspec") == "hack:sign_text_input" && !random_input)
2336                                 {
2337                                         infostream<<"Launching metadata text input"<<std::endl;
2338                                         
2339                                         // Get a new text for it
2340
2341                                         TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2342
2343                                         std::wstring wtext = narrow_to_wide(meta->getString("text"));
2344
2345                                         (new GUITextInputMenu(guienv, guiroot, -1,
2346                                                         &g_menumgr, dest,
2347                                                         wtext))->drop();
2348                                 }
2349                                 // If metadata provides an inventory view, activate it
2350                                 else if(meta && meta->getString("formspec") != "" && !random_input)
2351                                 {
2352                                         infostream<<"Launching custom inventory view"<<std::endl;
2353
2354                                         InventoryLocation inventoryloc;
2355                                         inventoryloc.setNodeMeta(nodepos);
2356                                         
2357                                         /* Create menu */
2358
2359                                         GUIFormSpecMenu *menu =
2360                                                 new GUIFormSpecMenu(device, guiroot, -1,
2361                                                         &g_menumgr,
2362                                                         &client, gamedef);
2363                                         menu->setFormSpec(meta->getString("formspec"),
2364                                                         inventoryloc);
2365                                         menu->setFormSource(new NodeMetadataFormSource(
2366                                                         &client.getEnv().getClientMap(), nodepos));
2367                                         menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2368                                         menu->drop();
2369                                 }
2370                                 // Otherwise report right click to server
2371                                 else
2372                                 {
2373                                         // Report to server
2374                                         client.interact(3, pointed);
2375                                         camera.setDigging(1);  // right click animation
2376                                         
2377                                         // If the wielded item has node placement prediction,
2378                                         // make that happen
2379                                         const ItemDefinition &def =
2380                                                         playeritem.getDefinition(itemdef);
2381                                         if(def.node_placement_prediction != "")
2382                                         do{ // breakable
2383                                                 verbosestream<<"Node placement prediction for "
2384                                                                 <<playeritem.name<<" is "
2385                                                                 <<def.node_placement_prediction<<std::endl;
2386                                                 v3s16 p = neighbourpos;
2387                                                 // Place inside node itself if buildable_to
2388                                                 try{
2389                                                         MapNode n_under = map.getNode(nodepos);
2390                                                         if(nodedef->get(n_under).buildable_to)
2391                                                                 p = nodepos;
2392                                                 }catch(InvalidPositionException &e){}
2393                                                 // Find id of predicted node
2394                                                 content_t id;
2395                                                 bool found =
2396                                                         nodedef->getId(def.node_placement_prediction, id);
2397                                                 if(!found){
2398                                                         errorstream<<"Node placement prediction failed for "
2399                                                                         <<playeritem.name<<" (places "
2400                                                                         <<def.node_placement_prediction
2401                                                                         <<") - Name not known"<<std::endl;
2402                                                         break;
2403                                                 }
2404                                                 MapNode n(id);
2405                                                 try{
2406                                                         // This triggers the required mesh update too
2407                                                         client.addNode(p, n);
2408                                                 }catch(InvalidPositionException &e){
2409                                                         errorstream<<"Node placement prediction failed for "
2410                                                                         <<playeritem.name<<" (places "
2411                                                                         <<def.node_placement_prediction
2412                                                                         <<") - Position not loaded"<<std::endl;
2413                                                 }
2414                                         }while(0);
2415                                 }
2416                         }
2417                 }
2418                 else if(pointed.type == POINTEDTHING_OBJECT)
2419                 {
2420                         infotext = narrow_to_wide(selected_object->infoText());
2421
2422                         if(infotext == L"" && show_debug){
2423                                 infotext = narrow_to_wide(selected_object->debugInfoText());
2424                         }
2425
2426                         //if(input->getLeftClicked())
2427                         if(input->getLeftState())
2428                         {
2429                                 bool do_punch = false;
2430                                 bool do_punch_damage = false;
2431                                 if(object_hit_delay_timer <= 0.0){
2432                                         do_punch = true;
2433                                         do_punch_damage = true;
2434                                         object_hit_delay_timer = object_hit_delay;
2435                                 }
2436                                 if(input->getLeftClicked()){
2437                                         do_punch = true;
2438                                 }
2439                                 if(do_punch){
2440                                         infostream<<"Left-clicked object"<<std::endl;
2441                                         left_punch = true;
2442                                 }
2443                                 if(do_punch_damage){
2444                                         // Report direct punch
2445                                         v3f objpos = selected_object->getPosition();
2446                                         v3f dir = (objpos - player_position).normalize();
2447                                         
2448                                         bool disable_send = selected_object->directReportPunch(
2449                                                         dir, &playeritem, time_from_last_punch);
2450                                         time_from_last_punch = 0;
2451                                         if(!disable_send)
2452                                                 client.interact(0, pointed);
2453                                 }
2454                         }
2455                         else if(input->getRightClicked())
2456                         {
2457                                 infostream<<"Right-clicked object"<<std::endl;
2458                                 client.interact(3, pointed);  // place
2459                         }
2460                 }
2461                 else if(input->getLeftState())
2462                 {
2463                         // When button is held down in air, show continuous animation
2464                         left_punch = true;
2465                 }
2466
2467                 pointed_old = pointed;
2468                 
2469                 if(left_punch || input->getLeftClicked())
2470                 {
2471                         camera.setDigging(0); // left click animation
2472                 }
2473
2474                 input->resetLeftClicked();
2475                 input->resetRightClicked();
2476
2477                 input->resetLeftReleased();
2478                 input->resetRightReleased();
2479                 
2480                 /*
2481                         Calculate stuff for drawing
2482                 */
2483
2484                 /*
2485                         Fog range
2486                 */
2487         
2488                 if(farmesh)
2489                 {
2490                         fog_range = BS*farmesh_range;
2491                 }
2492                 else
2493                 {
2494                         fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2495                         fog_range *= 0.9;
2496                         if(draw_control.range_all)
2497                                 fog_range = 100000*BS;
2498                 }
2499
2500                 /*
2501                         Calculate general brightness
2502                 */
2503                 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2504                 float time_brightness = (float)decode_light(
2505                                 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2506                 float direct_brightness = 0;
2507                 bool sunlight_seen = false;
2508                 if(g_settings->getBool("free_move")){
2509                         direct_brightness = time_brightness;
2510                         sunlight_seen = true;
2511                 } else {
2512                         ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2513                         float old_brightness = sky->getBrightness();
2514                         direct_brightness = (float)client.getEnv().getClientMap()
2515                                         .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2516                                         daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2517                                         / 255.0;
2518                 }
2519                 
2520                 time_of_day = client.getEnv().getTimeOfDayF();
2521                 float maxsm = 0.05;
2522                 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2523                                 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2524                                 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2525                         time_of_day_smooth = time_of_day;
2526                 float todsm = 0.05;
2527                 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2528                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2529                                         + (time_of_day+1.0) * todsm;
2530                 else
2531                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2532                                         + time_of_day * todsm;
2533                         
2534                 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2535                                 sunlight_seen);
2536                 
2537                 float brightness = sky->getBrightness();
2538                 video::SColor bgcolor = sky->getBgColor();
2539                 video::SColor skycolor = sky->getSkyColor();
2540
2541                 /*
2542                         Update clouds
2543                 */
2544                 if(clouds){
2545                         if(sky->getCloudsVisible()){
2546                                 clouds->setVisible(true);
2547                                 clouds->step(dtime);
2548                                 clouds->update(v2f(player_position.X, player_position.Z),
2549                                                 sky->getCloudColor());
2550                         } else{
2551                                 clouds->setVisible(false);
2552                         }
2553                 }
2554                 
2555                 /*
2556                         Update farmesh
2557                 */
2558                 if(farmesh)
2559                 {
2560                         farmesh_range = draw_control.wanted_range * 10;
2561                         if(draw_control.range_all && farmesh_range < 500)
2562                                 farmesh_range = 500;
2563                         if(farmesh_range > 1000)
2564                                 farmesh_range = 1000;
2565
2566                         farmesh->step(dtime);
2567                         farmesh->update(v2f(player_position.X, player_position.Z),
2568                                         brightness, farmesh_range);
2569                 }
2570                 
2571                 /*
2572                         Fog
2573                 */
2574                 
2575                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2576                 {
2577                         driver->setFog(
2578                                 bgcolor,
2579                                 video::EFT_FOG_LINEAR,
2580                                 fog_range*0.4,
2581                                 fog_range*1.0,
2582                                 0.01,
2583                                 false, // pixel fog
2584                                 false // range fog
2585                         );
2586                 }
2587                 else
2588                 {
2589                         driver->setFog(
2590                                 bgcolor,
2591                                 video::EFT_FOG_LINEAR,
2592                                 100000*BS,
2593                                 110000*BS,
2594                                 0.01,
2595                                 false, // pixel fog
2596                                 false // range fog
2597                         );
2598                 }
2599
2600                 /*
2601                         Update gui stuff (0ms)
2602                 */
2603
2604                 //TimeTaker guiupdatetimer("Gui updating");
2605                 
2606                 const char program_name_and_version[] =
2607                         "Minetest-c55 " VERSION_STRING;
2608
2609                 if(show_debug)
2610                 {
2611                         static float drawtime_avg = 0;
2612                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2613                         /*static float beginscenetime_avg = 0;
2614                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2615                         static float scenetime_avg = 0;
2616                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2617                         static float endscenetime_avg = 0;
2618                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2619                         
2620                         char temptext[300];
2621                         snprintf(temptext, 300, "%s ("
2622                                         "R: range_all=%i"
2623                                         ")"
2624                                         " drawtime=%.0f, dtime_jitter = % .1f %%"
2625                                         ", v_range = %.1f, RTT = %.3f",
2626                                         program_name_and_version,
2627                                         draw_control.range_all,
2628                                         drawtime_avg,
2629                                         dtime_jitter1_max_fraction * 100.0,
2630                                         draw_control.wanted_range,
2631                                         client.getRTT()
2632                                         );
2633                         
2634                         guitext->setText(narrow_to_wide(temptext).c_str());
2635                         guitext->setVisible(true);
2636                 }
2637                 else if(show_hud || show_chat)
2638                 {
2639                         guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2640                         guitext->setVisible(true);
2641                 }
2642                 else
2643                 {
2644                         guitext->setVisible(false);
2645                 }
2646                 
2647                 if(show_debug)
2648                 {
2649                         char temptext[300];
2650                         snprintf(temptext, 300,
2651                                         "(% .1f, % .1f, % .1f)"
2652                                         " (yaw = %.1f) (seed = %lli)",
2653                                         player_position.X/BS,
2654                                         player_position.Y/BS,
2655                                         player_position.Z/BS,
2656                                         wrapDegrees_0_360(camera_yaw),
2657                                         client.getMapSeed());
2658
2659                         guitext2->setText(narrow_to_wide(temptext).c_str());
2660                         guitext2->setVisible(true);
2661                 }
2662                 else
2663                 {
2664                         guitext2->setVisible(false);
2665                 }
2666                 
2667                 {
2668                         guitext_info->setText(infotext.c_str());
2669                         guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2670                 }
2671
2672                 {
2673                         float statustext_time_max = 1.5;
2674                         if(!statustext.empty())
2675                         {
2676                                 statustext_time += dtime;
2677                                 if(statustext_time >= statustext_time_max)
2678                                 {
2679                                         statustext = L"";
2680                                         statustext_time = 0;
2681                                 }
2682                         }
2683                         guitext_status->setText(statustext.c_str());
2684                         guitext_status->setVisible(!statustext.empty());
2685
2686                         if(!statustext.empty())
2687                         {
2688                                 s32 status_y = screensize.Y - 130;
2689                                 core::rect<s32> rect(
2690                                                 10,
2691                                                 status_y - guitext_status->getTextHeight(),
2692                                                 screensize.X - 10,
2693                                                 status_y
2694                                 );
2695                                 guitext_status->setRelativePosition(rect);
2696
2697                                 // Fade out
2698                                 video::SColor initial_color(255,0,0,0);
2699                                 if(guienv->getSkin())
2700                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2701                                 video::SColor final_color = initial_color;
2702                                 final_color.setAlpha(0);
2703                                 video::SColor fade_color =
2704                                         initial_color.getInterpolated_quadratic(
2705                                                 initial_color,
2706                                                 final_color,
2707                                                 pow(statustext_time / (float)statustext_time_max, 2.0f));
2708                                 guitext_status->setOverrideColor(fade_color);
2709                                 guitext_status->enableOverrideColor(true);
2710                         }
2711                 }
2712                 
2713                 /*
2714                         Get chat messages from client
2715                 */
2716                 {
2717                         // Get new messages from error log buffer
2718                         while(!chat_log_error_buf.empty())
2719                         {
2720                                 chat_backend.addMessage(L"", narrow_to_wide(
2721                                                 chat_log_error_buf.get()));
2722                         }
2723                         // Get new messages from client
2724                         std::wstring message;
2725                         while(client.getChatMessage(message))
2726                         {
2727                                 chat_backend.addUnparsedMessage(message);
2728                         }
2729                         // Remove old messages
2730                         chat_backend.step(dtime);
2731
2732                         // Display all messages in a static text element
2733                         u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2734                         std::wstring recent_chat = chat_backend.getRecentChat();
2735                         guitext_chat->setText(recent_chat.c_str());
2736
2737                         // Update gui element size and position
2738                         s32 chat_y = 5+(text_height+5);
2739                         if(show_debug)
2740                                 chat_y += (text_height+5);
2741                         core::rect<s32> rect(
2742                                 10,
2743                                 chat_y,
2744                                 screensize.X - 10,
2745                                 chat_y + guitext_chat->getTextHeight()
2746                         );
2747                         guitext_chat->setRelativePosition(rect);
2748
2749                         // Don't show chat if disabled or empty or profiler is enabled
2750                         guitext_chat->setVisible(show_chat && recent_chat_count != 0
2751                                         && !show_profiler);
2752                 }
2753
2754                 /*
2755                         Inventory
2756                 */
2757                 
2758                 if(client.getPlayerItem() != new_playeritem)
2759                 {
2760                         client.selectPlayerItem(new_playeritem);
2761                 }
2762                 if(client.getLocalInventoryUpdated())
2763                 {
2764                         //infostream<<"Updating local inventory"<<std::endl;
2765                         client.getLocalInventory(local_inventory);
2766                         
2767                         update_wielded_item_trigger = true;
2768                 }
2769                 if(update_wielded_item_trigger)
2770                 {
2771                         update_wielded_item_trigger = false;
2772                         // Update wielded tool
2773                         InventoryList *mlist = local_inventory.getList("main");
2774                         ItemStack item;
2775                         if(mlist != NULL)
2776                                 item = mlist->getItem(client.getPlayerItem());
2777                         camera.wield(item);
2778                 }
2779
2780                 /*
2781                         Update block draw list every 200ms or when camera direction has
2782                         changed much
2783                 */
2784                 update_draw_list_timer += dtime;
2785                 if(update_draw_list_timer >= 0.2 ||
2786                                 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
2787                         update_draw_list_timer = 0;
2788                         client.getEnv().getClientMap().updateDrawList(driver);
2789                         update_draw_list_last_cam_dir = camera_direction;
2790                 }
2791
2792                 /*
2793                         Drawing begins
2794                 */
2795
2796                 TimeTaker tt_draw("mainloop: draw");
2797
2798                 
2799                 {
2800                         TimeTaker timer("beginScene");
2801                         //driver->beginScene(false, true, bgcolor);
2802                         //driver->beginScene(true, true, bgcolor);
2803                         driver->beginScene(true, true, skycolor);
2804                         beginscenetime = timer.stop(true);
2805                 }
2806                 
2807                 //timer3.stop();
2808         
2809                 //infostream<<"smgr->drawAll()"<<std::endl;
2810                 {
2811                         TimeTaker timer("smgr");
2812                         smgr->drawAll();
2813                         
2814                         if(g_settings->getBool("anaglyph"))
2815                         {
2816                                 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
2817                                 irr::core::vector3df oldTarget   = camera.getCameraNode()->getTarget();
2818
2819                                 irr::core::matrix4 startMatrix   = camera.getCameraNode()->getAbsoluteTransformation();
2820
2821                                 irr::core::vector3df focusPoint  = (camera.getCameraNode()->getTarget() -
2822                                                                                  camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
2823                                                                                  camera.getCameraNode()->getAbsolutePosition() ;
2824
2825                                 //Left eye...
2826                                 irr::core::vector3df leftEye;
2827                                 irr::core::matrix4   leftMove;
2828
2829                                 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
2830                                 leftEye=(startMatrix*leftMove).getTranslation();
2831
2832                                 //clear the depth buffer, and color
2833                                 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
2834
2835                                 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
2836                                 driver->getOverrideMaterial().EnableFlags  = irr::video::EMF_COLOR_MASK;
2837                                 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX + 
2838                                                                                                                          irr::scene::ESNRP_SOLID +
2839                                                                                                                          irr::scene::ESNRP_TRANSPARENT +
2840                                                                                                                          irr::scene::ESNRP_TRANSPARENT_EFFECT +
2841                                                                                                                          irr::scene::ESNRP_SHADOW;
2842
2843                                 camera.getCameraNode()->setPosition( leftEye );
2844                                 camera.getCameraNode()->setTarget( focusPoint );
2845
2846                                 smgr->drawAll(); // 'smgr->drawAll();' may go here
2847
2848
2849                                 //Right eye...
2850                                 irr::core::vector3df rightEye;
2851                                 irr::core::matrix4   rightMove;
2852
2853                                 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
2854                                 rightEye=(startMatrix*rightMove).getTranslation();
2855
2856                                 //clear the depth buffer
2857                                 driver->clearZBuffer();
2858
2859                                 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
2860                                 driver->getOverrideMaterial().EnableFlags  = irr::video::EMF_COLOR_MASK;
2861                                 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
2862                                                                                                                          irr::scene::ESNRP_SOLID +
2863                                                                                                                          irr::scene::ESNRP_TRANSPARENT +
2864                                                                                                                          irr::scene::ESNRP_TRANSPARENT_EFFECT +
2865                                                                                                                          irr::scene::ESNRP_SHADOW;
2866
2867                                 camera.getCameraNode()->setPosition( rightEye );
2868                                 camera.getCameraNode()->setTarget( focusPoint );
2869
2870                                 smgr->drawAll(); // 'smgr->drawAll();' may go here
2871
2872
2873                                 //driver->endScene();
2874
2875                                 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
2876                                 driver->getOverrideMaterial().EnableFlags=0;
2877                                 driver->getOverrideMaterial().EnablePasses=0;
2878
2879                                 camera.getCameraNode()->setPosition( oldPosition );
2880                                 camera.getCameraNode()->setTarget( oldTarget );
2881                         }
2882
2883                         scenetime = timer.stop(true);
2884                 }
2885                 
2886                 {
2887                 //TimeTaker timer9("auxiliary drawings");
2888                 // 0ms
2889                 
2890                 //timer9.stop();
2891                 //TimeTaker //timer10("//timer10");
2892                 
2893                 video::SMaterial m;
2894                 //m.Thickness = 10;
2895                 m.Thickness = 3;
2896                 m.Lighting = false;
2897                 driver->setMaterial(m);
2898
2899                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2900
2901                 if(show_hud)
2902                 {
2903                         for(std::vector<aabb3f>::const_iterator
2904                                         i = hilightboxes.begin();
2905                                         i != hilightboxes.end(); i++)
2906                         {
2907                                 /*infostream<<"hilightbox min="
2908                                                 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2909                                                 <<" max="
2910                                                 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2911                                                 <<std::endl;*/
2912                                 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2913                         }
2914                 }
2915
2916                 /*
2917                         Wielded tool
2918                 */
2919                 if(show_hud)
2920                 {
2921                         // Warning: This clears the Z buffer.
2922                         camera.drawWieldedTool();
2923                 }
2924
2925                 /*
2926                         Post effects
2927                 */
2928                 {
2929                         client.getEnv().getClientMap().renderPostFx();
2930                 }
2931
2932                 /*
2933                         Profiler graph
2934                 */
2935                 if(show_profiler_graph)
2936                 {
2937                         graph.draw(10, screensize.Y - 10, driver, font);
2938                 }
2939
2940                 /*
2941                         Draw crosshair
2942                 */
2943                 if(show_hud)
2944                 {
2945                         driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2946                                         displaycenter + core::vector2d<s32>(10,0),
2947                                         video::SColor(255,255,255,255));
2948                         driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2949                                         displaycenter + core::vector2d<s32>(0,10),
2950                                         video::SColor(255,255,255,255));
2951                 }
2952
2953                 } // timer
2954
2955                 //timer10.stop();
2956                 //TimeTaker //timer11("//timer11");
2957
2958                 /*
2959                         Draw gui
2960                 */
2961                 // 0-1ms
2962                 guienv->drawAll();
2963
2964                 /*
2965                         Draw hotbar
2966                 */
2967                 if(show_hud)
2968                 {
2969                         draw_hotbar(driver, font, gamedef,
2970                                         v2s32(displaycenter.X, screensize.Y),
2971                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2972                                         client.getHP(), client.getPlayerItem());
2973                 }
2974
2975                 /*
2976                         Damage flash
2977                 */
2978                 if(damage_flash_timer > 0.0)
2979                 {
2980                         damage_flash_timer -= dtime;
2981                         
2982                         video::SColor color(128,255,0,0);
2983                         driver->draw2DRectangle(color,
2984                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2985                                         NULL);
2986                 }
2987
2988                 /*
2989                         End scene
2990                 */
2991                 {
2992                         TimeTaker timer("endScene");
2993                         endSceneX(driver);
2994                         endscenetime = timer.stop(true);
2995                 }
2996
2997                 drawtime = tt_draw.stop(true);
2998                 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
2999
3000                 /*
3001                         End of drawing
3002                 */
3003
3004                 static s16 lastFPS = 0;
3005                 //u16 fps = driver->getFPS();
3006                 u16 fps = (1.0/dtime_avg1);
3007
3008                 if (lastFPS != fps)
3009                 {
3010                         core::stringw str = L"Minetest [";
3011                         str += driver->getName();
3012                         str += "] FPS=";
3013                         str += fps;
3014
3015                         device->setWindowCaption(str.c_str());
3016                         lastFPS = fps;
3017                 }
3018
3019                 /*
3020                         Log times and stuff for visualization
3021                 */
3022                 Profiler::GraphValues values;
3023                 g_profiler->graphGet(values);
3024                 graph.put(values);
3025         }
3026
3027         /*
3028                 Drop stuff
3029         */
3030         if(clouds)
3031                 clouds->drop();
3032         if(gui_chat_console)
3033                 gui_chat_console->drop();
3034         
3035         /*
3036                 Draw a "shutting down" screen, which will be shown while the map
3037                 generator and other stuff quits
3038         */
3039         {
3040                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3041                 draw_load_screen(L"Shutting down stuff...", driver, font);
3042                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3043                 guienv->drawAll();
3044                 driver->endScene();
3045                 gui_shuttingdowntext->remove();*/
3046         }
3047
3048         chat_backend.addMessage(L"", L"# Disconnected.");
3049         chat_backend.addMessage(L"", L"");
3050
3051         // Client scope (client is destructed before destructing *def and tsrc)
3052         }while(0);
3053         } // try-catch
3054         catch(SerializationError &e)
3055         {
3056                 error_message = L"A serialization error occurred:\n"
3057                                 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3058                                 L" running a different version of Minetest.";
3059                 errorstream<<wide_to_narrow(error_message)<<std::endl;
3060         }
3061         
3062         if(!sound_is_dummy)
3063                 delete sound;
3064
3065         delete tsrc;
3066         delete shsrc;
3067         delete nodedef;
3068         delete itemdef;
3069 }
3070
3071