3 Copyright (C) 2011 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
20 #include "common_irrlicht.h"
24 #include "guiPauseMenu.h"
25 #include "guiInventoryMenu.h"
26 #include "guiTextInputMenu.h"
27 #include "guiFurnaceMenu.h"
28 #include "materials.h"
31 Setting this to 1 enables a special camera mode that forces
32 the renderers to think that the camera statically points from
33 the starting place to a static direction.
35 This allows one to move around with the player and see what
36 is actually drawn behind solid things and behind the player.
38 #define FIELD_OF_VIEW_TEST 0
41 MapDrawControl draw_control;
50 ChatLine(const std::wstring &a_text):
63 // Inventory actions from the menu are buffered here before sending
64 Queue<InventoryAction*> inventory_action_queue;
65 // This is a copy of the inventory that the client's environment has
66 Inventory local_inventory;
68 u16 g_selected_item = 0;
74 struct TextDestSign : public TextDest
76 TextDestSign(v3s16 blockpos, s16 id, Client *client)
78 m_blockpos = blockpos;
82 void gotText(std::wstring text)
84 std::string ntext = wide_to_narrow(text);
85 dstream<<"Changing text of a sign object: "
87 m_client->sendSignText(m_blockpos, m_id, ntext);
95 struct TextDestChat : public TextDest
97 TextDestChat(Client *client)
101 void gotText(std::wstring text)
103 // Discard empty line
107 // Parse command (server command starts with "/#")
108 if(text[0] == L'/' && text[1] != L'#')
110 std::wstring reply = L"Local: ";
112 reply += L"Local commands not yet supported. "
113 L"Server prefix is \"/#\".";
115 m_client->addChatMessage(reply);
120 m_client->sendChatMessage(text);
122 m_client->addChatMessage(text);
128 struct TextDestSignNode : public TextDest
130 TextDestSignNode(v3s16 p, Client *client)
135 void gotText(std::wstring text)
137 std::string ntext = wide_to_narrow(text);
138 dstream<<"Changing text of a sign node: "
140 m_client->sendSignNodeText(m_p, ntext);
148 Render distance feedback loop
150 void updateViewingRange(f32 frametime_in, Client *client)
152 if(draw_control.range_all == true)
155 static f32 added_frametime = 0;
156 static s16 added_frames = 0;
158 added_frametime += frametime_in;
161 // Actually this counter kind of sucks because frametime is busytime
162 static f32 counter = 0;
163 counter -= frametime_in;
169 /*dstream<<__FUNCTION_NAME
170 <<": Collected "<<added_frames<<" frames, total of "
171 <<added_frametime<<"s."<<std::endl;*/
173 /*dstream<<"draw_control.blocks_drawn="
174 <<draw_control.blocks_drawn
175 <<", draw_control.blocks_would_have_drawn="
176 <<draw_control.blocks_would_have_drawn
179 float range_min = g_settings.getS16("viewing_range_nodes_min");
180 float range_max = g_settings.getS16("viewing_range_nodes_max");
182 draw_control.wanted_min_range = range_min;
183 draw_control.wanted_max_blocks = (1.2*draw_control.blocks_drawn)+1;
185 float block_draw_ratio = 1.0;
186 if(draw_control.blocks_would_have_drawn != 0)
188 block_draw_ratio = (float)draw_control.blocks_drawn
189 / (float)draw_control.blocks_would_have_drawn;
192 // Calculate the average frametime in the case that all wanted
193 // blocks had been drawn
194 f32 frametime = added_frametime / added_frames / block_draw_ratio;
196 added_frametime = 0.0;
199 float wanted_fps = g_settings.getFloat("wanted_fps");
200 float wanted_frametime = 1.0 / wanted_fps;
202 f32 wanted_frametime_change = wanted_frametime - frametime;
203 //dstream<<"wanted_frametime_change="<<wanted_frametime_change<<std::endl;
205 // If needed frametime change is small, just return
206 if(fabs(wanted_frametime_change) < wanted_frametime*0.4)
208 //dstream<<"ignoring small wanted_frametime_change"<<std::endl;
212 float range = draw_control.wanted_range;
213 float new_range = range;
215 static s16 range_old = 0;
216 static f32 frametime_old = 0;
218 float d_range = range - range_old;
219 f32 d_frametime = frametime - frametime_old;
220 // A sane default of 30ms per 50 nodes of range
221 static f32 time_per_range = 30. / 50;
224 time_per_range = d_frametime / d_range;
227 // The minimum allowed calculated frametime-range derivative:
228 // Practically this sets the maximum speed of changing the range.
229 // The lower this value, the higher the maximum changing speed.
230 // A low value here results in wobbly range (0.001)
231 // A high value here results in slow changing range (0.0025)
232 // SUGG: This could be dynamically adjusted so that when
233 // the camera is turning, this is lower
234 //float min_time_per_range = 0.0015;
235 float min_time_per_range = 0.0010;
236 //float min_time_per_range = 0.05 / range;
237 if(time_per_range < min_time_per_range)
239 time_per_range = min_time_per_range;
240 //dstream<<"time_per_range="<<time_per_range<<" (min)"<<std::endl;
244 //dstream<<"time_per_range="<<time_per_range<<std::endl;
247 f32 wanted_range_change = wanted_frametime_change / time_per_range;
248 // Dampen the change a bit to kill oscillations
249 //wanted_range_change *= 0.9;
250 //wanted_range_change *= 0.75;
251 wanted_range_change *= 0.5;
252 //dstream<<"wanted_range_change="<<wanted_range_change<<std::endl;
254 // If needed range change is very small, just return
255 if(fabs(wanted_range_change) < 0.001)
257 //dstream<<"ignoring small wanted_range_change"<<std::endl;
261 new_range += wanted_range_change;
262 //dstream<<"new_range="<<new_range/*<<std::endl*/;
264 //float new_range_unclamped = new_range;
265 if(new_range < range_min)
266 new_range = range_min;
267 if(new_range > range_max)
268 new_range = range_max;
270 /*if(new_range != new_range_unclamped)
271 dstream<<", clamped to "<<new_range<<std::endl;
273 dstream<<std::endl;*/
275 draw_control.wanted_range = new_range;
277 range_old = new_range;
278 frametime_old = frametime;
284 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
285 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
286 Inventory *inventory, s32 halfheartcount)
288 InventoryList *mainlist = inventory->getList("main");
291 dstream<<"WARNING: draw_hotbar(): mainlist == NULL"<<std::endl;
295 s32 padding = imgsize/12;
296 //s32 height = imgsize + padding*2;
297 s32 width = itemcount*(imgsize+padding*2);
299 // Position of upper left corner of bar
300 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
302 // Draw background color
303 /*core::rect<s32> barrect(0,0,width,height);
305 video::SColor bgcolor(255,128,128,128);
306 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
308 core::rect<s32> imgrect(0,0,imgsize,imgsize);
310 for(s32 i=0; i<itemcount; i++)
312 InventoryItem *item = mainlist->getItem(i);
314 core::rect<s32> rect = imgrect + pos
315 + v2s32(padding+i*(imgsize+padding*2), padding);
317 if(g_selected_item == i)
319 driver->draw2DRectangle(video::SColor(255,255,0,0),
320 core::rect<s32>(rect.UpperLeftCorner - v2s32(1,1)*padding,
321 rect.LowerRightCorner + v2s32(1,1)*padding),
326 video::SColor bgcolor2(128,0,0,0);
327 driver->draw2DRectangle(bgcolor2, rect, NULL);
332 drawInventoryItem(driver, font, item, rect, NULL);
340 video::ITexture *heart_texture =
341 driver->getTexture(porting::getDataPath("heart.png").c_str());
342 v2s32 p = pos + v2s32(0, -20);
343 for(s32 i=0; i<halfheartcount/2; i++)
345 const video::SColor color(255,255,255,255);
346 const video::SColor colors[] = {color,color,color,color};
347 core::rect<s32> rect(0,0,16,16);
349 driver->draw2DImage(heart_texture, rect,
350 core::rect<s32>(core::position2d<s32>(0,0),
351 core::dimension2di(heart_texture->getOriginalSize())),
355 if(halfheartcount % 2 == 1)
357 const video::SColor color(255,255,255,255);
358 const video::SColor colors[] = {color,color,color,color};
359 core::rect<s32> rect(0,0,16/2,16);
361 core::dimension2di srcd(heart_texture->getOriginalSize());
363 driver->draw2DImage(heart_texture, rect,
364 core::rect<s32>(core::position2d<s32>(0,0), srcd),
372 Find what the player is pointing at
374 void getPointedNode(Client *client, v3f player_position,
375 v3f camera_direction, v3f camera_position,
376 bool &nodefound, core::line3d<f32> shootline,
377 v3s16 &nodepos, v3s16 &neighbourpos,
378 core::aabbox3d<f32> &nodehilightbox,
381 f32 mindistance = BS * 1001;
383 v3s16 pos_i = floatToInt(player_position, BS);
385 /*std::cout<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
389 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
390 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
391 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
392 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
393 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
394 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
396 for(s16 y = ystart; y <= yend; y++)
397 for(s16 z = zstart; z <= zend; z++)
398 for(s16 x = xstart; x <= xend; x++)
403 n = client->getNode(v3s16(x,y,z));
404 if(content_pointable(n.d) == false)
407 catch(InvalidPositionException &e)
413 v3f npf = intToFloat(np, BS);
418 v3s16(0,0,1), // back
420 v3s16(1,0,0), // right
421 v3s16(0,0,-1), // front
422 v3s16(0,-1,0), // bottom
423 v3s16(-1,0,0), // left
429 if(n.d == CONTENT_TORCH)
431 v3s16 dir = unpackDir(n.dir);
432 v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
433 dir_f *= BS/2 - BS/6 - BS/20;
434 v3f cpf = npf + dir_f;
435 f32 distance = (cpf - camera_position).getLength();
437 core::aabbox3d<f32> box;
440 if(dir == v3s16(0,-1,0))
442 box = core::aabbox3d<f32>(
443 npf - v3f(BS/6, BS/2, BS/6),
444 npf + v3f(BS/6, -BS/2+BS/3*2, BS/6)
448 else if(dir == v3s16(0,1,0))
450 box = core::aabbox3d<f32>(
451 npf - v3f(BS/6, -BS/2+BS/3*2, BS/6),
452 npf + v3f(BS/6, BS/2, BS/6)
458 box = core::aabbox3d<f32>(
459 cpf - v3f(BS/6, BS/3, BS/6),
460 cpf + v3f(BS/6, BS/3, BS/6)
464 if(distance < mindistance)
466 if(box.intersectsWithLine(shootline))
471 mindistance = distance;
472 nodehilightbox = box;
476 else if(n.d == CONTENT_SIGN_WALL)
478 v3s16 dir = unpackDir(n.dir);
479 v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
480 dir_f *= BS/2 - BS/6 - BS/20;
481 v3f cpf = npf + dir_f;
482 f32 distance = (cpf - camera_position).getLength();
486 v3f(BS*0.42,-BS*0.35,-BS*0.4),
487 v3f(BS*0.49, BS*0.35, BS*0.4),
490 for(s32 i=0; i<2; i++)
492 if(dir == v3s16(1,0,0))
493 vertices[i].rotateXZBy(0);
494 if(dir == v3s16(-1,0,0))
495 vertices[i].rotateXZBy(180);
496 if(dir == v3s16(0,0,1))
497 vertices[i].rotateXZBy(90);
498 if(dir == v3s16(0,0,-1))
499 vertices[i].rotateXZBy(-90);
500 if(dir == v3s16(0,-1,0))
501 vertices[i].rotateXYBy(-90);
502 if(dir == v3s16(0,1,0))
503 vertices[i].rotateXYBy(90);
508 core::aabbox3d<f32> box;
510 box = core::aabbox3d<f32>(vertices[0]);
511 box.addInternalPoint(vertices[1]);
513 if(distance < mindistance)
515 if(box.intersectsWithLine(shootline))
520 mindistance = distance;
521 nodehilightbox = box;
530 for(u16 i=0; i<6; i++)
532 v3f dir_f = v3f(dirs[i].X,
533 dirs[i].Y, dirs[i].Z);
534 v3f centerpoint = npf + dir_f * BS/2;
536 (centerpoint - camera_position).getLength();
538 if(distance < mindistance)
540 core::CMatrix4<f32> m;
541 m.buildRotateFromTo(v3f(0,0,1), dir_f);
543 // This is the back face
545 v3f(BS/2, BS/2, BS/2),
546 v3f(-BS/2, -BS/2, BS/2+d)
549 for(u16 j=0; j<2; j++)
551 m.rotateVect(corners[j]);
555 core::aabbox3d<f32> facebox(corners[0]);
556 facebox.addInternalPoint(corners[1]);
558 if(facebox.intersectsWithLine(shootline))
562 neighbourpos = np + dirs[i];
563 mindistance = distance;
565 //nodehilightbox = facebox;
567 const float d = 0.502;
568 core::aabbox3d<f32> nodebox
569 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
570 v3f nodepos_f = intToFloat(nodepos, BS);
571 nodebox.MinEdge += nodepos_f;
572 nodebox.MaxEdge += nodepos_f;
573 nodehilightbox = nodebox;
575 } // if distance < mindistance
585 IrrlichtDevice *device,
588 std::string playername,
591 std::wstring &error_message
594 video::IVideoDriver* driver = device->getVideoDriver();
595 scene::ISceneManager* smgr = device->getSceneManager();
597 v2u32 screensize(0,0);
598 v2u32 last_screensize(0,0);
599 screensize = driver->getScreenSize();
601 const s32 hotbar_itemcount = 8;
602 const s32 hotbar_imagesize = 36;
605 Draw "Loading" screen
607 const wchar_t *text = L"Loading and connecting...";
608 u32 text_height = font->getDimension(text).Height;
609 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
610 core::vector2d<s32> textsize(300, text_height);
611 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
613 gui::IGUIStaticText *gui_loadingtext = guienv->addStaticText(
614 text, textrect, false, false);
615 gui_loadingtext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
617 driver->beginScene(true, true, video::SColor(255,0,0,0));
621 std::cout<<DTIME<<"Creating server and client"<<std::endl;
625 SharedPtr will delete it when it goes out of scope.
627 SharedPtr<Server> server;
629 server = new Server(map_dir);
637 Client client(device, playername.c_str(), draw_control);
639 Address connect_address(0,0,0,0, port);
642 //connect_address.Resolve("localhost");
643 connect_address.setAddress(127,0,0,1);
645 connect_address.Resolve(address.c_str());
647 catch(ResolveError &e)
649 std::cout<<DTIME<<"Couldn't resolve address"<<std::endl;
651 error_message = L"Couldn't resolve address";
652 gui_loadingtext->remove();
657 Attempt to connect to the server
660 dstream<<DTIME<<"Connecting to server at ";
661 connect_address.print(&dstream);
663 client.connect(connect_address);
665 bool could_connect = false;
668 float time_counter = 0.0;
671 if(client.connectedAndInitialized())
673 could_connect = true;
676 // Wait for 10 seconds
677 if(time_counter >= 10.0)
683 driver->beginScene(true, true, video::SColor(255,0,0,0));
687 // Update client and server
699 catch(con::PeerNotFoundException &e)
702 if(could_connect == false)
704 std::cout<<DTIME<<"Timed out."<<std::endl;
705 error_message = L"Connection timed out.";
706 gui_loadingtext->remove();
713 /*scene::ISceneNode* skybox;
714 skybox = smgr->addSkyBoxSceneNode(
715 driver->getTexture(porting::getDataPath("skybox2.png").c_str()),
716 driver->getTexture(porting::getDataPath("skybox3.png").c_str()),
717 driver->getTexture(porting::getDataPath("skybox1.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()));*/
723 Create the camera node
726 scene::ICameraSceneNode* camera = smgr->addCameraSceneNode(
728 v3f(BS*100, BS*2, BS*100), // Look from
729 v3f(BS*100+1, BS*2, BS*100), // Look to
735 error_message = L"Failed to create the camera node";
739 //video::SColor skycolor = video::SColor(255,90,140,200);
740 //video::SColor skycolor = video::SColor(255,166,202,244);
741 //video::SColor skycolor = video::SColor(255,120,185,244);
742 video::SColor skycolor = video::SColor(255,140,186,250);
744 camera->setFOV(FOV_ANGLE);
746 // Just so big a value that everything rendered is visible
747 camera->setFarValue(100000*BS);
749 f32 camera_yaw = 0; // "right/left"
750 f32 camera_pitch = 0; // "up/down"
756 gui_loadingtext->remove();
762 // First line of debug text
763 gui::IGUIStaticText *guitext = guienv->addStaticText(
765 core::rect<s32>(5, 5, 795, 5+text_height),
767 // Second line of debug text
768 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
770 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
773 // At the middle of the screen
774 // Object infos are shown in this
775 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
777 core::rect<s32>(0,0,400,text_height+5) + v2s32(100,200),
781 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
783 core::rect<s32>(0,0,0,0),
784 false, false); // Disable word wrap as of now
786 //guitext_chat->setBackgroundColor(video::SColor(96,0,0,0));
787 core::list<ChatLine> chat_lines;
789 /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
790 (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/
791 /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
792 (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/
794 // Test the text input system
795 /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr,
797 /*GUIMessageMenu *menu =
798 new GUIMessageMenu(guienv, guiroot, -1,
804 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
805 &g_menumgr))->drop();
808 /*guitext2->setVisible(true);
809 guitext_info->setVisible(true);
810 guitext_chat->setVisible(true);*/
812 //s32 guitext_chat_pad_bottom = 70;
815 Some statistics are collected in these
818 u32 beginscenetime = 0;
820 u32 endscenetime = 0;
823 //throw con::PeerNotFoundException("lol");
825 core::list<float> frametime_log;
827 float damage_flash_timer = 0;
833 bool first_loop_after_window_activation = true;
835 // Time is in milliseconds
836 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
837 // NOTE: So we have to use getTime() and call run()s between them
838 u32 lasttime = device->getTimer()->getTime();
840 while(device->run() && kill == false)
842 if(g_gamecallback->disconnect_requested)
844 g_gamecallback->disconnect_requested = false;
849 Process TextureSource's queue
851 ((TextureSource*)g_texturesource)->processQueue();
856 last_screensize = screensize;
857 screensize = driver->getScreenSize();
858 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
859 //bool screensize_changed = screensize != last_screensize;
861 // Hilight boxes collected during the loop and displayed
862 core::list< core::aabbox3d<f32> > hilightboxes;
865 std::wstring infotext;
867 // When screen size changes, update positions and sizes of stuff
868 /*if(screensize_changed)
870 v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing);
871 quick_inventory->updatePosition(pos);
874 //TimeTaker //timer1("//timer1");
876 // Time of frame without fps limit
880 // not using getRealTime is necessary for wine
881 u32 time = device->getTimer()->getTime();
883 busytime_u32 = time - lasttime;
886 busytime = busytime_u32 / 1000.0;
889 //std::cout<<"busytime_u32="<<busytime_u32<<std::endl;
891 // Necessary for device->getTimer()->getTime()
898 updateViewingRange(busytime, &client);
905 float fps_max = g_settings.getFloat("fps_max");
906 u32 frametime_min = 1000./fps_max;
908 if(busytime_u32 < frametime_min)
910 u32 sleeptime = frametime_min - busytime_u32;
911 device->sleep(sleeptime);
915 // Necessary for device->getTimer()->getTime()
919 Time difference calculation
921 f32 dtime; // in seconds
923 u32 time = device->getTimer()->getTime();
925 dtime = (time - lasttime) / 1000.0;
931 Log frametime for visualization
933 frametime_log.push_back(dtime);
934 if(frametime_log.size() > 100)
936 core::list<float>::Iterator i = frametime_log.begin();
937 frametime_log.erase(i);
941 Visualize frametime in terminal
943 /*for(u32 i=0; i<dtime*400; i++)
945 std::cout<<std::endl;*/
948 Time average and jitter calculation
951 static f32 dtime_avg1 = 0.0;
952 dtime_avg1 = dtime_avg1 * 0.98 + dtime * 0.02;
953 f32 dtime_jitter1 = dtime - dtime_avg1;
955 static f32 dtime_jitter1_max_sample = 0.0;
956 static f32 dtime_jitter1_max_fraction = 0.0;
958 static f32 jitter1_max = 0.0;
959 static f32 counter = 0.0;
960 if(dtime_jitter1 > jitter1_max)
961 jitter1_max = dtime_jitter1;
966 dtime_jitter1_max_sample = jitter1_max;
967 dtime_jitter1_max_fraction
968 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
974 Busytime average and jitter calculation
977 static f32 busytime_avg1 = 0.0;
978 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
979 f32 busytime_jitter1 = busytime - busytime_avg1;
981 static f32 busytime_jitter1_max_sample = 0.0;
982 static f32 busytime_jitter1_min_sample = 0.0;
984 static f32 jitter1_max = 0.0;
985 static f32 jitter1_min = 0.0;
986 static f32 counter = 0.0;
987 if(busytime_jitter1 > jitter1_max)
988 jitter1_max = busytime_jitter1;
989 if(busytime_jitter1 < jitter1_min)
990 jitter1_min = busytime_jitter1;
994 busytime_jitter1_max_sample = jitter1_max;
995 busytime_jitter1_min_sample = jitter1_min;
1002 Debug info for client
1005 static float counter = 0.0;
1010 client.printDebugInfo(std::cout);
1015 Direct handling of user input
1018 // Reset input if window not active or some menu is active
1019 if(device->isWindowActive() == false || noMenuActive() == false)
1024 // Input handler step() (used by the random input generator)
1028 Launch menus according to keys
1030 if(input->wasKeyDown(irr::KEY_KEY_I))
1032 dstream<<DTIME<<"the_game: "
1033 <<"Launching inventory"<<std::endl;
1035 GUIInventoryMenu *menu =
1036 new GUIInventoryMenu(guienv, guiroot, -1,
1037 &g_menumgr, v2s16(8,7),
1038 client.getInventoryContext(),
1041 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1042 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1043 "list", "current_player", "main",
1044 v2s32(0, 3), v2s32(8, 4)));
1045 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1046 "list", "current_player", "craft",
1047 v2s32(3, 0), v2s32(3, 3)));
1048 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1049 "list", "current_player", "craftresult",
1050 v2s32(7, 1), v2s32(1, 1)));
1052 menu->setDrawSpec(draw_spec);
1056 else if(input->wasKeyDown(irr::KEY_ESCAPE))
1058 dstream<<DTIME<<"the_game: "
1059 <<"Launching pause menu"<<std::endl;
1060 // It will delete itself by itself
1061 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1062 &g_menumgr))->drop();
1064 else if(input->wasKeyDown(irr::KEY_KEY_T))
1066 TextDest *dest = new TextDestChat(&client);
1068 (new GUITextInputMenu(guienv, guiroot, -1,
1073 // Item selection with mouse wheel
1075 s32 wheel = input->getMouseWheel();
1076 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1077 hotbar_itemcount-1);
1081 if(g_selected_item < max_item)
1084 g_selected_item = 0;
1088 if(g_selected_item > 0)
1091 g_selected_item = max_item;
1096 for(u16 i=0; i<10; i++)
1098 s32 keycode = irr::KEY_KEY_1 + i;
1100 keycode = irr::KEY_KEY_0;
1101 if(input->wasKeyDown((irr::EKEY_CODE)keycode))
1103 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1105 g_selected_item = i;
1107 dstream<<DTIME<<"Selected item: "
1108 <<g_selected_item<<std::endl;
1113 // Viewing range selection
1114 if(input->wasKeyDown(irr::KEY_KEY_R))
1116 if(draw_control.range_all)
1118 draw_control.range_all = false;
1119 dstream<<DTIME<<"Disabled full viewing range"<<std::endl;
1123 draw_control.range_all = true;
1124 dstream<<DTIME<<"Enabled full viewing range"<<std::endl;
1128 // Print debug stacks
1129 if(input->wasKeyDown(irr::KEY_KEY_P))
1131 dstream<<"-----------------------------------------"
1133 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1134 dstream<<"-----------------------------------------"
1136 debug_stacks_print();
1140 Player speed control
1153 PlayerControl control(
1154 input->isKeyDown(irr::KEY_KEY_W),
1155 input->isKeyDown(irr::KEY_KEY_S),
1156 input->isKeyDown(irr::KEY_KEY_A),
1157 input->isKeyDown(irr::KEY_KEY_D),
1158 input->isKeyDown(irr::KEY_SPACE),
1159 input->isKeyDown(irr::KEY_KEY_E),
1160 input->isKeyDown(irr::KEY_LSHIFT)
1161 || input->isKeyDown(irr::KEY_RSHIFT),
1165 client.setPlayerControl(control);
1174 //TimeTaker timer("server->step(dtime)");
1175 server->step(dtime);
1183 //TimeTaker timer("client.step(dtime)");
1185 //client.step(dtime_avg1);
1188 // Read client events
1191 ClientEvent event = client.getClientEvent();
1192 if(event.type == CE_NONE)
1196 else if(event.type == CE_PLAYER_DAMAGE)
1198 //u16 damage = event.player_damage.amount;
1199 //dstream<<"Player damage: "<<damage<<std::endl;
1200 damage_flash_timer = 0.05;
1202 else if(event.type == CE_PLAYER_FORCE_MOVE)
1204 camera_yaw = event.player_force_move.yaw;
1205 camera_pitch = event.player_force_move.pitch;
1209 // Get player position
1210 v3f player_position = client.getPlayerPosition();
1212 //TimeTaker //timer2("//timer2");
1215 Mouse and camera control
1218 if((device->isWindowActive() && noMenuActive()) || random_input)
1221 device->getCursorControl()->setVisible(false);
1223 if(first_loop_after_window_activation){
1224 //std::cout<<"window active, first loop"<<std::endl;
1225 first_loop_after_window_activation = false;
1228 s32 dx = input->getMousePos().X - displaycenter.X;
1229 s32 dy = input->getMousePos().Y - displaycenter.Y;
1230 //std::cout<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1231 camera_yaw -= dx*0.2;
1232 camera_pitch += dy*0.2;
1233 if(camera_pitch < -89.5) camera_pitch = -89.5;
1234 if(camera_pitch > 89.5) camera_pitch = 89.5;
1236 input->setMousePos(displaycenter.X, displaycenter.Y);
1239 device->getCursorControl()->setVisible(true);
1241 //std::cout<<"window inactive"<<std::endl;
1242 first_loop_after_window_activation = true;
1245 camera_yaw = wrapDegrees(camera_yaw);
1246 camera_pitch = wrapDegrees(camera_pitch);
1248 v3f camera_direction = v3f(0,0,1);
1249 camera_direction.rotateYZBy(camera_pitch);
1250 camera_direction.rotateXZBy(camera_yaw);
1252 // This is at the height of the eyes of the current figure
1253 //v3f camera_position = player_position + v3f(0, BS+BS/2, 0);
1254 // This is more like in minecraft
1255 v3f camera_position = player_position + v3f(0, BS+BS*0.625, 0);
1257 camera->setPosition(camera_position);
1258 // *100.0 helps in large map coordinates
1259 camera->setTarget(camera_position + camera_direction * 100.0);
1261 if(FIELD_OF_VIEW_TEST){
1262 client.updateCamera(v3f(0,0,0), v3f(0,0,1));
1265 //TimeTaker timer("client.updateCamera");
1266 client.updateCamera(camera_position, camera_direction);
1270 //TimeTaker //timer3("//timer3");
1273 Calculate what block is the crosshair pointing to
1276 //u32 t1 = device->getTimer()->getRealTime();
1278 //f32 d = 4; // max. distance
1279 f32 d = 4; // max. distance
1280 core::line3d<f32> shootline(camera_position,
1281 camera_position + camera_direction * BS * (d+1));
1283 MapBlockObject *selected_object = client.getSelectedObject
1284 (d*BS, camera_position, shootline);
1286 ClientActiveObject *selected_active_object
1287 = client.getSelectedActiveObject
1288 (d*BS, camera_position, shootline);
1290 if(selected_object != NULL)
1292 //dstream<<"Client returned selected_object != NULL"<<std::endl;
1294 core::aabbox3d<f32> box_on_map
1295 = selected_object->getSelectionBoxOnMap();
1297 hilightboxes.push_back(box_on_map);
1299 infotext = narrow_to_wide(selected_object->infoText());
1301 if(input->getLeftClicked())
1303 std::cout<<DTIME<<"Left-clicked object"<<std::endl;
1304 client.clickObject(0, selected_object->getBlock()->getPos(),
1305 selected_object->getId(), g_selected_item);
1307 else if(input->getRightClicked())
1309 std::cout<<DTIME<<"Right-clicked object"<<std::endl;
1311 Check if we want to modify the object ourselves
1313 if(selected_object->getTypeId() == MAPBLOCKOBJECT_TYPE_SIGN)
1315 dstream<<"Sign object right-clicked"<<std::endl;
1317 if(random_input == false)
1319 // Get a new text for it
1321 TextDest *dest = new TextDestSign(
1322 selected_object->getBlock()->getPos(),
1323 selected_object->getId(),
1326 SignObject *sign_object = (SignObject*)selected_object;
1328 std::wstring wtext =
1329 narrow_to_wide(sign_object->getText());
1331 (new GUITextInputMenu(guienv, guiroot, -1,
1337 Otherwise pass the event to the server as-is
1341 client.clickObject(1, selected_object->getBlock()->getPos(),
1342 selected_object->getId(), g_selected_item);
1346 else if(selected_active_object != NULL)
1348 //dstream<<"Client returned selected_active_object != NULL"<<std::endl;
1350 core::aabbox3d<f32> *selection_box
1351 = selected_active_object->getSelectionBox();
1352 // Box should exist because object was returned in the
1354 assert(selection_box);
1356 v3f pos = selected_active_object->getPosition();
1358 core::aabbox3d<f32> box_on_map(
1359 selection_box->MinEdge + pos,
1360 selection_box->MaxEdge + pos
1363 hilightboxes.push_back(box_on_map);
1365 //infotext = narrow_to_wide("A ClientActiveObject");
1366 infotext = narrow_to_wide(selected_active_object->infoText());
1368 if(input->getLeftClicked())
1370 std::cout<<DTIME<<"Left-clicked object"<<std::endl;
1371 client.clickActiveObject(0,
1372 selected_active_object->getId(), g_selected_item);
1374 else if(input->getRightClicked())
1376 std::cout<<DTIME<<"Right-clicked object"<<std::endl;
1379 else // selected_object == NULL
1383 Find out which node we are pointing at
1386 bool nodefound = false;
1389 core::aabbox3d<f32> nodehilightbox;
1391 getPointedNode(&client, player_position,
1392 camera_direction, camera_position,
1393 nodefound, shootline,
1394 nodepos, neighbourpos,
1397 static float nodig_delay_counter = 0.0;
1401 static v3s16 nodepos_old(-32768,-32768,-32768);
1403 static float dig_time = 0.0;
1404 static u16 dig_index = 0;
1410 hilightboxes.push_back(nodehilightbox);
1413 Check information text of node
1416 NodeMetadata *meta = client.getNodeMetadata(nodepos);
1419 infotext = narrow_to_wide(meta->infoText());
1422 //MapNode node = client.getNode(nodepos);
1428 if(input->getLeftReleased())
1430 client.clearTempMod(nodepos);
1434 if(nodig_delay_counter > 0.0)
1436 nodig_delay_counter -= dtime;
1440 if(nodepos != nodepos_old)
1442 std::cout<<DTIME<<"Pointing at ("<<nodepos.X<<","
1443 <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;
1445 if(nodepos_old != v3s16(-32768,-32768,-32768))
1447 client.clearTempMod(nodepos_old);
1452 if(input->getLeftClicked() ||
1453 (input->getLeftState() && nodepos != nodepos_old))
1455 dstream<<DTIME<<"Started digging"<<std::endl;
1456 client.groundAction(0, nodepos, neighbourpos, g_selected_item);
1458 if(input->getLeftClicked())
1460 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, 0));
1462 if(input->getLeftState())
1464 MapNode n = client.getNode(nodepos);
1466 // Get tool name. Default is "" = bare hands
1467 std::string toolname = "";
1468 InventoryList *mlist = local_inventory.getList("main");
1471 InventoryItem *item = mlist->getItem(g_selected_item);
1472 if(item && (std::string)item->getName() == "ToolItem")
1474 ToolItem *titem = (ToolItem*)item;
1475 toolname = titem->getToolName();
1479 // Get digging properties for material and tool
1481 DiggingProperties prop =
1482 getDiggingProperties(material, toolname);
1484 float dig_time_complete = 0.0;
1486 if(prop.diggable == false)
1488 /*dstream<<"Material "<<(int)material
1489 <<" not diggable with \""
1490 <<toolname<<"\""<<std::endl;*/
1491 // I guess nobody will wait for this long
1492 dig_time_complete = 10000000.0;
1496 dig_time_complete = prop.time;
1499 if(dig_time_complete >= 0.001)
1501 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1502 * dig_time/dig_time_complete);
1504 // This is for torches
1507 dig_index = CRACK_ANIMATION_LENGTH;
1510 if(dig_index < CRACK_ANIMATION_LENGTH)
1512 //TimeTaker timer("client.setTempMod");
1513 //dstream<<"dig_index="<<dig_index<<std::endl;
1514 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1518 dstream<<DTIME<<"Digging completed"<<std::endl;
1519 client.groundAction(3, nodepos, neighbourpos, g_selected_item);
1520 client.clearTempMod(nodepos);
1521 client.removeNode(nodepos);
1525 nodig_delay_counter = dig_time_complete
1526 / (float)CRACK_ANIMATION_LENGTH;
1528 // We don't want a corresponding delay to
1529 // very time consuming nodes
1530 if(nodig_delay_counter > 0.5)
1532 nodig_delay_counter = 0.5;
1534 // We want a slight delay to very little
1535 // time consuming nodes
1536 float mindelay = 0.15;
1537 if(nodig_delay_counter < mindelay)
1539 nodig_delay_counter = mindelay;
1547 if(input->getRightClicked())
1549 std::cout<<DTIME<<"Ground right-clicked"<<std::endl;
1551 if(meta && meta->typeId() == CONTENT_SIGN_WALL && !random_input)
1553 dstream<<"Sign node right-clicked"<<std::endl;
1555 SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
1557 // Get a new text for it
1559 TextDest *dest = new TextDestSignNode(nodepos, &client);
1561 std::wstring wtext =
1562 narrow_to_wide(signmeta->getText());
1564 (new GUITextInputMenu(guienv, guiroot, -1,
1568 else if(meta && meta->typeId() == CONTENT_CHEST && !random_input)
1570 dstream<<"Chest node right-clicked"<<std::endl;
1572 //ChestNodeMetadata *chestmeta = (ChestNodeMetadata*)meta;
1574 std::string chest_inv_id;
1575 chest_inv_id += "nodemeta:";
1576 chest_inv_id += itos(nodepos.X);
1577 chest_inv_id += ",";
1578 chest_inv_id += itos(nodepos.Y);
1579 chest_inv_id += ",";
1580 chest_inv_id += itos(nodepos.Z);
1582 GUIInventoryMenu *menu =
1583 new GUIInventoryMenu(guienv, guiroot, -1,
1584 &g_menumgr, v2s16(8,9),
1585 client.getInventoryContext(),
1588 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1590 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1591 "list", chest_inv_id, "0",
1592 v2s32(0, 0), v2s32(8, 4)));
1593 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1594 "list", "current_player", "main",
1595 v2s32(0, 5), v2s32(8, 4)));
1597 menu->setDrawSpec(draw_spec);
1602 else if(meta && meta->typeId() == CONTENT_FURNACE && !random_input)
1604 dstream<<"Furnace node right-clicked"<<std::endl;
1606 GUIFurnaceMenu *menu =
1607 new GUIFurnaceMenu(guienv, guiroot, -1,
1608 &g_menumgr, nodepos, &client);
1615 client.groundAction(1, nodepos, neighbourpos, g_selected_item);
1619 nodepos_old = nodepos;
1624 } // selected_object == NULL
1626 input->resetLeftClicked();
1627 input->resetRightClicked();
1629 if(input->getLeftReleased())
1631 std::cout<<DTIME<<"Left button released (stopped digging)"
1633 client.groundAction(2, v3s16(0,0,0), v3s16(0,0,0), 0);
1635 if(input->getRightReleased())
1637 //std::cout<<DTIME<<"Right released"<<std::endl;
1641 input->resetLeftReleased();
1642 input->resetRightReleased();
1645 Calculate stuff for drawing
1648 camera->setAspectRatio((f32)screensize.X / (f32)screensize.Y);
1650 u32 daynight_ratio = client.getDayNightRatio();
1651 u8 l = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
1652 video::SColor bgcolor = video::SColor(
1654 skycolor.getRed() * l / 255,
1655 skycolor.getGreen() * l / 255,
1656 skycolor.getBlue() * l / 255);
1662 if(g_settings.getBool("enable_fog") == true)
1664 //f32 range = draw_control.wanted_range * BS + MAP_BLOCKSIZE/2*BS;
1665 f32 range = draw_control.wanted_range * BS + 0.8*MAP_BLOCKSIZE*BS;
1666 //f32 range = draw_control.wanted_range * BS + 0.0*MAP_BLOCKSIZE*BS;
1667 if(draw_control.range_all)
1672 video::EFT_FOG_LINEAR,
1684 video::EFT_FOG_LINEAR,
1695 Update gui stuff (0ms)
1698 //TimeTaker guiupdatetimer("Gui updating");
1701 static float drawtime_avg = 0;
1702 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
1703 static float beginscenetime_avg = 0;
1704 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
1705 static float scenetime_avg = 0;
1706 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
1707 static float endscenetime_avg = 0;
1708 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;
1711 snprintf(temptext, 300, "Minetest-c55 ("
1715 " drawtime=%.0f, beginscenetime=%.0f"
1716 ", scenetime=%.0f, endscenetime=%.0f",
1718 draw_control.range_all,
1725 guitext->setText(narrow_to_wide(temptext).c_str());
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
1744 guitext2->setText(narrow_to_wide(temptext).c_str());
1748 guitext_info->setText(infotext.c_str());
1752 Get chat messages from client
1756 std::wstring message;
1757 while(client.getChatMessage(message))
1759 chat_lines.push_back(ChatLine(message));
1760 /*if(chat_lines.size() > 6)
1762 core::list<ChatLine>::Iterator
1763 i = chat_lines.begin();
1764 chat_lines.erase(i);
1767 // Append them to form the whole static text and throw
1768 // it to the gui element
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++)
1779 // After this, line number is valid for this loop
1784 This results in a maximum age of 60*6 to the
1785 lowermost line and a maximum of 6 lines
1787 float allowed_age = (6-line_number) * 60.0;
1789 if((*i).age > allowed_age)
1791 to_be_removed_count++;
1794 whole += (*i).text + L'\n';
1796 for(u16 i=0; i<to_be_removed_count; i++)
1798 core::list<ChatLine>::Iterator
1799 it = chat_lines.begin();
1800 chat_lines.erase(it);
1802 guitext_chat->setText(whole.c_str());
1804 // Update gui element size and position
1806 /*core::rect<s32> rect(
1808 screensize.Y - guitext_chat_pad_bottom
1809 - text_height*chat_lines.size(),
1811 screensize.Y - guitext_chat_pad_bottom
1813 core::rect<s32> rect(
1817 50 + text_height*chat_lines.size()
1820 guitext_chat->setRelativePosition(rect);
1822 if(chat_lines.size() == 0)
1823 guitext_chat->setVisible(false);
1825 guitext_chat->setVisible(true);
1832 static u16 old_selected_item = 65535;
1833 if(client.getLocalInventoryUpdated()
1834 || g_selected_item != old_selected_item)
1836 old_selected_item = g_selected_item;
1837 //std::cout<<"Updating local inventory"<<std::endl;
1838 client.getLocalInventory(local_inventory);
1842 Send actions returned by the inventory menu
1844 while(inventory_action_queue.size() != 0)
1846 InventoryAction *a = inventory_action_queue.pop_front();
1848 client.sendInventoryAction(a);
1857 TimeTaker drawtimer("Drawing");
1861 TimeTaker timer("beginScene");
1862 driver->beginScene(true, true, bgcolor);
1863 //driver->beginScene(false, true, bgcolor);
1864 beginscenetime = timer.stop(true);
1869 //std::cout<<DTIME<<"smgr->drawAll()"<<std::endl;
1872 TimeTaker timer("smgr");
1874 scenetime = timer.stop(true);
1878 //TimeTaker timer9("auxiliary drawings");
1882 //TimeTaker //timer10("//timer10");
1888 driver->setMaterial(m);
1890 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
1892 for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin();
1893 i != hilightboxes.end(); i++)
1895 /*std::cout<<"hilightbox min="
1896 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
1898 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
1900 driver->draw3DBox(*i, video::SColor(255,0,0,0));
1906 if(g_settings.getBool("frametime_graph") == true)
1909 for(core::list<float>::Iterator
1910 i = frametime_log.begin();
1911 i != frametime_log.end();
1914 driver->draw2DLine(v2s32(x,50),
1915 v2s32(x,50+(*i)*1000),
1916 video::SColor(255,255,255,255));
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));
1934 //TimeTaker //timer11("//timer11");
1946 draw_hotbar(driver, font, v2s32(displaycenter.X, screensize.Y),
1947 hotbar_imagesize, hotbar_itemcount, &local_inventory,
1954 if(damage_flash_timer > 0.0)
1956 damage_flash_timer -= dtime;
1958 video::SColor color(128,255,0,0);
1959 driver->draw2DRectangle(color,
1960 core::rect<s32>(0,0,screensize.X,screensize.Y),
1968 TimeTaker timer("endScene");
1970 endscenetime = timer.stop(true);
1973 drawtime = drawtimer.stop(true);
1979 static s16 lastFPS = 0;
1980 //u16 fps = driver->getFPS();
1981 u16 fps = (1.0/dtime_avg1);
1985 core::stringw str = L"Minetest [";
1986 str += driver->getName();
1990 device->setWindowCaption(str.c_str());