3 Copyright (C) 2010-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.
21 #include "common_irrlicht.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
29 #include "guiPauseMenu.h"
30 #include "guiPasswordChange.h"
31 #include "guiInventoryMenu.h"
32 #include "guiTextInputMenu.h"
33 #include "guiDeathScreen.h"
35 #include "guiChatConsole.h"
43 #include "mainmenumanager.h"
47 // Needed for determining pointing to nodes
49 #include "nodemetadata.h"
50 #include "main.h" // For g_settings
52 #include "tile.h" // For TextureSource
53 #include "logoutputbuffer.h"
55 #include "quicktune_shortcutter.h"
56 #include "clientmap.h"
61 Setting this to 1 enables a special camera mode that forces
62 the renderers to think that the camera statically points from
63 the starting place to a static direction.
65 This allows one to move around with the player and see what
66 is actually drawn behind solid things and behind the player.
68 #define FIELD_OF_VIEW_TEST 0
75 struct TextDestChat : public TextDest
77 TextDestChat(Client *client)
81 void gotText(std::wstring text)
83 m_client->typeChatMessage(text);
89 struct TextDestNodeMetadata : public TextDest
91 TextDestNodeMetadata(v3s16 p, Client *client)
96 void gotText(std::wstring text)
98 std::string ntext = wide_to_narrow(text);
99 infostream<<"Changing text of a sign node: "
101 m_client->sendSignNodeText(m_p, ntext);
108 /* Respawn menu callback */
110 class MainRespawnInitiator: public IRespawnInitiator
113 MainRespawnInitiator(bool *active, Client *client):
114 m_active(active), m_client(client)
121 m_client->sendRespawn();
131 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
133 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
134 Inventory *inventory, s32 halfheartcount, u16 playeritem)
136 InventoryList *mainlist = inventory->getList("main");
139 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
143 s32 padding = imgsize/12;
144 //s32 height = imgsize + padding*2;
145 s32 width = itemcount*(imgsize+padding*2);
147 // Position of upper left corner of bar
148 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
150 // Draw background color
151 /*core::rect<s32> barrect(0,0,width,height);
153 video::SColor bgcolor(255,128,128,128);
154 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
156 core::rect<s32> imgrect(0,0,imgsize,imgsize);
158 for(s32 i=0; i<itemcount; i++)
160 const ItemStack &item = mainlist->getItem(i);
162 core::rect<s32> rect = imgrect + pos
163 + v2s32(padding+i*(imgsize+padding*2), padding);
167 video::SColor c_outside(255,255,0,0);
168 //video::SColor c_outside(255,0,0,0);
169 //video::SColor c_inside(255,192,192,192);
170 s32 x1 = rect.UpperLeftCorner.X;
171 s32 y1 = rect.UpperLeftCorner.Y;
172 s32 x2 = rect.LowerRightCorner.X;
173 s32 y2 = rect.LowerRightCorner.Y;
174 // Black base borders
175 driver->draw2DRectangle(c_outside,
177 v2s32(x1 - padding, y1 - padding),
178 v2s32(x2 + padding, y1)
180 driver->draw2DRectangle(c_outside,
182 v2s32(x1 - padding, y2),
183 v2s32(x2 + padding, y2 + padding)
185 driver->draw2DRectangle(c_outside,
187 v2s32(x1 - padding, y1),
190 driver->draw2DRectangle(c_outside,
193 v2s32(x2 + padding, y2)
195 /*// Light inside borders
196 driver->draw2DRectangle(c_inside,
198 v2s32(x1 - padding/2, y1 - padding/2),
199 v2s32(x2 + padding/2, y1)
201 driver->draw2DRectangle(c_inside,
203 v2s32(x1 - padding/2, y2),
204 v2s32(x2 + padding/2, y2 + padding/2)
206 driver->draw2DRectangle(c_inside,
208 v2s32(x1 - padding/2, y1),
211 driver->draw2DRectangle(c_inside,
214 v2s32(x2 + padding/2, y2)
219 video::SColor bgcolor2(128,0,0,0);
220 driver->draw2DRectangle(bgcolor2, rect, NULL);
221 drawItemStack(driver, font, item, rect, NULL, gamedef);
227 video::ITexture *heart_texture =
228 gamedef->getTextureSource()->getTextureRaw("heart.png");
231 v2s32 p = pos + v2s32(0, -20);
232 for(s32 i=0; i<halfheartcount/2; i++)
234 const video::SColor color(255,255,255,255);
235 const video::SColor colors[] = {color,color,color,color};
236 core::rect<s32> rect(0,0,16,16);
238 driver->draw2DImage(heart_texture, rect,
239 core::rect<s32>(core::position2d<s32>(0,0),
240 core::dimension2di(heart_texture->getOriginalSize())),
244 if(halfheartcount % 2 == 1)
246 const video::SColor color(255,255,255,255);
247 const video::SColor colors[] = {color,color,color,color};
248 core::rect<s32> rect(0,0,16/2,16);
250 core::dimension2di srcd(heart_texture->getOriginalSize());
252 driver->draw2DImage(heart_texture, rect,
253 core::rect<s32>(core::position2d<s32>(0,0), srcd),
261 Check if a node is pointable
263 inline bool isPointableNode(const MapNode& n,
264 Client *client, bool liquids_pointable)
266 const ContentFeatures &features = client->getNodeDefManager()->get(n);
267 return features.pointable ||
268 (liquids_pointable && features.isLiquid());
272 Find what the player is pointing at
274 PointedThing getPointedThing(Client *client, v3f player_position,
275 v3f camera_direction, v3f camera_position,
276 core::line3d<f32> shootline, f32 d,
277 bool liquids_pointable,
278 bool look_for_object,
279 core::aabbox3d<f32> &hilightbox,
280 bool &should_show_hilightbox,
281 ClientActiveObject *&selected_object)
285 hilightbox = core::aabbox3d<f32>(0,0,0,0,0,0);
286 should_show_hilightbox = false;
287 selected_object = NULL;
289 INodeDefManager *nodedef = client->getNodeDefManager();
290 ClientMap &map = client->getEnv().getClientMap();
292 // First try to find a pointed at active object
295 selected_object = client->getSelectedActiveObject(d*BS,
296 camera_position, shootline);
298 if(selected_object != NULL)
300 core::aabbox3d<f32> *selection_box
301 = selected_object->getSelectionBox();
302 // Box should exist because object was returned in the
304 assert(selection_box);
306 v3f pos = selected_object->getPosition();
308 hilightbox = core::aabbox3d<f32>(
309 selection_box->MinEdge + pos,
310 selection_box->MaxEdge + pos
313 should_show_hilightbox = selected_object->doShowSelectionBox();
315 result.type = POINTEDTHING_OBJECT;
316 result.object_id = selected_object->getId();
320 // That didn't work, try to find a pointed at node
322 f32 mindistance = BS * 1001;
324 v3s16 pos_i = floatToInt(player_position, BS);
326 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
330 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
331 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
332 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
333 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
334 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
335 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
337 for(s16 y = ystart; y <= yend; y++)
338 for(s16 z = zstart; z <= zend; z++)
339 for(s16 x = xstart; x <= xend; x++)
344 n = map.getNode(v3s16(x,y,z));
346 catch(InvalidPositionException &e)
350 if(!isPointableNode(n, client, liquids_pointable))
354 v3f npf = intToFloat(np, BS);
359 v3s16(0,0,1), // back
361 v3s16(1,0,0), // right
362 v3s16(0,0,-1), // front
363 v3s16(0,-1,0), // bottom
364 v3s16(-1,0,0), // left
367 const ContentFeatures &f = nodedef->get(n);
369 if(f.selection_box.type == NODEBOX_FIXED)
371 core::aabbox3d<f32> box = f.selection_box.fixed;
375 v3s16 facedirs[6] = {
384 core::aabbox3d<f32> faceboxes[6] = {
387 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
388 box.MinEdge.X+d, box.MaxEdge.Y, box.MaxEdge.Z
392 box.MaxEdge.X-d, box.MinEdge.Y, box.MinEdge.Z,
393 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
397 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
398 box.MaxEdge.X, box.MinEdge.Y+d, box.MaxEdge.Z
402 box.MinEdge.X, box.MaxEdge.Y-d, box.MinEdge.Z,
403 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
407 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
408 box.MaxEdge.X, box.MaxEdge.Y, box.MinEdge.Z+d
412 box.MinEdge.X, box.MinEdge.Y, box.MaxEdge.Z-d,
413 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
417 for(u16 i=0; i<6; i++)
419 v3f facedir_f(facedirs[i].X, facedirs[i].Y, facedirs[i].Z);
420 v3f centerpoint = npf + facedir_f * BS/2;
421 f32 distance = (centerpoint - camera_position).getLength();
422 if(distance >= mindistance)
424 if(!faceboxes[i].intersectsWithLine(shootline))
426 result.type = POINTEDTHING_NODE;
427 result.node_undersurface = np;
428 result.node_abovesurface = np+facedirs[i];
429 mindistance = distance;
431 should_show_hilightbox = true;
434 else if(f.selection_box.type == NODEBOX_WALLMOUNTED)
436 v3s16 dir = n.getWallMountedDir(nodedef);
437 v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
438 dir_f *= BS/2 - BS/6 - BS/20;
439 v3f cpf = npf + dir_f;
440 f32 distance = (cpf - camera_position).getLength();
442 core::aabbox3d<f32> box;
445 if(dir == v3s16(0,1,0)){
446 box = f.selection_box.wall_top;
449 else if(dir == v3s16(0,-1,0)){
450 box = f.selection_box.wall_bottom;
456 f.selection_box.wall_side.MinEdge,
457 f.selection_box.wall_side.MaxEdge
460 for(s32 i=0; i<2; i++)
462 if(dir == v3s16(-1,0,0))
463 vertices[i].rotateXZBy(0);
464 if(dir == v3s16(1,0,0))
465 vertices[i].rotateXZBy(180);
466 if(dir == v3s16(0,0,-1))
467 vertices[i].rotateXZBy(90);
468 if(dir == v3s16(0,0,1))
469 vertices[i].rotateXZBy(-90);
472 box = core::aabbox3d<f32>(vertices[0]);
473 box.addInternalPoint(vertices[1]);
479 if(distance < mindistance)
481 if(box.intersectsWithLine(shootline))
483 result.type = POINTEDTHING_NODE;
484 result.node_undersurface = np;
485 result.node_abovesurface = np;
486 mindistance = distance;
488 should_show_hilightbox = true;
492 else // NODEBOX_REGULAR
494 for(u16 i=0; i<6; i++)
496 v3f dir_f = v3f(dirs[i].X,
497 dirs[i].Y, dirs[i].Z);
498 v3f centerpoint = npf + dir_f * BS/2;
500 (centerpoint - camera_position).getLength();
502 if(distance < mindistance)
504 core::CMatrix4<f32> m;
505 m.buildRotateFromTo(v3f(0,0,1), dir_f);
507 // This is the back face
509 v3f(BS/2, BS/2, BS/2),
510 v3f(-BS/2, -BS/2, BS/2+d)
513 for(u16 j=0; j<2; j++)
515 m.rotateVect(corners[j]);
519 core::aabbox3d<f32> facebox(corners[0]);
520 facebox.addInternalPoint(corners[1]);
522 if(facebox.intersectsWithLine(shootline))
524 result.type = POINTEDTHING_NODE;
525 result.node_undersurface = np;
526 result.node_abovesurface = np + dirs[i];
527 mindistance = distance;
529 //hilightbox = facebox;
531 const float d = 0.502;
532 core::aabbox3d<f32> nodebox
533 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
534 v3f nodepos_f = intToFloat(np, BS);
535 nodebox.MinEdge += nodepos_f;
536 nodebox.MaxEdge += nodepos_f;
537 hilightbox = nodebox;
538 should_show_hilightbox = true;
540 } // if distance < mindistance
549 Draws a screen with a single text on it.
550 Text will be removed when the screen is drawn the next time.
552 /*gui::IGUIStaticText **/
553 void draw_load_screen(const std::wstring &text,
554 video::IVideoDriver* driver, gui::IGUIFont* font)
556 v2u32 screensize = driver->getScreenSize();
557 const wchar_t *loadingtext = text.c_str();
558 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
559 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
560 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
561 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
563 gui::IGUIStaticText *guitext = guienv->addStaticText(
564 loadingtext, textrect, false, false);
565 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
567 driver->beginScene(true, true, video::SColor(255,0,0,0));
576 /* Profiler display */
578 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
579 gui::IGUIFont *font, u32 text_height,
580 u32 show_profiler, u32 show_profiler_max)
582 if(show_profiler == 0)
584 guitext_profiler->setVisible(false);
589 std::ostringstream os(std::ios_base::binary);
590 g_profiler->printPage(os, show_profiler, show_profiler_max);
591 std::wstring text = narrow_to_wide(os.str());
592 guitext_profiler->setText(text.c_str());
593 guitext_profiler->setVisible(true);
595 s32 w = font->getDimension(text.c_str()).Width;
598 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
599 8+(text_height+5)*2 +
600 font->getDimension(text.c_str()).Height);
601 guitext_profiler->setRelativePosition(rect);
602 guitext_profiler->setVisible(true);
610 Profiler::GraphValues values;
616 Meta(float initial=0, video::SColor color=
617 video::SColor(255,255,255,255)):
623 std::list<Piece> m_log;
631 void put(const Profiler::GraphValues &values)
634 piece.values = values;
635 m_log.push_back(piece);
636 while(m_log.size() > m_log_max_size)
637 m_log.erase(m_log.begin());
640 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
641 gui::IGUIFont* font) const
643 std::map<std::string, Meta> m_meta;
644 for(std::list<Piece>::const_iterator k = m_log.begin();
645 k != m_log.end(); k++)
647 const Piece &piece = *k;
648 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
649 i != piece.values.end(); i++){
650 const std::string &id = i->first;
651 const float &value = i->second;
652 std::map<std::string, Meta>::iterator j =
654 if(j == m_meta.end()){
655 m_meta[id] = Meta(value);
658 if(value < j->second.min)
659 j->second.min = value;
660 if(value > j->second.max)
661 j->second.max = value;
666 static const video::SColor usable_colors[] = {
667 video::SColor(255,255,100,100),
668 video::SColor(255,90,225,90),
669 video::SColor(255,100,100,255),
670 video::SColor(255,255,150,50),
671 video::SColor(255,220,220,100)
673 static const u32 usable_colors_count =
674 sizeof(usable_colors) / sizeof(*usable_colors);
675 u32 next_color_i = 0;
676 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
677 i != m_meta.end(); i++){
678 Meta &meta = i->second;
679 video::SColor color(255,200,200,200);
680 if(next_color_i < usable_colors_count)
681 color = usable_colors[next_color_i++];
686 s32 textx = x_left + m_log_max_size + 15;
687 s32 textx2 = textx + 200 - 15;
691 u32 num_graphs = m_meta.size();
692 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
694 video::SColor bgcolor(120,0,0,0);
695 driver->draw2DRectangle(bgcolor, rect, NULL);
699 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
700 i != m_meta.end(); i++){
701 const std::string &id = i->first;
702 const Meta &meta = i->second;
704 s32 y = y_bottom - meta_i * 50;
705 float show_min = meta.min;
706 float show_max = meta.max;
707 if(show_min >= -0.0001 && show_max >= -0.0001){
708 if(show_min <= show_max * 0.5)
713 snprintf(buf, 10, "%.3g", show_max);
714 font->draw(narrow_to_wide(buf).c_str(),
715 core::rect<s32>(textx, y - graphh,
716 textx2, y - graphh + texth),
718 snprintf(buf, 10, "%.3g", show_min);
719 font->draw(narrow_to_wide(buf).c_str(),
720 core::rect<s32>(textx, y - texth,
723 font->draw(narrow_to_wide(id).c_str(),
724 core::rect<s32>(textx, y - graphh/2 - texth/2,
725 textx2, y - graphh/2 + texth/2),
728 s32 graph1h = graphh;
729 bool relativegraph = (show_min != 0 && show_min != show_max);
730 float lastscaledvalue = 0.0;
731 bool lastscaledvalue_exists = false;
732 for(std::list<Piece>::const_iterator j = m_log.begin();
733 j != m_log.end(); j++)
735 const Piece &piece = *j;
737 bool value_exists = false;
738 Profiler::GraphValues::const_iterator k =
739 piece.values.find(id);
740 if(k != piece.values.end()){
746 lastscaledvalue_exists = false;
749 float scaledvalue = 1.0;
750 if(show_max != show_min)
751 scaledvalue = (value - show_min) / (show_max - show_min);
752 if(scaledvalue == 1.0 && value == 0){
754 lastscaledvalue_exists = false;
758 if(lastscaledvalue_exists){
759 s32 ivalue1 = lastscaledvalue * graph1h;
760 s32 ivalue2 = scaledvalue * graph1h;
761 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
762 v2s32(x, graph1y - ivalue2), meta.color);
764 lastscaledvalue = scaledvalue;
765 lastscaledvalue_exists = true;
767 s32 ivalue = scaledvalue * graph1h;
768 driver->draw2DLine(v2s32(x, graph1y),
769 v2s32(x, graph1y - ivalue), meta.color);
782 IrrlichtDevice *device,
785 std::string playername,
786 std::string password,
787 std::string address, // If "", local server is used
789 std::wstring &error_message,
790 std::string configpath,
791 ChatBackend &chat_backend,
792 const SubgameSpec &gamespec, // Used for local game,
793 bool simple_singleplayer_mode
796 video::IVideoDriver* driver = device->getVideoDriver();
797 scene::ISceneManager* smgr = device->getSceneManager();
799 // Calculate text height using the font
800 u32 text_height = font->getDimension(L"Random test string").Height;
802 v2u32 screensize(0,0);
803 v2u32 last_screensize(0,0);
804 screensize = driver->getScreenSize();
806 const s32 hotbar_itemcount = 8;
807 //const s32 hotbar_imagesize = 36;
808 //const s32 hotbar_imagesize = 64;
809 s32 hotbar_imagesize = 48;
812 Draw "Loading" screen
815 draw_load_screen(L"Loading...", driver, font);
817 // Create texture source
818 IWritableTextureSource *tsrc = createTextureSource(device);
820 // These will be filled by data received from the server
821 // Create item definition manager
822 IWritableItemDefManager *itemdef = createItemDefManager();
823 // Create node definition manager
824 IWritableNodeDefManager *nodedef = createNodeDefManager();
826 // Add chat log output for errors to be shown in chat
827 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
829 // Create UI for modifying quicktune values
830 QuicktuneShortcutter quicktune;
834 SharedPtr will delete it when it goes out of scope.
836 SharedPtr<Server> server;
838 draw_load_screen(L"Creating server...", driver, font);
839 infostream<<"Creating server"<<std::endl;
840 server = new Server(map_dir, configpath, gamespec,
841 simple_singleplayer_mode);
845 do{ // Client scope (breakable do-while(0))
851 draw_load_screen(L"Creating client...", driver, font);
852 infostream<<"Creating client"<<std::endl;
854 MapDrawControl draw_control;
856 Client client(device, playername.c_str(), password, draw_control,
857 tsrc, itemdef, nodedef);
859 // Client acts as our GameDef
860 IGameDef *gamedef = &client;
862 draw_load_screen(L"Resolving address...", driver, font);
863 Address connect_address(0,0,0,0, port);
866 //connect_address.Resolve("localhost");
867 connect_address.setAddress(127,0,0,1);
869 connect_address.Resolve(address.c_str());
871 catch(ResolveError &e)
873 error_message = L"Couldn't resolve address";
874 errorstream<<wide_to_narrow(error_message)<<std::endl;
875 // Break out of client scope
880 Attempt to connect to the server
883 infostream<<"Connecting to server at ";
884 connect_address.print(&infostream);
885 infostream<<std::endl;
886 client.connect(connect_address);
889 Wait for server to accept connection
891 bool could_connect = false;
892 bool connect_aborted = false;
894 float frametime = 0.033;
895 float time_counter = 0.0;
899 // Update client and server
900 client.step(frametime);
902 server->step(frametime);
905 if(client.connectedAndInitialized()){
906 could_connect = true;
910 if(client.accessDenied()){
911 error_message = L"Access denied. Reason: "
912 +client.accessDeniedReason();
913 errorstream<<wide_to_narrow(error_message)<<std::endl;
916 if(input->wasKeyDown(EscapeKey)){
917 connect_aborted = true;
918 infostream<<"Connect aborted [Escape]"<<std::endl;
923 std::wostringstream ss;
924 ss<<L"Connecting to server... (press Escape to cancel)\n";
925 std::wstring animation = L"/-\\|";
926 ss<<animation[(int)(time_counter/0.2)%4];
927 draw_load_screen(ss.str(), driver, font);
930 sleep_ms(1000*frametime);
931 time_counter += frametime;
934 catch(con::PeerNotFoundException &e)
938 Handle failure to connect
941 if(error_message == L"" && !connect_aborted){
942 error_message = L"Connection failed";
943 errorstream<<wide_to_narrow(error_message)<<std::endl;
945 // Break out of client scope
950 Wait until content has been received
952 bool got_content = false;
953 bool content_aborted = false;
955 float frametime = 0.033;
956 float time_counter = 0.0;
960 // Update client and server
961 client.step(frametime);
963 server->step(frametime);
966 if(client.texturesReceived() &&
967 client.itemdefReceived() &&
968 client.nodedefReceived()){
973 if(!client.connectedAndInitialized()){
974 error_message = L"Client disconnected";
975 errorstream<<wide_to_narrow(error_message)<<std::endl;
978 if(input->wasKeyDown(EscapeKey)){
979 content_aborted = true;
980 infostream<<"Connect aborted [Escape]"<<std::endl;
985 std::wostringstream ss;
986 ss<<L"Waiting content... (press Escape to cancel)\n";
988 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
989 ss<<L" Item definitions\n";
990 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
991 ss<<L" Node definitions\n";
992 //ss<<(client.texturesReceived()?L"[X]":L"[ ]");
993 ss<<L"["<<(int)(client.textureReceiveProgress()*100+0.5)<<L"%] ";
996 draw_load_screen(ss.str(), driver, font);
999 sleep_ms(1000*frametime);
1000 time_counter += frametime;
1005 if(error_message == L"" && !content_aborted){
1006 error_message = L"Something failed";
1007 errorstream<<wide_to_narrow(error_message)<<std::endl;
1009 // Break out of client scope
1014 After all content has been received:
1015 Update cached textures, meshes and materials
1017 client.afterContentReceived();
1020 Create the camera node
1022 Camera camera(smgr, draw_control);
1023 if (!camera.successfullyCreated(error_message))
1026 f32 camera_yaw = 0; // "right/left"
1027 f32 camera_pitch = 0; // "up/down"
1033 Clouds *clouds = NULL;
1034 if(g_settings->getBool("enable_clouds"))
1036 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1044 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1050 FarMesh *farmesh = NULL;
1051 if(g_settings->getBool("enable_farmesh"))
1053 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1057 A copy of the local inventory
1059 Inventory local_inventory(itemdef);
1065 // First line of debug text
1066 gui::IGUIStaticText *guitext = guienv->addStaticText(
1068 core::rect<s32>(5, 5, 795, 5+text_height),
1070 // Second line of debug text
1071 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1073 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1075 // At the middle of the screen
1076 // Object infos are shown in this
1077 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1079 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1082 // Status text (displays info when showing and hiding GUI stuff, etc.)
1083 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1085 core::rect<s32>(0,0,0,0),
1087 guitext_status->setVisible(false);
1089 std::wstring statustext;
1090 float statustext_time = 0;
1093 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1095 core::rect<s32>(0,0,0,0),
1096 //false, false); // Disable word wrap as of now
1098 // Remove stale "recent" chat messages from previous connections
1099 chat_backend.clearRecentChat();
1100 // Chat backend and console
1101 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1103 // Profiler text (size is updated when text is updated)
1104 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1106 core::rect<s32>(0,0,0,0),
1108 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1109 guitext_profiler->setVisible(false);
1112 Some statistics are collected in these
1115 u32 beginscenetime = 0;
1117 u32 endscenetime = 0;
1119 float recent_turn_speed = 0.0;
1121 ProfilerGraph graph;
1122 // Initially clear the profiler
1123 Profiler::GraphValues dummyvalues;
1124 g_profiler->graphGet(dummyvalues);
1126 float nodig_delay_timer = 0.0;
1127 float dig_time = 0.0;
1129 PointedThing pointed_old;
1130 bool digging = false;
1131 bool ldown_for_dig = false;
1133 float damage_flash_timer = 0;
1134 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1136 const float object_hit_delay = 0.2;
1137 float object_hit_delay_timer = 0.0;
1138 float time_from_last_punch = 10;
1140 bool invert_mouse = g_settings->getBool("invert_mouse");
1142 bool respawn_menu_active = false;
1143 bool update_wielded_item_trigger = false;
1145 bool show_hud = true;
1146 bool show_chat = true;
1147 bool force_fog_off = false;
1148 bool disable_camera_update = false;
1149 bool show_debug = g_settings->getBool("show_debug");
1150 bool show_profiler_graph = false;
1151 u32 show_profiler = 0;
1152 u32 show_profiler_max = 3; // Number of pages
1154 float time_of_day = 0;
1155 float time_of_day_smooth = 0;
1161 bool first_loop_after_window_activation = true;
1163 // TODO: Convert the static interval timers to these
1164 // Interval limiter for profiler
1165 IntervalLimiter m_profiler_interval;
1167 // Time is in milliseconds
1168 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1169 // NOTE: So we have to use getTime() and call run()s between them
1170 u32 lasttime = device->getTimer()->getTime();
1174 if(device->run() == false || kill == true)
1177 // Time of frame without fps limit
1181 // not using getRealTime is necessary for wine
1182 u32 time = device->getTimer()->getTime();
1184 busytime_u32 = time - lasttime;
1187 busytime = busytime_u32 / 1000.0;
1190 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1192 // Necessary for device->getTimer()->getTime()
1200 float fps_max = g_settings->getFloat("fps_max");
1201 u32 frametime_min = 1000./fps_max;
1203 if(busytime_u32 < frametime_min)
1205 u32 sleeptime = frametime_min - busytime_u32;
1206 device->sleep(sleeptime);
1207 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1211 // Necessary for device->getTimer()->getTime()
1215 Time difference calculation
1217 f32 dtime; // in seconds
1219 u32 time = device->getTimer()->getTime();
1221 dtime = (time - lasttime) / 1000.0;
1226 g_profiler->graphAdd("mainloop_dtime", dtime);
1230 if(nodig_delay_timer >= 0)
1231 nodig_delay_timer -= dtime;
1232 if(object_hit_delay_timer >= 0)
1233 object_hit_delay_timer -= dtime;
1234 time_from_last_punch += dtime;
1236 g_profiler->add("Elapsed time", dtime);
1237 g_profiler->avg("FPS", 1./dtime);
1240 Time average and jitter calculation
1243 static f32 dtime_avg1 = 0.0;
1244 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1245 f32 dtime_jitter1 = dtime - dtime_avg1;
1247 static f32 dtime_jitter1_max_sample = 0.0;
1248 static f32 dtime_jitter1_max_fraction = 0.0;
1250 static f32 jitter1_max = 0.0;
1251 static f32 counter = 0.0;
1252 if(dtime_jitter1 > jitter1_max)
1253 jitter1_max = dtime_jitter1;
1258 dtime_jitter1_max_sample = jitter1_max;
1259 dtime_jitter1_max_fraction
1260 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1266 Busytime average and jitter calculation
1269 static f32 busytime_avg1 = 0.0;
1270 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1271 f32 busytime_jitter1 = busytime - busytime_avg1;
1273 static f32 busytime_jitter1_max_sample = 0.0;
1274 static f32 busytime_jitter1_min_sample = 0.0;
1276 static f32 jitter1_max = 0.0;
1277 static f32 jitter1_min = 0.0;
1278 static f32 counter = 0.0;
1279 if(busytime_jitter1 > jitter1_max)
1280 jitter1_max = busytime_jitter1;
1281 if(busytime_jitter1 < jitter1_min)
1282 jitter1_min = busytime_jitter1;
1286 busytime_jitter1_max_sample = jitter1_max;
1287 busytime_jitter1_min_sample = jitter1_min;
1294 Handle miscellaneous stuff
1297 if(client.accessDenied())
1299 error_message = L"Access denied. Reason: "
1300 +client.accessDeniedReason();
1301 errorstream<<wide_to_narrow(error_message)<<std::endl;
1305 if(g_gamecallback->disconnect_requested)
1307 g_gamecallback->disconnect_requested = false;
1311 if(g_gamecallback->changepassword_requested)
1313 (new GUIPasswordChange(guienv, guiroot, -1,
1314 &g_menumgr, &client))->drop();
1315 g_gamecallback->changepassword_requested = false;
1319 Process TextureSource's queue
1321 tsrc->processQueue();
1326 last_screensize = screensize;
1327 screensize = driver->getScreenSize();
1328 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1329 //bool screensize_changed = screensize != last_screensize;
1332 if(screensize.Y <= 800)
1333 hotbar_imagesize = 32;
1334 else if(screensize.Y <= 1280)
1335 hotbar_imagesize = 48;
1337 hotbar_imagesize = 64;
1339 // Hilight boxes collected during the loop and displayed
1340 core::list< core::aabbox3d<f32> > hilightboxes;
1343 std::wstring infotext;
1346 Debug info for client
1349 static float counter = 0.0;
1354 client.printDebugInfo(infostream);
1361 float profiler_print_interval =
1362 g_settings->getFloat("profiler_print_interval");
1363 bool print_to_log = true;
1364 if(profiler_print_interval == 0){
1365 print_to_log = false;
1366 profiler_print_interval = 5;
1368 if(m_profiler_interval.step(dtime, profiler_print_interval))
1371 infostream<<"Profiler:"<<std::endl;
1372 g_profiler->print(infostream);
1375 update_profiler_gui(guitext_profiler, font, text_height,
1376 show_profiler, show_profiler_max);
1378 g_profiler->clear();
1382 Direct handling of user input
1385 // Reset input if window not active or some menu is active
1386 if(device->isWindowActive() == false
1387 || noMenuActive() == false
1388 || guienv->hasFocus(gui_chat_console))
1393 // Input handler step() (used by the random input generator)
1397 Launch menus and trigger stuff according to keys
1399 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1401 // drop selected item
1402 IDropAction *a = new IDropAction();
1404 a->from_inv.setCurrentPlayer();
1405 a->from_list = "main";
1406 a->from_i = client.getPlayerItem();
1407 client.inventoryAction(a);
1409 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1411 infostream<<"the_game: "
1412 <<"Launching inventory"<<std::endl;
1414 GUIInventoryMenu *menu =
1415 new GUIInventoryMenu(guienv, guiroot, -1,
1416 &g_menumgr, v2s16(8,7),
1419 InventoryLocation inventoryloc;
1420 inventoryloc.setCurrentPlayer();
1422 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1423 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1424 "list", inventoryloc, "main",
1425 v2s32(0, 3), v2s32(8, 4)));
1426 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1427 "list", inventoryloc, "craft",
1428 v2s32(3, 0), v2s32(3, 3)));
1429 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1430 "list", inventoryloc, "craftpreview",
1431 v2s32(7, 1), v2s32(1, 1)));
1433 menu->setDrawSpec(draw_spec);
1437 else if(input->wasKeyDown(EscapeKey))
1439 infostream<<"the_game: "
1440 <<"Launching pause menu"<<std::endl;
1441 // It will delete itself by itself
1442 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1443 &g_menumgr, simple_singleplayer_mode))->drop();
1445 // Move mouse cursor on top of the disconnect button
1446 if(simple_singleplayer_mode)
1447 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1449 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1451 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1453 TextDest *dest = new TextDestChat(&client);
1455 (new GUITextInputMenu(guienv, guiroot, -1,
1459 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1461 TextDest *dest = new TextDestChat(&client);
1463 (new GUITextInputMenu(guienv, guiroot, -1,
1467 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1469 if (!gui_chat_console->isOpenInhibited())
1471 // Open up to over half of the screen
1472 gui_chat_console->openConsole(0.6);
1473 guienv->setFocus(gui_chat_console);
1476 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1478 if(g_settings->getBool("free_move"))
1480 g_settings->set("free_move","false");
1481 statustext = L"free_move disabled";
1482 statustext_time = 0;
1486 g_settings->set("free_move","true");
1487 statustext = L"free_move enabled";
1488 statustext_time = 0;
1491 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1493 if(g_settings->getBool("fast_move"))
1495 g_settings->set("fast_move","false");
1496 statustext = L"fast_move disabled";
1497 statustext_time = 0;
1501 g_settings->set("fast_move","true");
1502 statustext = L"fast_move enabled";
1503 statustext_time = 0;
1506 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1508 irr::video::IImage* const image = driver->createScreenShot();
1510 irr::c8 filename[256];
1511 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1512 g_settings->get("screenshot_path").c_str(),
1513 device->getTimer()->getRealTime());
1514 if (driver->writeImageToFile(image, filename)) {
1515 std::wstringstream sstr;
1516 sstr<<"Saved screenshot to '"<<filename<<"'";
1517 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1518 statustext = sstr.str();
1519 statustext_time = 0;
1521 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1526 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1528 show_hud = !show_hud;
1530 statustext = L"HUD shown";
1532 statustext = L"HUD hidden";
1533 statustext_time = 0;
1535 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1537 show_chat = !show_chat;
1539 statustext = L"Chat shown";
1541 statustext = L"Chat hidden";
1542 statustext_time = 0;
1544 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1546 force_fog_off = !force_fog_off;
1548 statustext = L"Fog disabled";
1550 statustext = L"Fog enabled";
1551 statustext_time = 0;
1553 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1555 disable_camera_update = !disable_camera_update;
1556 if(disable_camera_update)
1557 statustext = L"Camera update disabled";
1559 statustext = L"Camera update enabled";
1560 statustext_time = 0;
1562 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1564 // Initial / 3x toggle: Chat only
1565 // 1x toggle: Debug text with chat
1566 // 2x toggle: Debug text with profiler graph
1570 show_profiler_graph = false;
1571 statustext = L"Debug info shown";
1572 statustext_time = 0;
1574 else if(show_profiler_graph)
1577 show_profiler_graph = false;
1578 statustext = L"Debug info and profiler graph hidden";
1579 statustext_time = 0;
1583 show_profiler_graph = true;
1584 statustext = L"Profiler graph shown";
1585 statustext_time = 0;
1588 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1590 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1592 // FIXME: This updates the profiler with incomplete values
1593 update_profiler_gui(guitext_profiler, font, text_height,
1594 show_profiler, show_profiler_max);
1596 if(show_profiler != 0)
1598 std::wstringstream sstr;
1599 sstr<<"Profiler shown (page "<<show_profiler
1600 <<" of "<<show_profiler_max<<")";
1601 statustext = sstr.str();
1602 statustext_time = 0;
1606 statustext = L"Profiler hidden";
1607 statustext_time = 0;
1610 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1612 s16 range = g_settings->getS16("viewing_range_nodes_min");
1613 s16 range_new = range + 10;
1614 g_settings->set("viewing_range_nodes_min", itos(range_new));
1615 statustext = narrow_to_wide(
1616 "Minimum viewing range changed to "
1618 statustext_time = 0;
1620 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1622 s16 range = g_settings->getS16("viewing_range_nodes_min");
1623 s16 range_new = range - 10;
1626 g_settings->set("viewing_range_nodes_min",
1628 statustext = narrow_to_wide(
1629 "Minimum viewing range changed to "
1631 statustext_time = 0;
1634 // Handle QuicktuneShortcutter
1635 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1637 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1639 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1641 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1644 std::string msg = quicktune.getMessage();
1646 statustext = narrow_to_wide(msg);
1647 statustext_time = 0;
1651 // Item selection with mouse wheel
1652 u16 new_playeritem = client.getPlayerItem();
1654 s32 wheel = input->getMouseWheel();
1655 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1656 hotbar_itemcount-1);
1660 if(new_playeritem < max_item)
1667 if(new_playeritem > 0)
1670 new_playeritem = max_item;
1675 for(u16 i=0; i<10; i++)
1677 const KeyPress *kp = NumberKey + (i + 1) % 10;
1678 if(input->wasKeyDown(*kp))
1680 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1684 infostream<<"Selected item: "
1685 <<new_playeritem<<std::endl;
1690 // Viewing range selection
1691 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1693 draw_control.range_all = !draw_control.range_all;
1694 if(draw_control.range_all)
1696 infostream<<"Enabled full viewing range"<<std::endl;
1697 statustext = L"Enabled full viewing range";
1698 statustext_time = 0;
1702 infostream<<"Disabled full viewing range"<<std::endl;
1703 statustext = L"Disabled full viewing range";
1704 statustext_time = 0;
1708 // Print debug stacks
1709 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1711 dstream<<"-----------------------------------------"
1713 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1714 dstream<<"-----------------------------------------"
1716 debug_stacks_print();
1720 Mouse and camera control
1721 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1724 float turn_amount = 0;
1725 if((device->isWindowActive() && noMenuActive()) || random_input)
1729 // Mac OSX gets upset if this is set every frame
1730 if(device->getCursorControl()->isVisible())
1731 device->getCursorControl()->setVisible(false);
1734 if(first_loop_after_window_activation){
1735 //infostream<<"window active, first loop"<<std::endl;
1736 first_loop_after_window_activation = false;
1739 s32 dx = input->getMousePos().X - displaycenter.X;
1740 s32 dy = input->getMousePos().Y - displaycenter.Y;
1743 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1745 /*const float keyspeed = 500;
1746 if(input->isKeyDown(irr::KEY_UP))
1747 dy -= dtime * keyspeed;
1748 if(input->isKeyDown(irr::KEY_DOWN))
1749 dy += dtime * keyspeed;
1750 if(input->isKeyDown(irr::KEY_LEFT))
1751 dx -= dtime * keyspeed;
1752 if(input->isKeyDown(irr::KEY_RIGHT))
1753 dx += dtime * keyspeed;*/
1757 camera_pitch += dy*d;
1758 if(camera_pitch < -89.5) camera_pitch = -89.5;
1759 if(camera_pitch > 89.5) camera_pitch = 89.5;
1761 turn_amount = v2f(dx, dy).getLength() * d;
1763 input->setMousePos(displaycenter.X, displaycenter.Y);
1766 // Mac OSX gets upset if this is set every frame
1767 if(device->getCursorControl()->isVisible() == false)
1768 device->getCursorControl()->setVisible(true);
1770 //infostream<<"window inactive"<<std::endl;
1771 first_loop_after_window_activation = true;
1773 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1774 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1777 Player speed control
1789 PlayerControl control(
1790 input->isKeyDown(getKeySetting("keymap_forward")),
1791 input->isKeyDown(getKeySetting("keymap_backward")),
1792 input->isKeyDown(getKeySetting("keymap_left")),
1793 input->isKeyDown(getKeySetting("keymap_right")),
1794 input->isKeyDown(getKeySetting("keymap_jump")),
1795 input->isKeyDown(getKeySetting("keymap_special1")),
1796 input->isKeyDown(getKeySetting("keymap_sneak")),
1800 client.setPlayerControl(control);
1809 //TimeTaker timer("server->step(dtime)");
1810 server->step(dtime);
1818 //TimeTaker timer("client.step(dtime)");
1820 //client.step(dtime_avg1);
1824 // Read client events
1827 ClientEvent event = client.getClientEvent();
1828 if(event.type == CE_NONE)
1832 else if(event.type == CE_PLAYER_DAMAGE)
1834 //u16 damage = event.player_damage.amount;
1835 //infostream<<"Player damage: "<<damage<<std::endl;
1836 damage_flash_timer = 0.05;
1837 if(event.player_damage.amount >= 2){
1838 damage_flash_timer += 0.05 * event.player_damage.amount;
1841 else if(event.type == CE_PLAYER_FORCE_MOVE)
1843 camera_yaw = event.player_force_move.yaw;
1844 camera_pitch = event.player_force_move.pitch;
1846 else if(event.type == CE_DEATHSCREEN)
1848 if(respawn_menu_active)
1851 /*bool set_camera_point_target =
1852 event.deathscreen.set_camera_point_target;
1853 v3f camera_point_target;
1854 camera_point_target.X = event.deathscreen.camera_point_target_x;
1855 camera_point_target.Y = event.deathscreen.camera_point_target_y;
1856 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1857 MainRespawnInitiator *respawner =
1858 new MainRespawnInitiator(
1859 &respawn_menu_active, &client);
1860 GUIDeathScreen *menu =
1861 new GUIDeathScreen(guienv, guiroot, -1,
1862 &g_menumgr, respawner);
1865 chat_backend.addMessage(L"", L"You died.");
1867 /* Handle visualization */
1869 damage_flash_timer = 0;
1871 /*LocalPlayer* player = client.getLocalPlayer();
1872 player->setPosition(player->getPosition() + v3f(0,-BS,0));
1873 camera.update(player, busytime, screensize);*/
1875 else if(event.type == CE_TEXTURES_UPDATED)
1877 update_wielded_item_trigger = true;
1882 //TimeTaker //timer2("//timer2");
1885 For interaction purposes, get info about the held item
1887 - Is it a usable item?
1888 - Can it point to liquids?
1890 ItemStack playeritem;
1891 bool playeritem_usable = false;
1892 bool playeritem_liquids_pointable = false;
1894 InventoryList *mlist = local_inventory.getList("main");
1897 playeritem = mlist->getItem(client.getPlayerItem());
1898 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1899 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1902 ToolCapabilities playeritem_toolcap =
1903 playeritem.getToolCapabilities(itemdef);
1909 LocalPlayer* player = client.getEnv().getLocalPlayer();
1910 float full_punch_interval = playeritem_toolcap.full_punch_interval;
1911 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
1912 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
1913 camera.update(player, busytime, screensize, tool_reload_ratio);
1916 v3f player_position = player->getPosition();
1917 v3f camera_position = camera.getPosition();
1918 v3f camera_direction = camera.getDirection();
1919 f32 camera_fov = camera.getFovMax();
1921 if(!disable_camera_update){
1922 client.getEnv().getClientMap().updateCamera(camera_position,
1923 camera_direction, camera_fov);
1927 //TimeTaker //timer3("//timer3");
1930 Calculate what block is the crosshair pointing to
1933 //u32 t1 = device->getTimer()->getRealTime();
1935 f32 d = 4; // max. distance
1936 core::line3d<f32> shootline(camera_position,
1937 camera_position + camera_direction * BS * (d+1));
1939 core::aabbox3d<f32> hilightbox;
1940 bool should_show_hilightbox = false;
1941 ClientActiveObject *selected_object = NULL;
1943 PointedThing pointed = getPointedThing(
1945 &client, player_position, camera_direction,
1946 camera_position, shootline, d,
1947 playeritem_liquids_pointable, !ldown_for_dig,
1949 hilightbox, should_show_hilightbox,
1952 if(pointed != pointed_old)
1954 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
1955 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
1961 if(should_show_hilightbox)
1962 hilightboxes.push_back(hilightbox);
1966 - releasing left mouse button
1967 - pointing away from node
1971 if(input->getLeftReleased())
1973 infostream<<"Left button released"
1974 <<" (stopped digging)"<<std::endl;
1977 else if(pointed != pointed_old)
1979 if (pointed.type == POINTEDTHING_NODE
1980 && pointed_old.type == POINTEDTHING_NODE
1981 && pointed.node_undersurface == pointed_old.node_undersurface)
1983 // Still pointing to the same node,
1984 // but a different face. Don't reset.
1988 infostream<<"Pointing away from node"
1989 <<" (stopped digging)"<<std::endl;
1995 client.interact(1, pointed_old);
1996 client.setCrack(-1, v3s16(0,0,0));
2000 if(!digging && ldown_for_dig && !input->getLeftState())
2002 ldown_for_dig = false;
2005 bool left_punch = false;
2007 if(playeritem_usable && input->getLeftState())
2009 if(input->getLeftClicked())
2010 client.interact(4, pointed);
2012 else if(pointed.type == POINTEDTHING_NODE)
2014 v3s16 nodepos = pointed.node_undersurface;
2015 v3s16 neighbourpos = pointed.node_abovesurface;
2018 Check information text of node
2021 ClientMap &map = client.getEnv().getClientMap();
2022 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2024 infotext = narrow_to_wide(meta->infoText());
2026 MapNode n = map.getNode(nodepos);
2027 if(nodedef->get(n).tname_tiles[0] == "unknown_block.png"){
2028 infotext = L"Unknown node: ";
2029 infotext += narrow_to_wide(nodedef->get(n).name);
2037 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2041 infostream<<"Started digging"<<std::endl;
2042 client.interact(0, pointed);
2044 ldown_for_dig = true;
2046 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2048 // Get digging parameters
2049 DigParams params = getDigParams(nodedef->get(n).groups,
2050 &playeritem_toolcap);
2051 // If can't dig, try hand
2052 if(!params.diggable){
2053 const ItemDefinition &hand = itemdef->get("");
2054 const ToolCapabilities *tp = hand.tool_capabilities;
2056 params = getDigParams(nodedef->get(n).groups, tp);
2059 float dig_time_complete = 0.0;
2061 if(params.diggable == false)
2063 // I guess nobody will wait for this long
2064 dig_time_complete = 10000000.0;
2068 dig_time_complete = params.time;
2071 if(dig_time_complete >= 0.001)
2073 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
2074 * dig_time/dig_time_complete);
2076 // This is for torches
2079 dig_index = CRACK_ANIMATION_LENGTH;
2082 // Don't show cracks if not diggable
2083 if(dig_time_complete >= 100000.0)
2086 else if(dig_index < CRACK_ANIMATION_LENGTH)
2088 //TimeTaker timer("client.setTempMod");
2089 //infostream<<"dig_index="<<dig_index<<std::endl;
2090 client.setCrack(dig_index, nodepos);
2094 infostream<<"Digging completed"<<std::endl;
2095 client.interact(2, pointed);
2096 client.setCrack(-1, v3s16(0,0,0));
2097 client.removeNode(nodepos);
2102 nodig_delay_timer = dig_time_complete
2103 / (float)CRACK_ANIMATION_LENGTH;
2105 // We don't want a corresponding delay to
2106 // very time consuming nodes
2107 if(nodig_delay_timer > 0.5)
2109 nodig_delay_timer = 0.5;
2111 // We want a slight delay to very little
2112 // time consuming nodes
2113 float mindelay = 0.15;
2114 if(nodig_delay_timer < mindelay)
2116 nodig_delay_timer = mindelay;
2122 camera.setDigging(0); // left click animation
2125 if(input->getRightClicked())
2127 infostream<<"Ground right-clicked"<<std::endl;
2129 // If metadata provides an inventory view, activate it
2130 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
2132 infostream<<"Launching custom inventory view"<<std::endl;
2134 InventoryLocation inventoryloc;
2135 inventoryloc.setNodeMeta(nodepos);
2142 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
2144 GUIInventoryMenu::makeDrawSpecArrayFromString(
2146 meta->getInventoryDrawSpecString(),
2149 GUIInventoryMenu *menu =
2150 new GUIInventoryMenu(guienv, guiroot, -1,
2151 &g_menumgr, invsize,
2153 menu->setDrawSpec(draw_spec);
2156 // If metadata provides text input, activate text input
2157 else if(meta && meta->allowsTextInput() && !random_input)
2159 infostream<<"Launching metadata text input"<<std::endl;
2161 // Get a new text for it
2163 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2165 std::wstring wtext = narrow_to_wide(meta->getText());
2167 (new GUITextInputMenu(guienv, guiroot, -1,
2171 // Otherwise report right click to server
2174 client.interact(3, pointed);
2175 camera.setDigging(1); // right click animation
2179 else if(pointed.type == POINTEDTHING_OBJECT)
2181 infotext = narrow_to_wide(selected_object->infoText());
2183 if(infotext == L"" && show_debug){
2184 infotext = narrow_to_wide(selected_object->debugInfoText());
2187 //if(input->getLeftClicked())
2188 if(input->getLeftState())
2190 bool do_punch = false;
2191 bool do_punch_damage = false;
2192 if(object_hit_delay_timer <= 0.0){
2194 do_punch_damage = true;
2195 object_hit_delay_timer = object_hit_delay;
2197 if(input->getLeftClicked()){
2201 infostream<<"Left-clicked object"<<std::endl;
2204 if(do_punch_damage){
2205 // Report direct punch
2206 v3f objpos = selected_object->getPosition();
2207 v3f dir = (objpos - player_position).normalize();
2209 bool disable_send = selected_object->directReportPunch(
2210 dir, &playeritem, time_from_last_punch);
2211 time_from_last_punch = 0;
2213 client.interact(0, pointed);
2216 else if(input->getRightClicked())
2218 infostream<<"Right-clicked object"<<std::endl;
2219 client.interact(3, pointed); // place
2222 else if(input->getLeftState())
2224 // When button is held down in air, show continuous animation
2228 pointed_old = pointed;
2230 if(left_punch || input->getLeftClicked())
2232 camera.setDigging(0); // left click animation
2235 input->resetLeftClicked();
2236 input->resetRightClicked();
2238 input->resetLeftReleased();
2239 input->resetRightReleased();
2242 Calculate stuff for drawing
2252 fog_range = BS*farmesh_range;
2256 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2258 if(draw_control.range_all)
2259 fog_range = 100000*BS;
2263 Calculate general brightness
2265 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2266 float time_brightness = (float)decode_light(
2267 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2268 float direct_brightness = 0;
2269 bool sunlight_seen = false;
2270 if(g_settings->getBool("free_move")){
2271 direct_brightness = time_brightness;
2272 sunlight_seen = true;
2274 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2275 float old_brightness = sky->getBrightness();
2276 direct_brightness = (float)client.getEnv().getClientMap()
2277 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2278 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2282 time_of_day = client.getEnv().getTimeOfDayF();
2284 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2285 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2286 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2287 time_of_day_smooth = time_of_day;
2289 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2290 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2291 + (time_of_day+1.0) * todsm;
2293 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2294 + time_of_day * todsm;
2296 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2299 float brightness = sky->getBrightness();
2300 video::SColor bgcolor = sky->getBgColor();
2301 video::SColor skycolor = sky->getSkyColor();
2307 if(sky->getCloudsVisible()){
2308 clouds->setVisible(true);
2309 clouds->step(dtime);
2310 clouds->update(v2f(player_position.X, player_position.Z),
2311 sky->getCloudColor());
2313 clouds->setVisible(false);
2322 farmesh_range = draw_control.wanted_range * 10;
2323 if(draw_control.range_all && farmesh_range < 500)
2324 farmesh_range = 500;
2325 if(farmesh_range > 1000)
2326 farmesh_range = 1000;
2328 farmesh->step(dtime);
2329 farmesh->update(v2f(player_position.X, player_position.Z),
2330 brightness, farmesh_range);
2337 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2341 video::EFT_FOG_LINEAR,
2353 video::EFT_FOG_LINEAR,
2363 Update gui stuff (0ms)
2366 //TimeTaker guiupdatetimer("Gui updating");
2368 const char program_name_and_version[] =
2369 "Minetest-c55 " VERSION_STRING;
2373 static float drawtime_avg = 0;
2374 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2375 /*static float beginscenetime_avg = 0;
2376 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2377 static float scenetime_avg = 0;
2378 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2379 static float endscenetime_avg = 0;
2380 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2383 snprintf(temptext, 300, "%s ("
2386 " drawtime=%.0f, dtime_jitter = % .1f %%"
2387 ", v_range = %.1f, RTT = %.3f",
2388 program_name_and_version,
2389 draw_control.range_all,
2391 dtime_jitter1_max_fraction * 100.0,
2392 draw_control.wanted_range,
2396 guitext->setText(narrow_to_wide(temptext).c_str());
2397 guitext->setVisible(true);
2399 else if(show_hud || show_chat)
2401 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2402 guitext->setVisible(true);
2406 guitext->setVisible(false);
2412 snprintf(temptext, 300,
2413 "(% .1f, % .1f, % .1f)"
2415 player_position.X/BS,
2416 player_position.Y/BS,
2417 player_position.Z/BS,
2418 wrapDegrees_0_360(camera_yaw));
2420 guitext2->setText(narrow_to_wide(temptext).c_str());
2421 guitext2->setVisible(true);
2425 guitext2->setVisible(false);
2429 guitext_info->setText(infotext.c_str());
2430 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2434 float statustext_time_max = 1.5;
2435 if(!statustext.empty())
2437 statustext_time += dtime;
2438 if(statustext_time >= statustext_time_max)
2441 statustext_time = 0;
2444 guitext_status->setText(statustext.c_str());
2445 guitext_status->setVisible(!statustext.empty());
2447 if(!statustext.empty())
2449 s32 status_y = screensize.Y - 130;
2450 core::rect<s32> rect(
2452 status_y - guitext_status->getTextHeight(),
2456 guitext_status->setRelativePosition(rect);
2459 video::SColor initial_color(255,0,0,0);
2460 if(guienv->getSkin())
2461 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2462 video::SColor final_color = initial_color;
2463 final_color.setAlpha(0);
2464 video::SColor fade_color =
2465 initial_color.getInterpolated_quadratic(
2468 pow(statustext_time / (float)statustext_time_max, 2.0));
2469 guitext_status->setOverrideColor(fade_color);
2470 guitext_status->enableOverrideColor(true);
2475 Get chat messages from client
2478 // Get new messages from error log buffer
2479 while(!chat_log_error_buf.empty())
2481 chat_backend.addMessage(L"", narrow_to_wide(
2482 chat_log_error_buf.get()));
2484 // Get new messages from client
2485 std::wstring message;
2486 while(client.getChatMessage(message))
2488 chat_backend.addUnparsedMessage(message);
2490 // Remove old messages
2491 chat_backend.step(dtime);
2493 // Display all messages in a static text element
2494 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2495 std::wstring recent_chat = chat_backend.getRecentChat();
2496 guitext_chat->setText(recent_chat.c_str());
2498 // Update gui element size and position
2499 s32 chat_y = 5+(text_height+5);
2501 chat_y += (text_height+5);
2502 core::rect<s32> rect(
2506 chat_y + guitext_chat->getTextHeight()
2508 guitext_chat->setRelativePosition(rect);
2510 // Don't show chat if disabled or empty or profiler is enabled
2511 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2519 if(client.getPlayerItem() != new_playeritem)
2521 client.selectPlayerItem(new_playeritem);
2523 if(client.getLocalInventoryUpdated())
2525 //infostream<<"Updating local inventory"<<std::endl;
2526 client.getLocalInventory(local_inventory);
2528 update_wielded_item_trigger = true;
2530 if(update_wielded_item_trigger)
2532 update_wielded_item_trigger = false;
2533 // Update wielded tool
2534 InventoryList *mlist = local_inventory.getList("main");
2537 item = mlist->getItem(client.getPlayerItem());
2538 camera.wield(item, gamedef);
2545 TimeTaker tt_draw("mainloop: draw");
2549 TimeTaker timer("beginScene");
2550 //driver->beginScene(false, true, bgcolor);
2551 //driver->beginScene(true, true, bgcolor);
2552 driver->beginScene(true, true, skycolor);
2553 beginscenetime = timer.stop(true);
2558 //infostream<<"smgr->drawAll()"<<std::endl;
2560 TimeTaker timer("smgr");
2562 scenetime = timer.stop(true);
2566 //TimeTaker timer9("auxiliary drawings");
2570 //TimeTaker //timer10("//timer10");
2576 driver->setMaterial(m);
2578 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2582 for(core::list<aabb3f>::Iterator i=hilightboxes.begin();
2583 i != hilightboxes.end(); i++)
2585 /*infostream<<"hilightbox min="
2586 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2588 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2590 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2599 // Warning: This clears the Z buffer.
2600 camera.drawWieldedTool();
2607 client.getEnv().getClientMap().renderPostFx();
2613 if(show_profiler_graph)
2615 graph.draw(10, screensize.Y - 10, driver, font);
2623 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2624 displaycenter + core::vector2d<s32>(10,0),
2625 video::SColor(255,255,255,255));
2626 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2627 displaycenter + core::vector2d<s32>(0,10),
2628 video::SColor(255,255,255,255));
2634 //TimeTaker //timer11("//timer11");
2647 draw_hotbar(driver, font, gamedef,
2648 v2s32(displaycenter.X, screensize.Y),
2649 hotbar_imagesize, hotbar_itemcount, &local_inventory,
2650 client.getHP(), client.getPlayerItem());
2656 if(damage_flash_timer > 0.0)
2658 damage_flash_timer -= dtime;
2660 video::SColor color(128,255,0,0);
2661 driver->draw2DRectangle(color,
2662 core::rect<s32>(0,0,screensize.X,screensize.Y),
2667 driver->clearZBuffer();
2668 // Draw some sky things
2669 //draw_horizon(driver, camera.getCameraNode());
2675 TimeTaker timer("endScene");
2677 endscenetime = timer.stop(true);
2680 drawtime = tt_draw.stop(true);
2681 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
2687 static s16 lastFPS = 0;
2688 //u16 fps = driver->getFPS();
2689 u16 fps = (1.0/dtime_avg1);
2693 core::stringw str = L"Minetest [";
2694 str += driver->getName();
2698 device->setWindowCaption(str.c_str());
2703 Log times and stuff for visualization
2705 Profiler::GraphValues values;
2706 g_profiler->graphGet(values);
2715 if(gui_chat_console)
2716 gui_chat_console->drop();
2719 Draw a "shutting down" screen, which will be shown while the map
2720 generator and other stuff quits
2723 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2724 draw_load_screen(L"Shutting down stuff...", driver, font);
2725 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2728 gui_shuttingdowntext->remove();*/
2731 chat_backend.addMessage(L"", L"# Disconnected.");
2732 chat_backend.addMessage(L"", L"");
2734 // Client scope (client is destructed before destructing *def and tsrc)