]> git.lizzy.rs Git - dragonfireclient.git/blob - src/game.cpp
disable tiling of textures only if smooth lighting is used
[dragonfireclient.git] / src / game.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 "common_irrlicht.h"
21 #include "game.h"
22 #include "client.h"
23 #include "server.h"
24 #include "guiPauseMenu.h"
25 #include "guiInventoryMenu.h"
26 #include "guiTextInputMenu.h"
27 #include "guiFurnaceMenu.h"
28 #include "materials.h"
29 #include "config.h"
30
31 /*
32         Setting this to 1 enables a special camera mode that forces
33         the renderers to think that the camera statically points from
34         the starting place to a static direction.
35
36         This allows one to move around with the player and see what
37         is actually drawn behind solid things and behind the player.
38 */
39 #define FIELD_OF_VIEW_TEST 0
40
41
42 MapDrawControl draw_control;
43
44 // Chat data
45 struct ChatLine
46 {
47         ChatLine():
48                 age(0.0)
49         {
50         }
51         ChatLine(const std::wstring &a_text):
52                 age(0.0),
53                 text(a_text)
54         {
55         }
56         float age;
57         std::wstring text;
58 };
59
60 /*
61         Inventory stuff
62 */
63
64 // Inventory actions from the menu are buffered here before sending
65 Queue<InventoryAction*> inventory_action_queue;
66 // This is a copy of the inventory that the client's environment has
67 Inventory local_inventory;
68
69 u16 g_selected_item = 0;
70
71 /*
72         Text input system
73 */
74
75 struct TextDestSign : public TextDest
76 {
77         TextDestSign(v3s16 blockpos, s16 id, Client *client)
78         {
79                 m_blockpos = blockpos;
80                 m_id = id;
81                 m_client = client;
82         }
83         void gotText(std::wstring text)
84         {
85                 std::string ntext = wide_to_narrow(text);
86                 dstream<<"Changing text of a sign object: "
87                                 <<ntext<<std::endl;
88                 m_client->sendSignText(m_blockpos, m_id, ntext);
89         }
90
91         v3s16 m_blockpos;
92         s16 m_id;
93         Client *m_client;
94 };
95
96 struct TextDestChat : public TextDest
97 {
98         TextDestChat(Client *client)
99         {
100                 m_client = client;
101         }
102         void gotText(std::wstring text)
103         {
104                 // Discard empty line
105                 if(text == L"")
106                         return;
107                 
108                 // Parse command (server command starts with "/#")
109                 if(text[0] == L'/' && text[1] != L'#')
110                 {
111                         std::wstring reply = L"Local: ";
112
113                         reply += L"Local commands not yet supported. "
114                                         L"Server prefix is \"/#\".";
115                         
116                         m_client->addChatMessage(reply);
117                         return;
118                 }
119
120                 // Send to others
121                 m_client->sendChatMessage(text);
122                 // Show locally
123                 m_client->addChatMessage(text);
124         }
125
126         Client *m_client;
127 };
128
129 struct TextDestSignNode : public TextDest
130 {
131         TextDestSignNode(v3s16 p, Client *client)
132         {
133                 m_p = p;
134                 m_client = client;
135         }
136         void gotText(std::wstring text)
137         {
138                 std::string ntext = wide_to_narrow(text);
139                 dstream<<"Changing text of a sign node: "
140                                 <<ntext<<std::endl;
141                 m_client->sendSignNodeText(m_p, ntext);
142         }
143
144         v3s16 m_p;
145         Client *m_client;
146 };
147
148 /*
149         Render distance feedback loop
150 */
151 void updateViewingRange(f32 frametime_in, Client *client)
152 {
153         if(draw_control.range_all == true)
154                 return;
155         
156         static f32 added_frametime = 0;
157         static s16 added_frames = 0;
158
159         added_frametime += frametime_in;
160         added_frames += 1;
161
162         // Actually this counter kind of sucks because frametime is busytime
163         static f32 counter = 0;
164         counter -= frametime_in;
165         if(counter > 0)
166                 return;
167         //counter = 0.1;
168         counter = 0.2;
169
170         /*dstream<<__FUNCTION_NAME
171                         <<": Collected "<<added_frames<<" frames, total of "
172                         <<added_frametime<<"s."<<std::endl;*/
173         
174         /*dstream<<"draw_control.blocks_drawn="
175                         <<draw_control.blocks_drawn
176                         <<", draw_control.blocks_would_have_drawn="
177                         <<draw_control.blocks_would_have_drawn
178                         <<std::endl;*/
179         
180         float range_min = g_settings.getS16("viewing_range_nodes_min");
181         float range_max = g_settings.getS16("viewing_range_nodes_max");
182         
183         draw_control.wanted_min_range = range_min;
184         draw_control.wanted_max_blocks = (1.2*draw_control.blocks_drawn)+1;
185         
186         float block_draw_ratio = 1.0;
187         if(draw_control.blocks_would_have_drawn != 0)
188         {
189                 block_draw_ratio = (float)draw_control.blocks_drawn
190                         / (float)draw_control.blocks_would_have_drawn;
191         }
192
193         // Calculate the average frametime in the case that all wanted
194         // blocks had been drawn
195         f32 frametime = added_frametime / added_frames / block_draw_ratio;
196         
197         added_frametime = 0.0;
198         added_frames = 0;
199         
200         float wanted_fps = g_settings.getFloat("wanted_fps");
201         float wanted_frametime = 1.0 / wanted_fps;
202         
203         f32 wanted_frametime_change = wanted_frametime - frametime;
204         //dstream<<"wanted_frametime_change="<<wanted_frametime_change<<std::endl;
205         
206         // If needed frametime change is small, just return
207         if(fabs(wanted_frametime_change) < wanted_frametime*0.4)
208         {
209                 //dstream<<"ignoring small wanted_frametime_change"<<std::endl;
210                 return;
211         }
212
213         float range = draw_control.wanted_range;
214         float new_range = range;
215
216         static s16 range_old = 0;
217         static f32 frametime_old = 0;
218         
219         float d_range = range - range_old;
220         f32 d_frametime = frametime - frametime_old;
221         // A sane default of 30ms per 50 nodes of range
222         static f32 time_per_range = 30. / 50;
223         if(d_range != 0)
224         {
225                 time_per_range = d_frametime / d_range;
226         }
227         
228         // The minimum allowed calculated frametime-range derivative:
229         // Practically this sets the maximum speed of changing the range.
230         // The lower this value, the higher the maximum changing speed.
231         // A low value here results in wobbly range (0.001)
232         // A high value here results in slow changing range (0.0025)
233         // SUGG: This could be dynamically adjusted so that when
234         //       the camera is turning, this is lower
235         //float min_time_per_range = 0.0015;
236         float min_time_per_range = 0.0010;
237         //float min_time_per_range = 0.05 / range;
238         if(time_per_range < min_time_per_range)
239         {
240                 time_per_range = min_time_per_range;
241                 //dstream<<"time_per_range="<<time_per_range<<" (min)"<<std::endl;
242         }
243         else
244         {
245                 //dstream<<"time_per_range="<<time_per_range<<std::endl;
246         }
247
248         f32 wanted_range_change = wanted_frametime_change / time_per_range;
249         // Dampen the change a bit to kill oscillations
250         //wanted_range_change *= 0.9;
251         //wanted_range_change *= 0.75;
252         wanted_range_change *= 0.5;
253         //dstream<<"wanted_range_change="<<wanted_range_change<<std::endl;
254
255         // If needed range change is very small, just return
256         if(fabs(wanted_range_change) < 0.001)
257         {
258                 //dstream<<"ignoring small wanted_range_change"<<std::endl;
259                 return;
260         }
261
262         new_range += wanted_range_change;
263         //dstream<<"new_range="<<new_range/*<<std::endl*/;
264         
265         //float new_range_unclamped = new_range;
266         if(new_range < range_min)
267                 new_range = range_min;
268         if(new_range > range_max)
269                 new_range = range_max;
270         
271         /*if(new_range != new_range_unclamped)
272                 dstream<<", clamped to "<<new_range<<std::endl;
273         else
274                 dstream<<std::endl;*/
275
276         draw_control.wanted_range = new_range;
277
278         range_old = new_range;
279         frametime_old = frametime;
280 }
281
282 /*
283         Hotbar draw routine
284 */
285 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
286                 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
287                 Inventory *inventory, s32 halfheartcount)
288 {
289         InventoryList *mainlist = inventory->getList("main");
290         if(mainlist == NULL)
291         {
292                 dstream<<"WARNING: draw_hotbar(): mainlist == NULL"<<std::endl;
293                 return;
294         }
295         
296         s32 padding = imgsize/12;
297         //s32 height = imgsize + padding*2;
298         s32 width = itemcount*(imgsize+padding*2);
299         
300         // Position of upper left corner of bar
301         v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
302         
303         // Draw background color
304         /*core::rect<s32> barrect(0,0,width,height);
305         barrect += pos;
306         video::SColor bgcolor(255,128,128,128);
307         driver->draw2DRectangle(bgcolor, barrect, NULL);*/
308
309         core::rect<s32> imgrect(0,0,imgsize,imgsize);
310
311         for(s32 i=0; i<itemcount; i++)
312         {
313                 InventoryItem *item = mainlist->getItem(i);
314                 
315                 core::rect<s32> rect = imgrect + pos
316                                 + v2s32(padding+i*(imgsize+padding*2), padding);
317                 
318                 if(g_selected_item == i)
319                 {
320                         driver->draw2DRectangle(video::SColor(255,255,0,0),
321                                         core::rect<s32>(rect.UpperLeftCorner - v2s32(1,1)*padding,
322                                                         rect.LowerRightCorner + v2s32(1,1)*padding),
323                                         NULL);
324                 }
325                 else
326                 {
327                         video::SColor bgcolor2(128,0,0,0);
328                         driver->draw2DRectangle(bgcolor2, rect, NULL);
329                 }
330
331                 if(item != NULL)
332                 {
333                         drawInventoryItem(driver, font, item, rect, NULL);
334                 }
335         }
336         
337         /*
338                 Draw hearts
339         */
340         {
341                 video::ITexture *heart_texture =
342                                 driver->getTexture(porting::getDataPath("heart.png").c_str());
343                 v2s32 p = pos + v2s32(0, -20);
344                 for(s32 i=0; i<halfheartcount/2; i++)
345                 {
346                         const video::SColor color(255,255,255,255);
347                         const video::SColor colors[] = {color,color,color,color};
348                         core::rect<s32> rect(0,0,16,16);
349                         rect += p;
350                         driver->draw2DImage(heart_texture, rect,
351                                 core::rect<s32>(core::position2d<s32>(0,0),
352                                 core::dimension2di(heart_texture->getOriginalSize())),
353                                 NULL, colors, true);
354                         p += v2s32(20,0);
355                 }
356                 if(halfheartcount % 2 == 1)
357                 {
358                         const video::SColor color(255,255,255,255);
359                         const video::SColor colors[] = {color,color,color,color};
360                         core::rect<s32> rect(0,0,16/2,16);
361                         rect += p;
362                         core::dimension2di srcd(heart_texture->getOriginalSize());
363                         srcd.Width /= 2;
364                         driver->draw2DImage(heart_texture, rect,
365                                 core::rect<s32>(core::position2d<s32>(0,0), srcd),
366                                 NULL, colors, true);
367                         p += v2s32(20,0);
368                 }
369         }
370 }
371
372 /*
373         Find what the player is pointing at
374 */
375 void getPointedNode(Client *client, v3f player_position,
376                 v3f camera_direction, v3f camera_position,
377                 bool &nodefound, core::line3d<f32> shootline,
378                 v3s16 &nodepos, v3s16 &neighbourpos,
379                 core::aabbox3d<f32> &nodehilightbox,
380                 f32 d)
381 {
382         f32 mindistance = BS * 1001;
383         
384         v3s16 pos_i = floatToInt(player_position, BS);
385
386         /*std::cout<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
387                         <<std::endl;*/
388
389         s16 a = d;
390         s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
391         s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
392         s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
393         s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
394         s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
395         s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
396         
397         for(s16 y = ystart; y <= yend; y++)
398         for(s16 z = zstart; z <= zend; z++)
399         for(s16 x = xstart; x <= xend; x++)
400         {
401                 MapNode n;
402                 try
403                 {
404                         n = client->getNode(v3s16(x,y,z));
405                         if(content_pointable(n.d) == false)
406                                 continue;
407                 }
408                 catch(InvalidPositionException &e)
409                 {
410                         continue;
411                 }
412
413                 v3s16 np(x,y,z);
414                 v3f npf = intToFloat(np, BS);
415                 
416                 f32 d = 0.01;
417                 
418                 v3s16 dirs[6] = {
419                         v3s16(0,0,1), // back
420                         v3s16(0,1,0), // top
421                         v3s16(1,0,0), // right
422                         v3s16(0,0,-1), // front
423                         v3s16(0,-1,0), // bottom
424                         v3s16(-1,0,0), // left
425                 };
426                 
427                 /*
428                         Meta-objects
429                 */
430                 if(n.d == CONTENT_TORCH)
431                 {
432                         v3s16 dir = unpackDir(n.dir);
433                         v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
434                         dir_f *= BS/2 - BS/6 - BS/20;
435                         v3f cpf = npf + dir_f;
436                         f32 distance = (cpf - camera_position).getLength();
437
438                         core::aabbox3d<f32> box;
439                         
440                         // bottom
441                         if(dir == v3s16(0,-1,0))
442                         {
443                                 box = core::aabbox3d<f32>(
444                                         npf - v3f(BS/6, BS/2, BS/6),
445                                         npf + v3f(BS/6, -BS/2+BS/3*2, BS/6)
446                                 );
447                         }
448                         // top
449                         else if(dir == v3s16(0,1,0))
450                         {
451                                 box = core::aabbox3d<f32>(
452                                         npf - v3f(BS/6, -BS/2+BS/3*2, BS/6),
453                                         npf + v3f(BS/6, BS/2, BS/6)
454                                 );
455                         }
456                         // side
457                         else
458                         {
459                                 box = core::aabbox3d<f32>(
460                                         cpf - v3f(BS/6, BS/3, BS/6),
461                                         cpf + v3f(BS/6, BS/3, BS/6)
462                                 );
463                         }
464
465                         if(distance < mindistance)
466                         {
467                                 if(box.intersectsWithLine(shootline))
468                                 {
469                                         nodefound = true;
470                                         nodepos = np;
471                                         neighbourpos = np;
472                                         mindistance = distance;
473                                         nodehilightbox = box;
474                                 }
475                         }
476                 }
477                 else if(n.d == CONTENT_SIGN_WALL)
478                 {
479                         v3s16 dir = unpackDir(n.dir);
480                         v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
481                         dir_f *= BS/2 - BS/6 - BS/20;
482                         v3f cpf = npf + dir_f;
483                         f32 distance = (cpf - camera_position).getLength();
484
485                         v3f vertices[4] =
486                         {
487                                 v3f(BS*0.42,-BS*0.35,-BS*0.4),
488                                 v3f(BS*0.49, BS*0.35, BS*0.4),
489                         };
490
491                         for(s32 i=0; i<2; i++)
492                         {
493                                 if(dir == v3s16(1,0,0))
494                                         vertices[i].rotateXZBy(0);
495                                 if(dir == v3s16(-1,0,0))
496                                         vertices[i].rotateXZBy(180);
497                                 if(dir == v3s16(0,0,1))
498                                         vertices[i].rotateXZBy(90);
499                                 if(dir == v3s16(0,0,-1))
500                                         vertices[i].rotateXZBy(-90);
501                                 if(dir == v3s16(0,-1,0))
502                                         vertices[i].rotateXYBy(-90);
503                                 if(dir == v3s16(0,1,0))
504                                         vertices[i].rotateXYBy(90);
505
506                                 vertices[i] += npf;
507                         }
508
509                         core::aabbox3d<f32> box;
510
511                         box = core::aabbox3d<f32>(vertices[0]);
512                         box.addInternalPoint(vertices[1]);
513
514                         if(distance < mindistance)
515                         {
516                                 if(box.intersectsWithLine(shootline))
517                                 {
518                                         nodefound = true;
519                                         nodepos = np;
520                                         neighbourpos = np;
521                                         mindistance = distance;
522                                         nodehilightbox = box;
523                                 }
524                         }
525                 }
526                 /*
527                         Regular blocks
528                 */
529                 else
530                 {
531                         for(u16 i=0; i<6; i++)
532                         {
533                                 v3f dir_f = v3f(dirs[i].X,
534                                                 dirs[i].Y, dirs[i].Z);
535                                 v3f centerpoint = npf + dir_f * BS/2;
536                                 f32 distance =
537                                                 (centerpoint - camera_position).getLength();
538                                 
539                                 if(distance < mindistance)
540                                 {
541                                         core::CMatrix4<f32> m;
542                                         m.buildRotateFromTo(v3f(0,0,1), dir_f);
543
544                                         // This is the back face
545                                         v3f corners[2] = {
546                                                 v3f(BS/2, BS/2, BS/2),
547                                                 v3f(-BS/2, -BS/2, BS/2+d)
548                                         };
549                                         
550                                         for(u16 j=0; j<2; j++)
551                                         {
552                                                 m.rotateVect(corners[j]);
553                                                 corners[j] += npf;
554                                         }
555
556                                         core::aabbox3d<f32> facebox(corners[0]);
557                                         facebox.addInternalPoint(corners[1]);
558
559                                         if(facebox.intersectsWithLine(shootline))
560                                         {
561                                                 nodefound = true;
562                                                 nodepos = np;
563                                                 neighbourpos = np + dirs[i];
564                                                 mindistance = distance;
565
566                                                 //nodehilightbox = facebox;
567
568                                                 const float d = 0.502;
569                                                 core::aabbox3d<f32> nodebox
570                                                                 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
571                                                 v3f nodepos_f = intToFloat(nodepos, BS);
572                                                 nodebox.MinEdge += nodepos_f;
573                                                 nodebox.MaxEdge += nodepos_f;
574                                                 nodehilightbox = nodebox;
575                                         }
576                                 } // if distance < mindistance
577                         } // for dirs
578                 } // regular block
579         } // for coords
580 }
581
582 void the_game(
583         bool &kill,
584         bool random_input,
585         InputHandler *input,
586         IrrlichtDevice *device,
587         gui::IGUIFont* font,
588         std::string map_dir,
589         std::string playername,
590         std::string address,
591         u16 port,
592         std::wstring &error_message
593 )
594 {
595         video::IVideoDriver* driver = device->getVideoDriver();
596         scene::ISceneManager* smgr = device->getSceneManager();
597
598         v2u32 screensize(0,0);
599         v2u32 last_screensize(0,0);
600         screensize = driver->getScreenSize();
601
602         const s32 hotbar_itemcount = 8;
603         const s32 hotbar_imagesize = 36;
604         
605         /*
606                 Draw "Loading" screen
607         */
608         const wchar_t *text = L"Loading and connecting...";
609         u32 text_height = font->getDimension(text).Height;
610         core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
611         core::vector2d<s32> textsize(300, text_height);
612         core::rect<s32> textrect(center - textsize/2, center + textsize/2);
613
614         gui::IGUIStaticText *gui_loadingtext = guienv->addStaticText(
615                         text, textrect, false, false);
616         gui_loadingtext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
617
618         driver->beginScene(true, true, video::SColor(255,0,0,0));
619         guienv->drawAll();
620         driver->endScene();
621
622         std::cout<<DTIME<<"Creating server and client"<<std::endl;
623         
624         /*
625                 Create server.
626                 SharedPtr will delete it when it goes out of scope.
627         */
628         SharedPtr<Server> server;
629         if(address == ""){
630                 server = new Server(map_dir);
631                 server->start(port);
632         }
633         
634         /*
635                 Create client
636         */
637
638         Client client(device, playername.c_str(), draw_control);
639                         
640         Address connect_address(0,0,0,0, port);
641         try{
642                 if(address == "")
643                         //connect_address.Resolve("localhost");
644                         connect_address.setAddress(127,0,0,1);
645                 else
646                         connect_address.Resolve(address.c_str());
647         }
648         catch(ResolveError &e)
649         {
650                 std::cout<<DTIME<<"Couldn't resolve address"<<std::endl;
651                 //return 0;
652                 error_message = L"Couldn't resolve address";
653                 gui_loadingtext->remove();
654                 return;
655         }
656
657         /*
658                 Attempt to connect to the server
659         */
660         
661         dstream<<DTIME<<"Connecting to server at ";
662         connect_address.print(&dstream);
663         dstream<<std::endl;
664         client.connect(connect_address);
665
666         bool could_connect = false;
667         
668         try{
669                 float time_counter = 0.0;
670                 for(;;)
671                 {
672                         if(client.connectedAndInitialized())
673                         {
674                                 could_connect = true;
675                                 break;
676                         }
677                         // Wait for 10 seconds
678                         if(time_counter >= 10.0)
679                         {
680                                 break;
681                         }
682
683                         // Update screen
684                         driver->beginScene(true, true, video::SColor(255,0,0,0));
685                         guienv->drawAll();
686                         driver->endScene();
687
688                         // Update client and server
689
690                         client.step(0.1);
691
692                         if(server != NULL)
693                                 server->step(0.1);
694                         
695                         // Delay a bit
696                         sleep_ms(100);
697                         time_counter += 0.1;
698                 }
699         }
700         catch(con::PeerNotFoundException &e)
701         {}
702
703         if(could_connect == false)
704         {
705                 std::cout<<DTIME<<"Timed out."<<std::endl;
706                 error_message = L"Connection timed out.";
707                 gui_loadingtext->remove();
708                 return;
709         }
710
711         /*
712                 Create skybox
713         */
714         /*scene::ISceneNode* skybox;
715         skybox = smgr->addSkyBoxSceneNode(
716                 driver->getTexture(porting::getDataPath("skybox2.png").c_str()),
717                 driver->getTexture(porting::getDataPath("skybox3.png").c_str()),
718                 driver->getTexture(porting::getDataPath("skybox1.png").c_str()),
719                 driver->getTexture(porting::getDataPath("skybox1.png").c_str()),
720                 driver->getTexture(porting::getDataPath("skybox1.png").c_str()),
721                 driver->getTexture(porting::getDataPath("skybox1.png").c_str()));*/
722         
723         /*
724                 Create the camera node
725         */
726
727         scene::ICameraSceneNode* camera = smgr->addCameraSceneNode(
728                 0, // Camera parent
729                 v3f(BS*100, BS*2, BS*100), // Look from
730                 v3f(BS*100+1, BS*2, BS*100), // Look to
731                 -1 // Camera ID
732         );
733
734         if(camera == NULL)
735         {
736                 error_message = L"Failed to create the camera node";
737                 return;
738         }
739
740         //video::SColor skycolor = video::SColor(255,90,140,200);
741         //video::SColor skycolor = video::SColor(255,166,202,244);
742         //video::SColor skycolor = video::SColor(255,120,185,244);
743         video::SColor skycolor = video::SColor(255,140,186,250);
744
745         camera->setFOV(FOV_ANGLE);
746
747         // Just so big a value that everything rendered is visible
748         camera->setFarValue(100000*BS);
749         
750         f32 camera_yaw = 0; // "right/left"
751         f32 camera_pitch = 0; // "up/down"
752
753         /*
754                 Move into game
755         */
756         
757         gui_loadingtext->remove();
758
759         /*
760                 Add some gui stuff
761         */
762
763         // First line of debug text
764         gui::IGUIStaticText *guitext = guienv->addStaticText(
765                         L"Minetest-c55",
766                         core::rect<s32>(5, 5, 795, 5+text_height),
767                         false, false);
768         // Second line of debug text
769         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
770                         L"",
771                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
772                         false, false);
773         
774         // At the middle of the screen
775         // Object infos are shown in this
776         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
777                         L"",
778                         core::rect<s32>(0,0,400,text_height+5) + v2s32(100,200),
779                         false, false);
780         
781         // Chat text
782         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
783                         L"",
784                         core::rect<s32>(0,0,0,0),
785                         false, false); // Disable word wrap as of now
786                         //false, true);
787         //guitext_chat->setBackgroundColor(video::SColor(96,0,0,0));
788         core::list<ChatLine> chat_lines;
789         
790         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
791                         (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/
792         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
793                         (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/
794         
795         // Test the text input system
796         /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr,
797                         NULL))->drop();*/
798         /*GUIMessageMenu *menu =
799                         new GUIMessageMenu(guienv, guiroot, -1, 
800                                 &g_menumgr,
801                                 L"Asd");
802         menu->drop();*/
803         
804         // Launch pause menu
805         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
806                         &g_menumgr))->drop();
807         
808         // Enable texts
809         /*guitext2->setVisible(true);
810         guitext_info->setVisible(true);
811         guitext_chat->setVisible(true);*/
812
813         //s32 guitext_chat_pad_bottom = 70;
814
815         /*
816                 Some statistics are collected in these
817         */
818         u32 drawtime = 0;
819         u32 beginscenetime = 0;
820         u32 scenetime = 0;
821         u32 endscenetime = 0;
822         
823         // A test
824         //throw con::PeerNotFoundException("lol");
825
826         core::list<float> frametime_log;
827
828         float damage_flash_timer = 0;
829
830         /*
831                 Main loop
832         */
833
834         bool first_loop_after_window_activation = true;
835
836         // Time is in milliseconds
837         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
838         // NOTE: So we have to use getTime() and call run()s between them
839         u32 lasttime = device->getTimer()->getTime();
840
841         while(device->run() && kill == false)
842         {
843                 if(g_gamecallback->disconnect_requested)
844                 {
845                         g_gamecallback->disconnect_requested = false;
846                         break;
847                 }
848
849                 /*
850                         Process TextureSource's queue
851                 */
852                 ((TextureSource*)g_texturesource)->processQueue();
853
854                 /*
855                         Random calculations
856                 */
857                 last_screensize = screensize;
858                 screensize = driver->getScreenSize();
859                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
860                 //bool screensize_changed = screensize != last_screensize;
861                 
862                 // Hilight boxes collected during the loop and displayed
863                 core::list< core::aabbox3d<f32> > hilightboxes;
864                 
865                 // Info text
866                 std::wstring infotext;
867
868                 // When screen size changes, update positions and sizes of stuff
869                 /*if(screensize_changed)
870                 {
871                         v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing);
872                         quick_inventory->updatePosition(pos);
873                 }*/
874
875                 //TimeTaker //timer1("//timer1");
876                 
877                 // Time of frame without fps limit
878                 float busytime;
879                 u32 busytime_u32;
880                 {
881                         // not using getRealTime is necessary for wine
882                         u32 time = device->getTimer()->getTime();
883                         if(time > lasttime)
884                                 busytime_u32 = time - lasttime;
885                         else
886                                 busytime_u32 = 0;
887                         busytime = busytime_u32 / 1000.0;
888                 }
889
890                 //std::cout<<"busytime_u32="<<busytime_u32<<std::endl;
891         
892                 // Necessary for device->getTimer()->getTime()
893                 device->run();
894
895                 /*
896                         Viewing range
897                 */
898                 
899                 updateViewingRange(busytime, &client);
900                 
901                 /*
902                         FPS limiter
903                 */
904
905                 {
906                         float fps_max = g_settings.getFloat("fps_max");
907                         u32 frametime_min = 1000./fps_max;
908                         
909                         if(busytime_u32 < frametime_min)
910                         {
911                                 u32 sleeptime = frametime_min - busytime_u32;
912                                 device->sleep(sleeptime);
913                         }
914                 }
915
916                 // Necessary for device->getTimer()->getTime()
917                 device->run();
918
919                 /*
920                         Time difference calculation
921                 */
922                 f32 dtime; // in seconds
923                 
924                 u32 time = device->getTimer()->getTime();
925                 if(time > lasttime)
926                         dtime = (time - lasttime) / 1000.0;
927                 else
928                         dtime = 0;
929                 lasttime = time;
930
931                 /*
932                         Log frametime for visualization
933                 */
934                 frametime_log.push_back(dtime);
935                 if(frametime_log.size() > 100)
936                 {
937                         core::list<float>::Iterator i = frametime_log.begin();
938                         frametime_log.erase(i);
939                 }
940
941                 /*
942                         Visualize frametime in terminal
943                 */
944                 /*for(u32 i=0; i<dtime*400; i++)
945                         std::cout<<"X";
946                 std::cout<<std::endl;*/
947
948                 /*
949                         Time average and jitter calculation
950                 */
951
952                 static f32 dtime_avg1 = 0.0;
953                 dtime_avg1 = dtime_avg1 * 0.98 + dtime * 0.02;
954                 f32 dtime_jitter1 = dtime - dtime_avg1;
955
956                 static f32 dtime_jitter1_max_sample = 0.0;
957                 static f32 dtime_jitter1_max_fraction = 0.0;
958                 {
959                         static f32 jitter1_max = 0.0;
960                         static f32 counter = 0.0;
961                         if(dtime_jitter1 > jitter1_max)
962                                 jitter1_max = dtime_jitter1;
963                         counter += dtime;
964                         if(counter > 0.0)
965                         {
966                                 counter -= 3.0;
967                                 dtime_jitter1_max_sample = jitter1_max;
968                                 dtime_jitter1_max_fraction
969                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
970                                 jitter1_max = 0.0;
971                         }
972                 }
973                 
974                 /*
975                         Busytime average and jitter calculation
976                 */
977
978                 static f32 busytime_avg1 = 0.0;
979                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
980                 f32 busytime_jitter1 = busytime - busytime_avg1;
981                 
982                 static f32 busytime_jitter1_max_sample = 0.0;
983                 static f32 busytime_jitter1_min_sample = 0.0;
984                 {
985                         static f32 jitter1_max = 0.0;
986                         static f32 jitter1_min = 0.0;
987                         static f32 counter = 0.0;
988                         if(busytime_jitter1 > jitter1_max)
989                                 jitter1_max = busytime_jitter1;
990                         if(busytime_jitter1 < jitter1_min)
991                                 jitter1_min = busytime_jitter1;
992                         counter += dtime;
993                         if(counter > 0.0){
994                                 counter -= 3.0;
995                                 busytime_jitter1_max_sample = jitter1_max;
996                                 busytime_jitter1_min_sample = jitter1_min;
997                                 jitter1_max = 0.0;
998                                 jitter1_min = 0.0;
999                         }
1000                 }
1001                 
1002                 /*
1003                         Debug info for client
1004                 */
1005                 {
1006                         static float counter = 0.0;
1007                         counter -= dtime;
1008                         if(counter < 0)
1009                         {
1010                                 counter = 30.0;
1011                                 client.printDebugInfo(std::cout);
1012                         }
1013                 }
1014
1015                 /*
1016                         Direct handling of user input
1017                 */
1018                 
1019                 // Reset input if window not active or some menu is active
1020                 if(device->isWindowActive() == false || noMenuActive() == false)
1021                 {
1022                         input->clear();
1023                 }
1024
1025                 // Input handler step() (used by the random input generator)
1026                 input->step(dtime);
1027
1028                 /*
1029                         Launch menus according to keys
1030                 */
1031                 if(input->wasKeyDown(irr::KEY_KEY_I))
1032                 {
1033                         dstream<<DTIME<<"the_game: "
1034                                         <<"Launching inventory"<<std::endl;
1035                         
1036                         GUIInventoryMenu *menu =
1037                                 new GUIInventoryMenu(guienv, guiroot, -1,
1038                                         &g_menumgr, v2s16(8,7),
1039                                         client.getInventoryContext(),
1040                                         &client);
1041
1042                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1043                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1044                                         "list", "current_player", "main",
1045                                         v2s32(0, 3), v2s32(8, 4)));
1046                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1047                                         "list", "current_player", "craft",
1048                                         v2s32(3, 0), v2s32(3, 3)));
1049                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1050                                         "list", "current_player", "craftresult",
1051                                         v2s32(7, 1), v2s32(1, 1)));
1052
1053                         menu->setDrawSpec(draw_spec);
1054
1055                         menu->drop();
1056                 }
1057                 else if(input->wasKeyDown(irr::KEY_ESCAPE))
1058                 {
1059                         dstream<<DTIME<<"the_game: "
1060                                         <<"Launching pause menu"<<std::endl;
1061                         // It will delete itself by itself
1062                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1063                                         &g_menumgr))->drop();
1064                 }
1065                 else if(input->wasKeyDown(irr::KEY_KEY_T))
1066                 {
1067                         TextDest *dest = new TextDestChat(&client);
1068
1069                         (new GUITextInputMenu(guienv, guiroot, -1,
1070                                         &g_menumgr, dest,
1071                                         L""))->drop();
1072                 }
1073
1074                 // Item selection with mouse wheel
1075                 {
1076                         s32 wheel = input->getMouseWheel();
1077                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1078                                         hotbar_itemcount-1);
1079
1080                         if(wheel < 0)
1081                         {
1082                                 if(g_selected_item < max_item)
1083                                         g_selected_item++;
1084                                 else
1085                                         g_selected_item = 0;
1086                         }
1087                         else if(wheel > 0)
1088                         {
1089                                 if(g_selected_item > 0)
1090                                         g_selected_item--;
1091                                 else
1092                                         g_selected_item = max_item;
1093                         }
1094                 }
1095                 
1096                 // Item selection
1097                 for(u16 i=0; i<10; i++)
1098                 {
1099                         s32 keycode = irr::KEY_KEY_1 + i;
1100                         if(i == 9)
1101                                 keycode = irr::KEY_KEY_0;
1102                         if(input->wasKeyDown((irr::EKEY_CODE)keycode))
1103                         {
1104                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1105                                 {
1106                                         g_selected_item = i;
1107
1108                                         dstream<<DTIME<<"Selected item: "
1109                                                         <<g_selected_item<<std::endl;
1110                                 }
1111                         }
1112                 }
1113
1114                 // Viewing range selection
1115                 if(input->wasKeyDown(irr::KEY_KEY_R))
1116                 {
1117                         if(draw_control.range_all)
1118                         {
1119                                 draw_control.range_all = false;
1120                                 dstream<<DTIME<<"Disabled full viewing range"<<std::endl;
1121                         }
1122                         else
1123                         {
1124                                 draw_control.range_all = true;
1125                                 dstream<<DTIME<<"Enabled full viewing range"<<std::endl;
1126                         }
1127                 }
1128
1129                 // Print debug stacks
1130                 if(input->wasKeyDown(irr::KEY_KEY_P))
1131                 {
1132                         dstream<<"-----------------------------------------"
1133                                         <<std::endl;
1134                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1135                         dstream<<"-----------------------------------------"
1136                                         <<std::endl;
1137                         debug_stacks_print();
1138                 }
1139
1140                 /*
1141                         Player speed control
1142                 */
1143                 
1144                 {
1145                         /*bool a_up,
1146                         bool a_down,
1147                         bool a_left,
1148                         bool a_right,
1149                         bool a_jump,
1150                         bool a_superspeed,
1151                         bool a_sneak,
1152                         float a_pitch,
1153                         float a_yaw*/
1154                         PlayerControl control(
1155                                 input->isKeyDown(irr::KEY_KEY_W),
1156                                 input->isKeyDown(irr::KEY_KEY_S),
1157                                 input->isKeyDown(irr::KEY_KEY_A),
1158                                 input->isKeyDown(irr::KEY_KEY_D),
1159                                 input->isKeyDown(irr::KEY_SPACE),
1160                                 input->isKeyDown(irr::KEY_KEY_E),
1161                                 input->isKeyDown(irr::KEY_LSHIFT)
1162                                                 || input->isKeyDown(irr::KEY_RSHIFT),
1163                                 camera_pitch,
1164                                 camera_yaw
1165                         );
1166                         client.setPlayerControl(control);
1167                 }
1168                 
1169                 /*
1170                         Run server
1171                 */
1172
1173                 if(server != NULL)
1174                 {
1175                         //TimeTaker timer("server->step(dtime)");
1176                         server->step(dtime);
1177                 }
1178
1179                 /*
1180                         Process environment
1181                 */
1182                 
1183                 {
1184                         //TimeTaker timer("client.step(dtime)");
1185                         client.step(dtime);
1186                         //client.step(dtime_avg1);
1187                 }
1188
1189                 // Read client events
1190                 for(;;)
1191                 {
1192                         ClientEvent event = client.getClientEvent();
1193                         if(event.type == CE_NONE)
1194                         {
1195                                 break;
1196                         }
1197                         else if(event.type == CE_PLAYER_DAMAGE)
1198                         {
1199                                 //u16 damage = event.player_damage.amount;
1200                                 //dstream<<"Player damage: "<<damage<<std::endl;
1201                                 damage_flash_timer = 0.05;
1202                         }
1203                         else if(event.type == CE_PLAYER_FORCE_MOVE)
1204                         {
1205                                 camera_yaw = event.player_force_move.yaw;
1206                                 camera_pitch = event.player_force_move.pitch;
1207                         }
1208                 }
1209                 
1210                 // Get player position
1211                 v3f player_position = client.getPlayerPosition();
1212                 
1213                 //TimeTaker //timer2("//timer2");
1214
1215                 /*
1216                         Mouse and camera control
1217                 */
1218                 
1219                 if((device->isWindowActive() && noMenuActive()) || random_input)
1220                 {
1221                         if(!random_input)
1222                                 device->getCursorControl()->setVisible(false);
1223
1224                         if(first_loop_after_window_activation){
1225                                 //std::cout<<"window active, first loop"<<std::endl;
1226                                 first_loop_after_window_activation = false;
1227                         }
1228                         else{
1229                                 s32 dx = input->getMousePos().X - displaycenter.X;
1230                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1231                                 //std::cout<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1232                                 camera_yaw -= dx*0.2;
1233                                 camera_pitch += dy*0.2;
1234                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1235                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1236                         }
1237                         input->setMousePos(displaycenter.X, displaycenter.Y);
1238                 }
1239                 else{
1240                         device->getCursorControl()->setVisible(true);
1241
1242                         //std::cout<<"window inactive"<<std::endl;
1243                         first_loop_after_window_activation = true;
1244                 }
1245
1246                 camera_yaw = wrapDegrees(camera_yaw);
1247                 camera_pitch = wrapDegrees(camera_pitch);
1248                 
1249                 v3f camera_direction = v3f(0,0,1);
1250                 camera_direction.rotateYZBy(camera_pitch);
1251                 camera_direction.rotateXZBy(camera_yaw);
1252                 
1253                 // This is at the height of the eyes of the current figure
1254                 //v3f camera_position = player_position + v3f(0, BS+BS/2, 0);
1255                 // This is more like in minecraft
1256                 v3f camera_position = player_position + v3f(0, BS+BS*0.625, 0);
1257
1258                 camera->setPosition(camera_position);
1259                 // *100.0 helps in large map coordinates
1260                 camera->setTarget(camera_position + camera_direction * 100.0);
1261
1262                 if(FIELD_OF_VIEW_TEST){
1263                         client.updateCamera(v3f(0,0,0), v3f(0,0,1));
1264                 }
1265                 else{
1266                         //TimeTaker timer("client.updateCamera");
1267                         client.updateCamera(camera_position, camera_direction);
1268                 }
1269                 
1270                 //timer2.stop();
1271                 //TimeTaker //timer3("//timer3");
1272
1273                 /*
1274                         Calculate what block is the crosshair pointing to
1275                 */
1276                 
1277                 //u32 t1 = device->getTimer()->getRealTime();
1278                 
1279                 //f32 d = 4; // max. distance
1280                 f32 d = 4; // max. distance
1281                 core::line3d<f32> shootline(camera_position,
1282                                 camera_position + camera_direction * BS * (d+1));
1283
1284                 MapBlockObject *selected_object = client.getSelectedObject
1285                                 (d*BS, camera_position, shootline);
1286
1287                 ClientActiveObject *selected_active_object
1288                                 = client.getSelectedActiveObject
1289                                         (d*BS, camera_position, shootline);
1290
1291                 if(selected_object != NULL)
1292                 {
1293                         //dstream<<"Client returned selected_object != NULL"<<std::endl;
1294
1295                         core::aabbox3d<f32> box_on_map
1296                                         = selected_object->getSelectionBoxOnMap();
1297
1298                         hilightboxes.push_back(box_on_map);
1299
1300                         infotext = narrow_to_wide(selected_object->infoText());
1301
1302                         if(input->getLeftClicked())
1303                         {
1304                                 std::cout<<DTIME<<"Left-clicked object"<<std::endl;
1305                                 client.clickObject(0, selected_object->getBlock()->getPos(),
1306                                                 selected_object->getId(), g_selected_item);
1307                         }
1308                         else if(input->getRightClicked())
1309                         {
1310                                 std::cout<<DTIME<<"Right-clicked object"<<std::endl;
1311                                 /*
1312                                         Check if we want to modify the object ourselves
1313                                 */
1314                                 if(selected_object->getTypeId() == MAPBLOCKOBJECT_TYPE_SIGN)
1315                                 {
1316                                         dstream<<"Sign object right-clicked"<<std::endl;
1317                                         
1318                                         if(random_input == false)
1319                                         {
1320                                                 // Get a new text for it
1321
1322                                                 TextDest *dest = new TextDestSign(
1323                                                                 selected_object->getBlock()->getPos(),
1324                                                                 selected_object->getId(),
1325                                                                 &client);
1326
1327                                                 SignObject *sign_object = (SignObject*)selected_object;
1328
1329                                                 std::wstring wtext =
1330                                                                 narrow_to_wide(sign_object->getText());
1331
1332                                                 (new GUITextInputMenu(guienv, guiroot, -1,
1333                                                                 &g_menumgr, dest,
1334                                                                 wtext))->drop();
1335                                         }
1336                                 }
1337                                 /*
1338                                         Otherwise pass the event to the server as-is
1339                                 */
1340                                 else
1341                                 {
1342                                         client.clickObject(1, selected_object->getBlock()->getPos(),
1343                                                         selected_object->getId(), g_selected_item);
1344                                 }
1345                         }
1346                 }
1347                 else if(selected_active_object != NULL)
1348                 {
1349                         //dstream<<"Client returned selected_active_object != NULL"<<std::endl;
1350                         
1351                         core::aabbox3d<f32> *selection_box
1352                                         = selected_active_object->getSelectionBox();
1353                         // Box should exist because object was returned in the
1354                         // first place
1355                         assert(selection_box);
1356
1357                         v3f pos = selected_active_object->getPosition();
1358
1359                         core::aabbox3d<f32> box_on_map(
1360                                         selection_box->MinEdge + pos,
1361                                         selection_box->MaxEdge + pos
1362                         );
1363
1364                         hilightboxes.push_back(box_on_map);
1365
1366                         //infotext = narrow_to_wide("A ClientActiveObject");
1367                         infotext = narrow_to_wide(selected_active_object->infoText());
1368
1369                         if(input->getLeftClicked())
1370                         {
1371                                 std::cout<<DTIME<<"Left-clicked object"<<std::endl;
1372                                 client.clickActiveObject(0,
1373                                                 selected_active_object->getId(), g_selected_item);
1374                         }
1375                         else if(input->getRightClicked())
1376                         {
1377                                 std::cout<<DTIME<<"Right-clicked object"<<std::endl;
1378                         }
1379                 }
1380                 else // selected_object == NULL
1381                 {
1382
1383                 /*
1384                         Find out which node we are pointing at
1385                 */
1386                 
1387                 bool nodefound = false;
1388                 v3s16 nodepos;
1389                 v3s16 neighbourpos;
1390                 core::aabbox3d<f32> nodehilightbox;
1391
1392                 getPointedNode(&client, player_position,
1393                                 camera_direction, camera_position,
1394                                 nodefound, shootline,
1395                                 nodepos, neighbourpos,
1396                                 nodehilightbox, d);
1397         
1398                 static float nodig_delay_counter = 0.0;
1399
1400                 if(nodefound)
1401                 {
1402                         static v3s16 nodepos_old(-32768,-32768,-32768);
1403
1404                         static float dig_time = 0.0;
1405                         static u16 dig_index = 0;
1406                         
1407                         /*
1408                                 Visualize selection
1409                         */
1410
1411                         hilightboxes.push_back(nodehilightbox);
1412
1413                         /*
1414                                 Check information text of node
1415                         */
1416
1417                         NodeMetadata *meta = client.getNodeMetadata(nodepos);
1418                         if(meta)
1419                         {
1420                                 infotext = narrow_to_wide(meta->infoText());
1421                         }
1422                         
1423                         //MapNode node = client.getNode(nodepos);
1424
1425                         /*
1426                                 Handle digging
1427                         */
1428                         
1429                         if(input->getLeftReleased())
1430                         {
1431                                 client.clearTempMod(nodepos);
1432                                 dig_time = 0.0;
1433                         }
1434                         
1435                         if(nodig_delay_counter > 0.0)
1436                         {
1437                                 nodig_delay_counter -= dtime;
1438                         }
1439                         else
1440                         {
1441                                 if(nodepos != nodepos_old)
1442                                 {
1443                                         std::cout<<DTIME<<"Pointing at ("<<nodepos.X<<","
1444                                                         <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;
1445
1446                                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1447                                         {
1448                                                 client.clearTempMod(nodepos_old);
1449                                                 dig_time = 0.0;
1450                                         }
1451                                 }
1452
1453                                 if(input->getLeftClicked() ||
1454                                                 (input->getLeftState() && nodepos != nodepos_old))
1455                                 {
1456                                         dstream<<DTIME<<"Started digging"<<std::endl;
1457                                         client.groundAction(0, nodepos, neighbourpos, g_selected_item);
1458                                 }
1459                                 if(input->getLeftClicked())
1460                                 {
1461                                         client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, 0));
1462                                 }
1463                                 if(input->getLeftState())
1464                                 {
1465                                         MapNode n = client.getNode(nodepos);
1466                                 
1467                                         // Get tool name. Default is "" = bare hands
1468                                         std::string toolname = "";
1469                                         InventoryList *mlist = local_inventory.getList("main");
1470                                         if(mlist != NULL)
1471                                         {
1472                                                 InventoryItem *item = mlist->getItem(g_selected_item);
1473                                                 if(item && (std::string)item->getName() == "ToolItem")
1474                                                 {
1475                                                         ToolItem *titem = (ToolItem*)item;
1476                                                         toolname = titem->getToolName();
1477                                                 }
1478                                         }
1479
1480                                         // Get digging properties for material and tool
1481                                         u8 material = n.d;
1482                                         DiggingProperties prop =
1483                                                         getDiggingProperties(material, toolname);
1484                                         
1485                                         float dig_time_complete = 0.0;
1486
1487                                         if(prop.diggable == false)
1488                                         {
1489                                                 /*dstream<<"Material "<<(int)material
1490                                                                 <<" not diggable with \""
1491                                                                 <<toolname<<"\""<<std::endl;*/
1492                                                 // I guess nobody will wait for this long
1493                                                 dig_time_complete = 10000000.0;
1494                                         }
1495                                         else
1496                                         {
1497                                                 dig_time_complete = prop.time;
1498                                         }
1499                                         
1500                                         if(dig_time_complete >= 0.001)
1501                                         {
1502                                                 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1503                                                                 * dig_time/dig_time_complete);
1504                                         }
1505                                         // This is for torches
1506                                         else
1507                                         {
1508                                                 dig_index = CRACK_ANIMATION_LENGTH;
1509                                         }
1510
1511                                         if(dig_index < CRACK_ANIMATION_LENGTH)
1512                                         {
1513                                                 //TimeTaker timer("client.setTempMod");
1514                                                 //dstream<<"dig_index="<<dig_index<<std::endl;
1515                                                 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1516                                         }
1517                                         else
1518                                         {
1519                                                 dstream<<DTIME<<"Digging completed"<<std::endl;
1520                                                 client.groundAction(3, nodepos, neighbourpos, g_selected_item);
1521                                                 client.clearTempMod(nodepos);
1522                                                 client.removeNode(nodepos);
1523
1524                                                 dig_time = 0;
1525
1526                                                 nodig_delay_counter = dig_time_complete
1527                                                                 / (float)CRACK_ANIMATION_LENGTH;
1528
1529                                                 // We don't want a corresponding delay to
1530                                                 // very time consuming nodes
1531                                                 if(nodig_delay_counter > 0.5)
1532                                                 {
1533                                                         nodig_delay_counter = 0.5;
1534                                                 }
1535                                                 // We want a slight delay to very little
1536                                                 // time consuming nodes
1537                                                 float mindelay = 0.15;
1538                                                 if(nodig_delay_counter < mindelay)
1539                                                 {
1540                                                         nodig_delay_counter = mindelay;
1541                                                 }
1542                                         }
1543
1544                                         dig_time += dtime;
1545                                 }
1546                         }
1547                         
1548                         if(input->getRightClicked())
1549                         {
1550                                 std::cout<<DTIME<<"Ground right-clicked"<<std::endl;
1551                                 
1552                                 if(meta && meta->typeId() == CONTENT_SIGN_WALL && !random_input)
1553                                 {
1554                                         dstream<<"Sign node right-clicked"<<std::endl;
1555                                         
1556                                         SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
1557                                         
1558                                         // Get a new text for it
1559
1560                                         TextDest *dest = new TextDestSignNode(nodepos, &client);
1561
1562                                         std::wstring wtext =
1563                                                         narrow_to_wide(signmeta->getText());
1564
1565                                         (new GUITextInputMenu(guienv, guiroot, -1,
1566                                                         &g_menumgr, dest,
1567                                                         wtext))->drop();
1568                                 }
1569                                 else if(meta && meta->typeId() == CONTENT_CHEST && !random_input)
1570                                 {
1571                                         dstream<<"Chest node right-clicked"<<std::endl;
1572                                         
1573                                         //ChestNodeMetadata *chestmeta = (ChestNodeMetadata*)meta;
1574
1575                                         std::string chest_inv_id;
1576                                         chest_inv_id += "nodemeta:";
1577                                         chest_inv_id += itos(nodepos.X);
1578                                         chest_inv_id += ",";
1579                                         chest_inv_id += itos(nodepos.Y);
1580                                         chest_inv_id += ",";
1581                                         chest_inv_id += itos(nodepos.Z);
1582                                         
1583                                         GUIInventoryMenu *menu =
1584                                                 new GUIInventoryMenu(guienv, guiroot, -1,
1585                                                         &g_menumgr, v2s16(8,9),
1586                                                         client.getInventoryContext(),
1587                                                         &client);
1588
1589                                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1590                                         
1591                                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1592                                                         "list", chest_inv_id, "0",
1593                                                         v2s32(0, 0), v2s32(8, 4)));
1594                                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1595                                                         "list", "current_player", "main",
1596                                                         v2s32(0, 5), v2s32(8, 4)));
1597
1598                                         menu->setDrawSpec(draw_spec);
1599
1600                                         menu->drop();
1601
1602                                 }
1603                                 else if(meta && meta->typeId() == CONTENT_FURNACE && !random_input)
1604                                 {
1605                                         dstream<<"Furnace node right-clicked"<<std::endl;
1606                                         
1607                                         GUIFurnaceMenu *menu =
1608                                                 new GUIFurnaceMenu(guienv, guiroot, -1,
1609                                                         &g_menumgr, nodepos, &client);
1610
1611                                         menu->drop();
1612
1613                                 }
1614                                 else
1615                                 {
1616                                         client.groundAction(1, nodepos, neighbourpos, g_selected_item);
1617                                 }
1618                         }
1619                         
1620                         nodepos_old = nodepos;
1621                 }
1622                 else{
1623                 }
1624
1625                 } // selected_object == NULL
1626                 
1627                 input->resetLeftClicked();
1628                 input->resetRightClicked();
1629                 
1630                 if(input->getLeftReleased())
1631                 {
1632                         std::cout<<DTIME<<"Left button released (stopped digging)"
1633                                         <<std::endl;
1634                         client.groundAction(2, v3s16(0,0,0), v3s16(0,0,0), 0);
1635                 }
1636                 if(input->getRightReleased())
1637                 {
1638                         //std::cout<<DTIME<<"Right released"<<std::endl;
1639                         // Nothing here
1640                 }
1641                 
1642                 input->resetLeftReleased();
1643                 input->resetRightReleased();
1644                 
1645                 /*
1646                         Calculate stuff for drawing
1647                 */
1648
1649                 camera->setAspectRatio((f32)screensize.X / (f32)screensize.Y);
1650                 
1651                 u32 daynight_ratio = client.getDayNightRatio();
1652                 u8 l = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
1653                 video::SColor bgcolor = video::SColor(
1654                                 255,
1655                                 skycolor.getRed() * l / 255,
1656                                 skycolor.getGreen() * l / 255,
1657                                 skycolor.getBlue() * l / 255);
1658
1659                 /*
1660                         Fog
1661                 */
1662                 
1663                 if(g_settings.getBool("enable_fog") == true)
1664                 {
1665                         //f32 range = draw_control.wanted_range * BS + MAP_BLOCKSIZE/2*BS;
1666                         f32 range = draw_control.wanted_range * BS + 0.8*MAP_BLOCKSIZE*BS;
1667                         //f32 range = draw_control.wanted_range * BS + 0.0*MAP_BLOCKSIZE*BS;
1668                         if(draw_control.range_all)
1669                                 range = 100000*BS;
1670
1671                         driver->setFog(
1672                                 bgcolor,
1673                                 video::EFT_FOG_LINEAR,
1674                                 range*0.4,
1675                                 range*1.0,
1676                                 0.01,
1677                                 false, // pixel fog
1678                                 false // range fog
1679                         );
1680                 }
1681                 else
1682                 {
1683                         driver->setFog(
1684                                 bgcolor,
1685                                 video::EFT_FOG_LINEAR,
1686                                 100000*BS,
1687                                 110000*BS,
1688                                 0.01,
1689                                 false, // pixel fog
1690                                 false // range fog
1691                         );
1692                 }
1693
1694
1695                 /*
1696                         Update gui stuff (0ms)
1697                 */
1698
1699                 //TimeTaker guiupdatetimer("Gui updating");
1700                 
1701                 {
1702                         static float drawtime_avg = 0;
1703                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
1704                         static float beginscenetime_avg = 0;
1705                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
1706                         static float scenetime_avg = 0;
1707                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
1708                         static float endscenetime_avg = 0;
1709                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;
1710                         
1711                         char temptext[300];
1712                         snprintf(temptext, 300, "Minetest-c55 %s ("
1713                                         "R: range_all=%i"
1714                                         ")"
1715                                         " drawtime=%.0f, beginscenetime=%.0f"
1716                                         ", scenetime=%.0f, endscenetime=%.0f",
1717                                         VERSION_STRING,
1718                                         draw_control.range_all,
1719                                         drawtime_avg,
1720                                         beginscenetime_avg,
1721                                         scenetime_avg,
1722                                         endscenetime_avg
1723                                         );
1724                         
1725                         guitext->setText(narrow_to_wide(temptext).c_str());
1726                 }
1727                 
1728                 {
1729                         char temptext[300];
1730                         snprintf(temptext, 300,
1731                                         "(% .1f, % .1f, % .1f)"
1732                                         " (% .3f < btime_jitter < % .3f"
1733                                         ", dtime_jitter = % .1f %%"
1734                                         ", v_range = %.1f)",
1735                                         player_position.X/BS,
1736                                         player_position.Y/BS,
1737                                         player_position.Z/BS,
1738                                         busytime_jitter1_min_sample,
1739                                         busytime_jitter1_max_sample,
1740                                         dtime_jitter1_max_fraction * 100.0,
1741                                         draw_control.wanted_range
1742                                         );
1743
1744                         guitext2->setText(narrow_to_wide(temptext).c_str());
1745                 }
1746                 
1747                 {
1748                         guitext_info->setText(infotext.c_str());
1749                 }
1750                 
1751                 /*
1752                         Get chat messages from client
1753                 */
1754                 {
1755                         // Get new messages
1756                         std::wstring message;
1757                         while(client.getChatMessage(message))
1758                         {
1759                                 chat_lines.push_back(ChatLine(message));
1760                                 /*if(chat_lines.size() > 6)
1761                                 {
1762                                         core::list<ChatLine>::Iterator
1763                                                         i = chat_lines.begin();
1764                                         chat_lines.erase(i);
1765                                 }*/
1766                         }
1767                         // Append them to form the whole static text and throw
1768                         // it to the gui element
1769                         std::wstring whole;
1770                         // This will correspond to the line number counted from
1771                         // top to bottom, from size-1 to 0
1772                         s16 line_number = chat_lines.size();
1773                         // Count of messages to be removed from the top
1774                         u16 to_be_removed_count = 0;
1775                         for(core::list<ChatLine>::Iterator
1776                                         i = chat_lines.begin();
1777                                         i != chat_lines.end(); i++)
1778                         {
1779                                 // After this, line number is valid for this loop
1780                                 line_number--;
1781                                 // Increment age
1782                                 (*i).age += dtime;
1783                                 /*
1784                                         This results in a maximum age of 60*6 to the
1785                                         lowermost line and a maximum of 6 lines
1786                                 */
1787                                 float allowed_age = (6-line_number) * 60.0;
1788
1789                                 if((*i).age > allowed_age)
1790                                 {
1791                                         to_be_removed_count++;
1792                                         continue;
1793                                 }
1794                                 whole += (*i).text + L'\n';
1795                         }
1796                         for(u16 i=0; i<to_be_removed_count; i++)
1797                         {
1798                                 core::list<ChatLine>::Iterator
1799                                                 it = chat_lines.begin();
1800                                 chat_lines.erase(it);
1801                         }
1802                         guitext_chat->setText(whole.c_str());
1803
1804                         // Update gui element size and position
1805
1806                         /*core::rect<s32> rect(
1807                                         10,
1808                                         screensize.Y - guitext_chat_pad_bottom
1809                                                         - text_height*chat_lines.size(),
1810                                         screensize.X - 10,
1811                                         screensize.Y - guitext_chat_pad_bottom
1812                         );*/
1813                         core::rect<s32> rect(
1814                                         10,
1815                                         50,
1816                                         screensize.X - 10,
1817                                         50 + text_height*chat_lines.size()
1818                         );
1819
1820                         guitext_chat->setRelativePosition(rect);
1821
1822                         if(chat_lines.size() == 0)
1823                                 guitext_chat->setVisible(false);
1824                         else
1825                                 guitext_chat->setVisible(true);
1826                 }
1827
1828                 /*
1829                         Inventory
1830                 */
1831                 
1832                 static u16 old_selected_item = 65535;
1833                 if(client.getLocalInventoryUpdated()
1834                                 || g_selected_item != old_selected_item)
1835                 {
1836                         old_selected_item = g_selected_item;
1837                         //std::cout<<"Updating local inventory"<<std::endl;
1838                         client.getLocalInventory(local_inventory);
1839                 }
1840                 
1841                 /*
1842                         Send actions returned by the inventory menu
1843                 */
1844                 while(inventory_action_queue.size() != 0)
1845                 {
1846                         InventoryAction *a = inventory_action_queue.pop_front();
1847
1848                         client.sendInventoryAction(a);
1849                         // Eat it
1850                         delete a;
1851                 }
1852
1853                 /*
1854                         Drawing begins
1855                 */
1856
1857                 TimeTaker drawtimer("Drawing");
1858
1859                 
1860                 {
1861                         TimeTaker timer("beginScene");
1862                         driver->beginScene(true, true, bgcolor);
1863                         //driver->beginScene(false, true, bgcolor);
1864                         beginscenetime = timer.stop(true);
1865                 }
1866
1867                 //timer3.stop();
1868                 
1869                 //std::cout<<DTIME<<"smgr->drawAll()"<<std::endl;
1870                 
1871                 {
1872                         TimeTaker timer("smgr");
1873                         smgr->drawAll();
1874                         scenetime = timer.stop(true);
1875                 }
1876                 
1877                 {
1878                 //TimeTaker timer9("auxiliary drawings");
1879                 // 0ms
1880                 
1881                 //timer9.stop();
1882                 //TimeTaker //timer10("//timer10");
1883                 
1884                 video::SMaterial m;
1885                 //m.Thickness = 10;
1886                 m.Thickness = 3;
1887                 m.Lighting = false;
1888                 driver->setMaterial(m);
1889
1890                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
1891
1892                 for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin();
1893                                 i != hilightboxes.end(); i++)
1894                 {
1895                         /*std::cout<<"hilightbox min="
1896                                         <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
1897                                         <<" max="
1898                                         <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
1899                                         <<std::endl;*/
1900                         driver->draw3DBox(*i, video::SColor(255,0,0,0));
1901                 }
1902
1903                 /*
1904                         Frametime log
1905                 */
1906                 if(g_settings.getBool("frametime_graph") == true)
1907                 {
1908                         s32 x = 10;
1909                         for(core::list<float>::Iterator
1910                                         i = frametime_log.begin();
1911                                         i != frametime_log.end();
1912                                         i++)
1913                         {
1914                                 driver->draw2DLine(v2s32(x,50),
1915                                                 v2s32(x,50+(*i)*1000),
1916                                                 video::SColor(255,255,255,255));
1917                                 x++;
1918                         }
1919                 }
1920
1921                 /*
1922                         Draw crosshair
1923                 */
1924                 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
1925                                 displaycenter + core::vector2d<s32>(10,0),
1926                                 video::SColor(255,255,255,255));
1927                 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
1928                                 displaycenter + core::vector2d<s32>(0,10),
1929                                 video::SColor(255,255,255,255));
1930
1931                 } // timer
1932
1933                 //timer10.stop();
1934                 //TimeTaker //timer11("//timer11");
1935
1936                 /*
1937                         Draw gui
1938                 */
1939                 // 0-1ms
1940                 guienv->drawAll();
1941
1942                 /*
1943                         Draw hotbar
1944                 */
1945                 {
1946                         draw_hotbar(driver, font, v2s32(displaycenter.X, screensize.Y),
1947                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
1948                                         client.getHP());
1949                 }
1950
1951                 /*
1952                         Damage flash
1953                 */
1954                 if(damage_flash_timer > 0.0)
1955                 {
1956                         damage_flash_timer -= dtime;
1957                         
1958                         video::SColor color(128,255,0,0);
1959                         driver->draw2DRectangle(color,
1960                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
1961                                         NULL);
1962                 }
1963                 
1964                 /*
1965                         End scene
1966                 */
1967                 {
1968                         TimeTaker timer("endScene");
1969                         driver->endScene();
1970                         endscenetime = timer.stop(true);
1971                 }
1972
1973                 drawtime = drawtimer.stop(true);
1974
1975                 /*
1976                         End of drawing
1977                 */
1978
1979                 static s16 lastFPS = 0;
1980                 //u16 fps = driver->getFPS();
1981                 u16 fps = (1.0/dtime_avg1);
1982
1983                 if (lastFPS != fps)
1984                 {
1985                         core::stringw str = L"Minetest [";
1986                         str += driver->getName();
1987                         str += "] FPS:";
1988                         str += fps;
1989
1990                         device->setWindowCaption(str.c_str());
1991                         lastFPS = fps;
1992                 }
1993         }
1994 }
1995
1996