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),
727 for(std::list<Piece>::const_iterator j = m_log.begin();
728 j != m_log.end(); j++)
730 const Piece &piece = *j;
732 bool value_exists = false;
733 Profiler::GraphValues::const_iterator k =
734 piece.values.find(id);
735 if(k != piece.values.end()){
743 float scaledvalue = 1.0;
744 if(show_max != show_min)
745 scaledvalue = (value - show_min) / (show_max - show_min);
746 if(scaledvalue == 1.0 && value == 0){
750 s32 ivalue = scaledvalue * graphh;
751 driver->draw2DLine(v2s32(x, y),
752 v2s32(x, y - ivalue),
765 IrrlichtDevice *device,
768 std::string playername,
769 std::string password,
770 std::string address, // If "", local server is used
772 std::wstring &error_message,
773 std::string configpath,
774 ChatBackend &chat_backend,
775 const SubgameSpec &gamespec, // Used for local game,
776 bool simple_singleplayer_mode
779 video::IVideoDriver* driver = device->getVideoDriver();
780 scene::ISceneManager* smgr = device->getSceneManager();
782 // Calculate text height using the font
783 u32 text_height = font->getDimension(L"Random test string").Height;
785 v2u32 screensize(0,0);
786 v2u32 last_screensize(0,0);
787 screensize = driver->getScreenSize();
789 const s32 hotbar_itemcount = 8;
790 //const s32 hotbar_imagesize = 36;
791 //const s32 hotbar_imagesize = 64;
792 s32 hotbar_imagesize = 48;
795 Draw "Loading" screen
798 draw_load_screen(L"Loading...", driver, font);
800 // Create texture source
801 IWritableTextureSource *tsrc = createTextureSource(device);
803 // These will be filled by data received from the server
804 // Create item definition manager
805 IWritableItemDefManager *itemdef = createItemDefManager();
806 // Create node definition manager
807 IWritableNodeDefManager *nodedef = createNodeDefManager();
809 // Add chat log output for errors to be shown in chat
810 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
812 // Create UI for modifying quicktune values
813 QuicktuneShortcutter quicktune;
817 SharedPtr will delete it when it goes out of scope.
819 SharedPtr<Server> server;
821 draw_load_screen(L"Creating server...", driver, font);
822 infostream<<"Creating server"<<std::endl;
823 server = new Server(map_dir, configpath, gamespec,
824 simple_singleplayer_mode);
828 do{ // Client scope (breakable do-while(0))
834 draw_load_screen(L"Creating client...", driver, font);
835 infostream<<"Creating client"<<std::endl;
837 MapDrawControl draw_control;
839 Client client(device, playername.c_str(), password, draw_control,
840 tsrc, itemdef, nodedef);
842 // Client acts as our GameDef
843 IGameDef *gamedef = &client;
845 draw_load_screen(L"Resolving address...", driver, font);
846 Address connect_address(0,0,0,0, port);
849 //connect_address.Resolve("localhost");
850 connect_address.setAddress(127,0,0,1);
852 connect_address.Resolve(address.c_str());
854 catch(ResolveError &e)
856 error_message = L"Couldn't resolve address";
857 errorstream<<wide_to_narrow(error_message)<<std::endl;
858 // Break out of client scope
863 Attempt to connect to the server
866 infostream<<"Connecting to server at ";
867 connect_address.print(&infostream);
868 infostream<<std::endl;
869 client.connect(connect_address);
872 Wait for server to accept connection
874 bool could_connect = false;
875 bool connect_aborted = false;
877 float frametime = 0.033;
878 float time_counter = 0.0;
882 // Update client and server
883 client.step(frametime);
885 server->step(frametime);
888 if(client.connectedAndInitialized()){
889 could_connect = true;
893 if(client.accessDenied()){
894 error_message = L"Access denied. Reason: "
895 +client.accessDeniedReason();
896 errorstream<<wide_to_narrow(error_message)<<std::endl;
899 if(input->wasKeyDown(EscapeKey)){
900 connect_aborted = true;
901 infostream<<"Connect aborted [Escape]"<<std::endl;
906 std::wostringstream ss;
907 ss<<L"Connecting to server... (press Escape to cancel)\n";
908 std::wstring animation = L"/-\\|";
909 ss<<animation[(int)(time_counter/0.2)%4];
910 draw_load_screen(ss.str(), driver, font);
913 sleep_ms(1000*frametime);
914 time_counter += frametime;
917 catch(con::PeerNotFoundException &e)
921 Handle failure to connect
924 if(error_message == L"" && !connect_aborted){
925 error_message = L"Connection failed";
926 errorstream<<wide_to_narrow(error_message)<<std::endl;
928 // Break out of client scope
933 Wait until content has been received
935 bool got_content = false;
936 bool content_aborted = false;
938 float frametime = 0.033;
939 float time_counter = 0.0;
943 // Update client and server
944 client.step(frametime);
946 server->step(frametime);
949 if(client.texturesReceived() &&
950 client.itemdefReceived() &&
951 client.nodedefReceived()){
956 if(!client.connectedAndInitialized()){
957 error_message = L"Client disconnected";
958 errorstream<<wide_to_narrow(error_message)<<std::endl;
961 if(input->wasKeyDown(EscapeKey)){
962 content_aborted = true;
963 infostream<<"Connect aborted [Escape]"<<std::endl;
968 std::wostringstream ss;
969 ss<<L"Waiting content... (press Escape to cancel)\n";
971 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
972 ss<<L" Item definitions\n";
973 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
974 ss<<L" Node definitions\n";
975 //ss<<(client.texturesReceived()?L"[X]":L"[ ]");
976 ss<<L"["<<(int)(client.textureReceiveProgress()*100+0.5)<<L"%] ";
979 draw_load_screen(ss.str(), driver, font);
982 sleep_ms(1000*frametime);
983 time_counter += frametime;
988 if(error_message == L"" && !content_aborted){
989 error_message = L"Something failed";
990 errorstream<<wide_to_narrow(error_message)<<std::endl;
992 // Break out of client scope
997 After all content has been received:
998 Update cached textures, meshes and materials
1000 client.afterContentReceived();
1003 Create the camera node
1005 Camera camera(smgr, draw_control);
1006 if (!camera.successfullyCreated(error_message))
1009 f32 camera_yaw = 0; // "right/left"
1010 f32 camera_pitch = 0; // "up/down"
1016 Clouds *clouds = NULL;
1017 if(g_settings->getBool("enable_clouds"))
1019 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1027 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1033 FarMesh *farmesh = NULL;
1034 if(g_settings->getBool("enable_farmesh"))
1036 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1040 A copy of the local inventory
1042 Inventory local_inventory(itemdef);
1048 // First line of debug text
1049 gui::IGUIStaticText *guitext = guienv->addStaticText(
1051 core::rect<s32>(5, 5, 795, 5+text_height),
1053 // Second line of debug text
1054 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1056 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1058 // At the middle of the screen
1059 // Object infos are shown in this
1060 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1062 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1065 // Status text (displays info when showing and hiding GUI stuff, etc.)
1066 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1068 core::rect<s32>(0,0,0,0),
1070 guitext_status->setVisible(false);
1072 std::wstring statustext;
1073 float statustext_time = 0;
1076 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1078 core::rect<s32>(0,0,0,0),
1079 //false, false); // Disable word wrap as of now
1081 // Remove stale "recent" chat messages from previous connections
1082 chat_backend.clearRecentChat();
1083 // Chat backend and console
1084 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1086 // Profiler text (size is updated when text is updated)
1087 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1089 core::rect<s32>(0,0,0,0),
1091 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1092 guitext_profiler->setVisible(false);
1095 Some statistics are collected in these
1098 u32 beginscenetime = 0;
1100 u32 endscenetime = 0;
1102 float recent_turn_speed = 0.0;
1104 ProfilerGraph graph;
1106 float nodig_delay_timer = 0.0;
1107 float dig_time = 0.0;
1109 PointedThing pointed_old;
1110 bool digging = false;
1111 bool ldown_for_dig = false;
1113 float damage_flash_timer = 0;
1114 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1116 const float object_hit_delay = 0.2;
1117 float object_hit_delay_timer = 0.0;
1118 float time_from_last_punch = 10;
1120 bool invert_mouse = g_settings->getBool("invert_mouse");
1122 bool respawn_menu_active = false;
1123 bool update_wielded_item_trigger = false;
1125 bool show_hud = true;
1126 bool show_chat = true;
1127 bool force_fog_off = false;
1128 bool disable_camera_update = false;
1129 bool show_debug = g_settings->getBool("show_debug");
1130 bool show_profiler_graph = false;
1131 u32 show_profiler = 0;
1132 u32 show_profiler_max = 3; // Number of pages
1134 float time_of_day = 0;
1135 float time_of_day_smooth = 0;
1141 bool first_loop_after_window_activation = true;
1143 // TODO: Convert the static interval timers to these
1144 // Interval limiter for profiler
1145 IntervalLimiter m_profiler_interval;
1147 // Time is in milliseconds
1148 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1149 // NOTE: So we have to use getTime() and call run()s between them
1150 u32 lasttime = device->getTimer()->getTime();
1154 if(device->run() == false || kill == true)
1157 // Time of frame without fps limit
1161 // not using getRealTime is necessary for wine
1162 u32 time = device->getTimer()->getTime();
1164 busytime_u32 = time - lasttime;
1167 busytime = busytime_u32 / 1000.0;
1170 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1172 // Necessary for device->getTimer()->getTime()
1180 float fps_max = g_settings->getFloat("fps_max");
1181 u32 frametime_min = 1000./fps_max;
1183 if(busytime_u32 < frametime_min)
1185 u32 sleeptime = frametime_min - busytime_u32;
1186 device->sleep(sleeptime);
1187 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1191 // Necessary for device->getTimer()->getTime()
1195 Time difference calculation
1197 f32 dtime; // in seconds
1199 u32 time = device->getTimer()->getTime();
1201 dtime = (time - lasttime) / 1000.0;
1206 g_profiler->graphAdd("mainloop_dtime", dtime);
1210 if(nodig_delay_timer >= 0)
1211 nodig_delay_timer -= dtime;
1212 if(object_hit_delay_timer >= 0)
1213 object_hit_delay_timer -= dtime;
1214 time_from_last_punch += dtime;
1216 g_profiler->add("Elapsed time", dtime);
1217 g_profiler->avg("FPS", 1./dtime);
1220 Time average and jitter calculation
1223 static f32 dtime_avg1 = 0.0;
1224 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1225 f32 dtime_jitter1 = dtime - dtime_avg1;
1227 static f32 dtime_jitter1_max_sample = 0.0;
1228 static f32 dtime_jitter1_max_fraction = 0.0;
1230 static f32 jitter1_max = 0.0;
1231 static f32 counter = 0.0;
1232 if(dtime_jitter1 > jitter1_max)
1233 jitter1_max = dtime_jitter1;
1238 dtime_jitter1_max_sample = jitter1_max;
1239 dtime_jitter1_max_fraction
1240 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1246 Busytime average and jitter calculation
1249 static f32 busytime_avg1 = 0.0;
1250 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1251 f32 busytime_jitter1 = busytime - busytime_avg1;
1253 static f32 busytime_jitter1_max_sample = 0.0;
1254 static f32 busytime_jitter1_min_sample = 0.0;
1256 static f32 jitter1_max = 0.0;
1257 static f32 jitter1_min = 0.0;
1258 static f32 counter = 0.0;
1259 if(busytime_jitter1 > jitter1_max)
1260 jitter1_max = busytime_jitter1;
1261 if(busytime_jitter1 < jitter1_min)
1262 jitter1_min = busytime_jitter1;
1266 busytime_jitter1_max_sample = jitter1_max;
1267 busytime_jitter1_min_sample = jitter1_min;
1274 Handle miscellaneous stuff
1277 if(client.accessDenied())
1279 error_message = L"Access denied. Reason: "
1280 +client.accessDeniedReason();
1281 errorstream<<wide_to_narrow(error_message)<<std::endl;
1285 if(g_gamecallback->disconnect_requested)
1287 g_gamecallback->disconnect_requested = false;
1291 if(g_gamecallback->changepassword_requested)
1293 (new GUIPasswordChange(guienv, guiroot, -1,
1294 &g_menumgr, &client))->drop();
1295 g_gamecallback->changepassword_requested = false;
1299 Process TextureSource's queue
1301 tsrc->processQueue();
1306 last_screensize = screensize;
1307 screensize = driver->getScreenSize();
1308 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1309 //bool screensize_changed = screensize != last_screensize;
1312 if(screensize.Y <= 800)
1313 hotbar_imagesize = 32;
1314 else if(screensize.Y <= 1280)
1315 hotbar_imagesize = 48;
1317 hotbar_imagesize = 64;
1319 // Hilight boxes collected during the loop and displayed
1320 core::list< core::aabbox3d<f32> > hilightboxes;
1323 std::wstring infotext;
1326 Debug info for client
1329 static float counter = 0.0;
1334 client.printDebugInfo(infostream);
1341 float profiler_print_interval =
1342 g_settings->getFloat("profiler_print_interval");
1343 bool print_to_log = true;
1344 if(profiler_print_interval == 0){
1345 print_to_log = false;
1346 profiler_print_interval = 5;
1348 if(m_profiler_interval.step(dtime, profiler_print_interval))
1351 infostream<<"Profiler:"<<std::endl;
1352 g_profiler->print(infostream);
1355 update_profiler_gui(guitext_profiler, font, text_height,
1356 show_profiler, show_profiler_max);
1358 g_profiler->clear();
1362 Direct handling of user input
1365 // Reset input if window not active or some menu is active
1366 if(device->isWindowActive() == false
1367 || noMenuActive() == false
1368 || guienv->hasFocus(gui_chat_console))
1373 // Input handler step() (used by the random input generator)
1377 Launch menus and trigger stuff according to keys
1379 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1381 // drop selected item
1382 IDropAction *a = new IDropAction();
1384 a->from_inv.setCurrentPlayer();
1385 a->from_list = "main";
1386 a->from_i = client.getPlayerItem();
1387 client.inventoryAction(a);
1389 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1391 infostream<<"the_game: "
1392 <<"Launching inventory"<<std::endl;
1394 GUIInventoryMenu *menu =
1395 new GUIInventoryMenu(guienv, guiroot, -1,
1396 &g_menumgr, v2s16(8,7),
1399 InventoryLocation inventoryloc;
1400 inventoryloc.setCurrentPlayer();
1402 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1403 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1404 "list", inventoryloc, "main",
1405 v2s32(0, 3), v2s32(8, 4)));
1406 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1407 "list", inventoryloc, "craft",
1408 v2s32(3, 0), v2s32(3, 3)));
1409 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1410 "list", inventoryloc, "craftpreview",
1411 v2s32(7, 1), v2s32(1, 1)));
1413 menu->setDrawSpec(draw_spec);
1417 else if(input->wasKeyDown(EscapeKey))
1419 infostream<<"the_game: "
1420 <<"Launching pause menu"<<std::endl;
1421 // It will delete itself by itself
1422 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1423 &g_menumgr, simple_singleplayer_mode))->drop();
1425 // Move mouse cursor on top of the disconnect button
1426 if(simple_singleplayer_mode)
1427 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1429 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1431 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1433 TextDest *dest = new TextDestChat(&client);
1435 (new GUITextInputMenu(guienv, guiroot, -1,
1439 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1441 TextDest *dest = new TextDestChat(&client);
1443 (new GUITextInputMenu(guienv, guiroot, -1,
1447 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1449 if (!gui_chat_console->isOpenInhibited())
1451 // Open up to over half of the screen
1452 gui_chat_console->openConsole(0.6);
1453 guienv->setFocus(gui_chat_console);
1456 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1458 if(g_settings->getBool("free_move"))
1460 g_settings->set("free_move","false");
1461 statustext = L"free_move disabled";
1462 statustext_time = 0;
1466 g_settings->set("free_move","true");
1467 statustext = L"free_move enabled";
1468 statustext_time = 0;
1471 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1473 if(g_settings->getBool("fast_move"))
1475 g_settings->set("fast_move","false");
1476 statustext = L"fast_move disabled";
1477 statustext_time = 0;
1481 g_settings->set("fast_move","true");
1482 statustext = L"fast_move enabled";
1483 statustext_time = 0;
1486 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1488 irr::video::IImage* const image = driver->createScreenShot();
1490 irr::c8 filename[256];
1491 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1492 g_settings->get("screenshot_path").c_str(),
1493 device->getTimer()->getRealTime());
1494 if (driver->writeImageToFile(image, filename)) {
1495 std::wstringstream sstr;
1496 sstr<<"Saved screenshot to '"<<filename<<"'";
1497 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1498 statustext = sstr.str();
1499 statustext_time = 0;
1501 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1506 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1508 show_hud = !show_hud;
1510 statustext = L"HUD shown";
1512 statustext = L"HUD hidden";
1513 statustext_time = 0;
1515 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1517 show_chat = !show_chat;
1519 statustext = L"Chat shown";
1521 statustext = L"Chat hidden";
1522 statustext_time = 0;
1524 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1526 force_fog_off = !force_fog_off;
1528 statustext = L"Fog disabled";
1530 statustext = L"Fog enabled";
1531 statustext_time = 0;
1533 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1535 disable_camera_update = !disable_camera_update;
1536 if(disable_camera_update)
1537 statustext = L"Camera update disabled";
1539 statustext = L"Camera update enabled";
1540 statustext_time = 0;
1542 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1544 // Initial / 3x toggle: Chat only
1545 // 1x toggle: Debug text with chat
1546 // 2x toggle: Debug text with profiler graph
1550 show_profiler_graph = false;
1551 statustext = L"Debug info shown";
1552 statustext_time = 0;
1554 else if(show_profiler_graph)
1557 show_profiler_graph = false;
1558 statustext = L"Debug info and profiler graph hidden";
1559 statustext_time = 0;
1563 show_profiler_graph = true;
1564 statustext = L"Profiler graph shown";
1565 statustext_time = 0;
1568 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1570 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1572 // FIXME: This updates the profiler with incomplete values
1573 update_profiler_gui(guitext_profiler, font, text_height,
1574 show_profiler, show_profiler_max);
1576 if(show_profiler != 0)
1578 std::wstringstream sstr;
1579 sstr<<"Profiler shown (page "<<show_profiler
1580 <<" of "<<show_profiler_max<<")";
1581 statustext = sstr.str();
1582 statustext_time = 0;
1586 statustext = L"Profiler hidden";
1587 statustext_time = 0;
1590 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1592 s16 range = g_settings->getS16("viewing_range_nodes_min");
1593 s16 range_new = range + 10;
1594 g_settings->set("viewing_range_nodes_min", itos(range_new));
1595 statustext = narrow_to_wide(
1596 "Minimum viewing range changed to "
1598 statustext_time = 0;
1600 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1602 s16 range = g_settings->getS16("viewing_range_nodes_min");
1603 s16 range_new = range - 10;
1606 g_settings->set("viewing_range_nodes_min",
1608 statustext = narrow_to_wide(
1609 "Minimum viewing range changed to "
1611 statustext_time = 0;
1614 // Handle QuicktuneShortcutter
1615 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1617 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1619 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1621 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1624 std::string msg = quicktune.getMessage();
1626 statustext = narrow_to_wide(msg);
1627 statustext_time = 0;
1631 // Item selection with mouse wheel
1632 u16 new_playeritem = client.getPlayerItem();
1634 s32 wheel = input->getMouseWheel();
1635 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1636 hotbar_itemcount-1);
1640 if(new_playeritem < max_item)
1647 if(new_playeritem > 0)
1650 new_playeritem = max_item;
1655 for(u16 i=0; i<10; i++)
1657 const KeyPress *kp = NumberKey + (i + 1) % 10;
1658 if(input->wasKeyDown(*kp))
1660 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1664 infostream<<"Selected item: "
1665 <<new_playeritem<<std::endl;
1670 // Viewing range selection
1671 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1673 draw_control.range_all = !draw_control.range_all;
1674 if(draw_control.range_all)
1676 infostream<<"Enabled full viewing range"<<std::endl;
1677 statustext = L"Enabled full viewing range";
1678 statustext_time = 0;
1682 infostream<<"Disabled full viewing range"<<std::endl;
1683 statustext = L"Disabled full viewing range";
1684 statustext_time = 0;
1688 // Print debug stacks
1689 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1691 dstream<<"-----------------------------------------"
1693 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1694 dstream<<"-----------------------------------------"
1696 debug_stacks_print();
1700 Mouse and camera control
1701 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1704 float turn_amount = 0;
1705 if((device->isWindowActive() && noMenuActive()) || random_input)
1709 // Mac OSX gets upset if this is set every frame
1710 if(device->getCursorControl()->isVisible())
1711 device->getCursorControl()->setVisible(false);
1714 if(first_loop_after_window_activation){
1715 //infostream<<"window active, first loop"<<std::endl;
1716 first_loop_after_window_activation = false;
1719 s32 dx = input->getMousePos().X - displaycenter.X;
1720 s32 dy = input->getMousePos().Y - displaycenter.Y;
1723 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1725 /*const float keyspeed = 500;
1726 if(input->isKeyDown(irr::KEY_UP))
1727 dy -= dtime * keyspeed;
1728 if(input->isKeyDown(irr::KEY_DOWN))
1729 dy += dtime * keyspeed;
1730 if(input->isKeyDown(irr::KEY_LEFT))
1731 dx -= dtime * keyspeed;
1732 if(input->isKeyDown(irr::KEY_RIGHT))
1733 dx += dtime * keyspeed;*/
1737 camera_pitch += dy*d;
1738 if(camera_pitch < -89.5) camera_pitch = -89.5;
1739 if(camera_pitch > 89.5) camera_pitch = 89.5;
1741 turn_amount = v2f(dx, dy).getLength() * d;
1743 input->setMousePos(displaycenter.X, displaycenter.Y);
1746 // Mac OSX gets upset if this is set every frame
1747 if(device->getCursorControl()->isVisible() == false)
1748 device->getCursorControl()->setVisible(true);
1750 //infostream<<"window inactive"<<std::endl;
1751 first_loop_after_window_activation = true;
1753 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1754 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1757 Player speed control
1769 PlayerControl control(
1770 input->isKeyDown(getKeySetting("keymap_forward")),
1771 input->isKeyDown(getKeySetting("keymap_backward")),
1772 input->isKeyDown(getKeySetting("keymap_left")),
1773 input->isKeyDown(getKeySetting("keymap_right")),
1774 input->isKeyDown(getKeySetting("keymap_jump")),
1775 input->isKeyDown(getKeySetting("keymap_special1")),
1776 input->isKeyDown(getKeySetting("keymap_sneak")),
1780 client.setPlayerControl(control);
1789 //TimeTaker timer("server->step(dtime)");
1790 server->step(dtime);
1798 //TimeTaker timer("client.step(dtime)");
1800 //client.step(dtime_avg1);
1804 // Read client events
1807 ClientEvent event = client.getClientEvent();
1808 if(event.type == CE_NONE)
1812 else if(event.type == CE_PLAYER_DAMAGE)
1814 //u16 damage = event.player_damage.amount;
1815 //infostream<<"Player damage: "<<damage<<std::endl;
1816 damage_flash_timer = 0.05;
1817 if(event.player_damage.amount >= 2){
1818 damage_flash_timer += 0.05 * event.player_damage.amount;
1821 else if(event.type == CE_PLAYER_FORCE_MOVE)
1823 camera_yaw = event.player_force_move.yaw;
1824 camera_pitch = event.player_force_move.pitch;
1826 else if(event.type == CE_DEATHSCREEN)
1828 if(respawn_menu_active)
1831 /*bool set_camera_point_target =
1832 event.deathscreen.set_camera_point_target;
1833 v3f camera_point_target;
1834 camera_point_target.X = event.deathscreen.camera_point_target_x;
1835 camera_point_target.Y = event.deathscreen.camera_point_target_y;
1836 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1837 MainRespawnInitiator *respawner =
1838 new MainRespawnInitiator(
1839 &respawn_menu_active, &client);
1840 GUIDeathScreen *menu =
1841 new GUIDeathScreen(guienv, guiroot, -1,
1842 &g_menumgr, respawner);
1845 chat_backend.addMessage(L"", L"You died.");
1847 /* Handle visualization */
1849 damage_flash_timer = 0;
1851 /*LocalPlayer* player = client.getLocalPlayer();
1852 player->setPosition(player->getPosition() + v3f(0,-BS,0));
1853 camera.update(player, busytime, screensize);*/
1855 else if(event.type == CE_TEXTURES_UPDATED)
1857 update_wielded_item_trigger = true;
1862 //TimeTaker //timer2("//timer2");
1865 For interaction purposes, get info about the held item
1867 - Is it a usable item?
1868 - Can it point to liquids?
1870 ItemStack playeritem;
1871 bool playeritem_usable = false;
1872 bool playeritem_liquids_pointable = false;
1874 InventoryList *mlist = local_inventory.getList("main");
1877 playeritem = mlist->getItem(client.getPlayerItem());
1878 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1879 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1882 ToolCapabilities playeritem_toolcap =
1883 playeritem.getToolCapabilities(itemdef);
1889 LocalPlayer* player = client.getEnv().getLocalPlayer();
1890 float full_punch_interval = playeritem_toolcap.full_punch_interval;
1891 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
1892 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
1893 camera.update(player, busytime, screensize, tool_reload_ratio);
1896 v3f player_position = player->getPosition();
1897 v3f camera_position = camera.getPosition();
1898 v3f camera_direction = camera.getDirection();
1899 f32 camera_fov = camera.getFovMax();
1901 if(!disable_camera_update){
1902 client.getEnv().getClientMap().updateCamera(camera_position,
1903 camera_direction, camera_fov);
1907 //TimeTaker //timer3("//timer3");
1910 Calculate what block is the crosshair pointing to
1913 //u32 t1 = device->getTimer()->getRealTime();
1915 f32 d = 4; // max. distance
1916 core::line3d<f32> shootline(camera_position,
1917 camera_position + camera_direction * BS * (d+1));
1919 core::aabbox3d<f32> hilightbox;
1920 bool should_show_hilightbox = false;
1921 ClientActiveObject *selected_object = NULL;
1923 PointedThing pointed = getPointedThing(
1925 &client, player_position, camera_direction,
1926 camera_position, shootline, d,
1927 playeritem_liquids_pointable, !ldown_for_dig,
1929 hilightbox, should_show_hilightbox,
1932 if(pointed != pointed_old)
1934 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
1935 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
1941 if(should_show_hilightbox)
1942 hilightboxes.push_back(hilightbox);
1946 - releasing left mouse button
1947 - pointing away from node
1951 if(input->getLeftReleased())
1953 infostream<<"Left button released"
1954 <<" (stopped digging)"<<std::endl;
1957 else if(pointed != pointed_old)
1959 if (pointed.type == POINTEDTHING_NODE
1960 && pointed_old.type == POINTEDTHING_NODE
1961 && pointed.node_undersurface == pointed_old.node_undersurface)
1963 // Still pointing to the same node,
1964 // but a different face. Don't reset.
1968 infostream<<"Pointing away from node"
1969 <<" (stopped digging)"<<std::endl;
1975 client.interact(1, pointed_old);
1976 client.setCrack(-1, v3s16(0,0,0));
1980 if(!digging && ldown_for_dig && !input->getLeftState())
1982 ldown_for_dig = false;
1985 bool left_punch = false;
1987 if(playeritem_usable && input->getLeftState())
1989 if(input->getLeftClicked())
1990 client.interact(4, pointed);
1992 else if(pointed.type == POINTEDTHING_NODE)
1994 v3s16 nodepos = pointed.node_undersurface;
1995 v3s16 neighbourpos = pointed.node_abovesurface;
1998 Check information text of node
2001 ClientMap &map = client.getEnv().getClientMap();
2002 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2004 infotext = narrow_to_wide(meta->infoText());
2006 MapNode n = map.getNode(nodepos);
2007 if(nodedef->get(n).tname_tiles[0] == "unknown_block.png"){
2008 infotext = L"Unknown node: ";
2009 infotext += narrow_to_wide(nodedef->get(n).name);
2017 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2021 infostream<<"Started digging"<<std::endl;
2022 client.interact(0, pointed);
2024 ldown_for_dig = true;
2026 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2028 // Get digging parameters
2029 DigParams params = getDigParams(nodedef->get(n).groups,
2030 &playeritem_toolcap);
2031 // If can't dig, try hand
2032 if(!params.diggable){
2033 const ItemDefinition &hand = itemdef->get("");
2034 const ToolCapabilities *tp = hand.tool_capabilities;
2036 params = getDigParams(nodedef->get(n).groups, tp);
2039 float dig_time_complete = 0.0;
2041 if(params.diggable == false)
2043 // I guess nobody will wait for this long
2044 dig_time_complete = 10000000.0;
2048 dig_time_complete = params.time;
2051 if(dig_time_complete >= 0.001)
2053 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
2054 * dig_time/dig_time_complete);
2056 // This is for torches
2059 dig_index = CRACK_ANIMATION_LENGTH;
2062 // Don't show cracks if not diggable
2063 if(dig_time_complete >= 100000.0)
2066 else if(dig_index < CRACK_ANIMATION_LENGTH)
2068 //TimeTaker timer("client.setTempMod");
2069 //infostream<<"dig_index="<<dig_index<<std::endl;
2070 client.setCrack(dig_index, nodepos);
2074 infostream<<"Digging completed"<<std::endl;
2075 client.interact(2, pointed);
2076 client.setCrack(-1, v3s16(0,0,0));
2077 client.removeNode(nodepos);
2082 nodig_delay_timer = dig_time_complete
2083 / (float)CRACK_ANIMATION_LENGTH;
2085 // We don't want a corresponding delay to
2086 // very time consuming nodes
2087 if(nodig_delay_timer > 0.5)
2089 nodig_delay_timer = 0.5;
2091 // We want a slight delay to very little
2092 // time consuming nodes
2093 float mindelay = 0.15;
2094 if(nodig_delay_timer < mindelay)
2096 nodig_delay_timer = mindelay;
2102 camera.setDigging(0); // left click animation
2105 if(input->getRightClicked())
2107 infostream<<"Ground right-clicked"<<std::endl;
2109 // If metadata provides an inventory view, activate it
2110 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
2112 infostream<<"Launching custom inventory view"<<std::endl;
2114 InventoryLocation inventoryloc;
2115 inventoryloc.setNodeMeta(nodepos);
2122 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
2124 GUIInventoryMenu::makeDrawSpecArrayFromString(
2126 meta->getInventoryDrawSpecString(),
2129 GUIInventoryMenu *menu =
2130 new GUIInventoryMenu(guienv, guiroot, -1,
2131 &g_menumgr, invsize,
2133 menu->setDrawSpec(draw_spec);
2136 // If metadata provides text input, activate text input
2137 else if(meta && meta->allowsTextInput() && !random_input)
2139 infostream<<"Launching metadata text input"<<std::endl;
2141 // Get a new text for it
2143 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2145 std::wstring wtext = narrow_to_wide(meta->getText());
2147 (new GUITextInputMenu(guienv, guiroot, -1,
2151 // Otherwise report right click to server
2154 client.interact(3, pointed);
2155 camera.setDigging(1); // right click animation
2159 else if(pointed.type == POINTEDTHING_OBJECT)
2161 infotext = narrow_to_wide(selected_object->infoText());
2163 if(infotext == L"" && show_debug){
2164 infotext = narrow_to_wide(selected_object->debugInfoText());
2167 //if(input->getLeftClicked())
2168 if(input->getLeftState())
2170 bool do_punch = false;
2171 bool do_punch_damage = false;
2172 if(object_hit_delay_timer <= 0.0){
2174 do_punch_damage = true;
2175 object_hit_delay_timer = object_hit_delay;
2177 if(input->getLeftClicked()){
2181 infostream<<"Left-clicked object"<<std::endl;
2184 if(do_punch_damage){
2185 // Report direct punch
2186 v3f objpos = selected_object->getPosition();
2187 v3f dir = (objpos - player_position).normalize();
2189 bool disable_send = selected_object->directReportPunch(
2190 dir, &playeritem, time_from_last_punch);
2191 time_from_last_punch = 0;
2193 client.interact(0, pointed);
2196 else if(input->getRightClicked())
2198 infostream<<"Right-clicked object"<<std::endl;
2199 client.interact(3, pointed); // place
2202 else if(input->getLeftState())
2204 // When button is held down in air, show continuous animation
2208 pointed_old = pointed;
2210 if(left_punch || input->getLeftClicked())
2212 camera.setDigging(0); // left click animation
2215 input->resetLeftClicked();
2216 input->resetRightClicked();
2218 input->resetLeftReleased();
2219 input->resetRightReleased();
2222 Calculate stuff for drawing
2232 fog_range = BS*farmesh_range;
2236 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2238 if(draw_control.range_all)
2239 fog_range = 100000*BS;
2243 Calculate general brightness
2245 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2246 float time_brightness = (float)decode_light(
2247 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2248 float direct_brightness = 0;
2249 bool sunlight_seen = false;
2250 if(g_settings->getBool("free_move")){
2251 direct_brightness = time_brightness;
2252 sunlight_seen = true;
2254 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2255 float old_brightness = sky->getBrightness();
2256 direct_brightness = (float)client.getEnv().getClientMap()
2257 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2258 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2262 time_of_day = client.getEnv().getTimeOfDayF();
2264 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2265 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2266 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2267 time_of_day_smooth = time_of_day;
2269 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2270 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2271 + (time_of_day+1.0) * todsm;
2273 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2274 + time_of_day * todsm;
2276 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2279 float brightness = sky->getBrightness();
2280 video::SColor bgcolor = sky->getBgColor();
2281 video::SColor skycolor = sky->getSkyColor();
2287 if(sky->getCloudsVisible()){
2288 clouds->setVisible(true);
2289 clouds->step(dtime);
2290 clouds->update(v2f(player_position.X, player_position.Z),
2291 sky->getCloudColor());
2293 clouds->setVisible(false);
2302 farmesh_range = draw_control.wanted_range * 10;
2303 if(draw_control.range_all && farmesh_range < 500)
2304 farmesh_range = 500;
2305 if(farmesh_range > 1000)
2306 farmesh_range = 1000;
2308 farmesh->step(dtime);
2309 farmesh->update(v2f(player_position.X, player_position.Z),
2310 brightness, farmesh_range);
2317 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2321 video::EFT_FOG_LINEAR,
2333 video::EFT_FOG_LINEAR,
2343 Update gui stuff (0ms)
2346 //TimeTaker guiupdatetimer("Gui updating");
2348 const char program_name_and_version[] =
2349 "Minetest-c55 " VERSION_STRING;
2353 static float drawtime_avg = 0;
2354 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2355 /*static float beginscenetime_avg = 0;
2356 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2357 static float scenetime_avg = 0;
2358 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2359 static float endscenetime_avg = 0;
2360 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2363 snprintf(temptext, 300, "%s ("
2366 " drawtime=%.0f, dtime_jitter = % .1f %%"
2367 ", v_range = %.1f, RTT = %.3f",
2368 program_name_and_version,
2369 draw_control.range_all,
2371 dtime_jitter1_max_fraction * 100.0,
2372 draw_control.wanted_range,
2376 guitext->setText(narrow_to_wide(temptext).c_str());
2377 guitext->setVisible(true);
2379 else if(show_hud || show_chat)
2381 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2382 guitext->setVisible(true);
2386 guitext->setVisible(false);
2392 snprintf(temptext, 300,
2393 "(% .1f, % .1f, % .1f)"
2395 player_position.X/BS,
2396 player_position.Y/BS,
2397 player_position.Z/BS,
2398 wrapDegrees_0_360(camera_yaw));
2400 guitext2->setText(narrow_to_wide(temptext).c_str());
2401 guitext2->setVisible(true);
2405 guitext2->setVisible(false);
2409 guitext_info->setText(infotext.c_str());
2410 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2414 float statustext_time_max = 1.5;
2415 if(!statustext.empty())
2417 statustext_time += dtime;
2418 if(statustext_time >= statustext_time_max)
2421 statustext_time = 0;
2424 guitext_status->setText(statustext.c_str());
2425 guitext_status->setVisible(!statustext.empty());
2427 if(!statustext.empty())
2429 s32 status_y = screensize.Y - 130;
2430 core::rect<s32> rect(
2432 status_y - guitext_status->getTextHeight(),
2436 guitext_status->setRelativePosition(rect);
2439 video::SColor initial_color(255,0,0,0);
2440 if(guienv->getSkin())
2441 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2442 video::SColor final_color = initial_color;
2443 final_color.setAlpha(0);
2444 video::SColor fade_color =
2445 initial_color.getInterpolated_quadratic(
2448 pow(statustext_time / (float)statustext_time_max, 2.0));
2449 guitext_status->setOverrideColor(fade_color);
2450 guitext_status->enableOverrideColor(true);
2455 Get chat messages from client
2458 // Get new messages from error log buffer
2459 while(!chat_log_error_buf.empty())
2461 chat_backend.addMessage(L"", narrow_to_wide(
2462 chat_log_error_buf.get()));
2464 // Get new messages from client
2465 std::wstring message;
2466 while(client.getChatMessage(message))
2468 chat_backend.addUnparsedMessage(message);
2470 // Remove old messages
2471 chat_backend.step(dtime);
2473 // Display all messages in a static text element
2474 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2475 std::wstring recent_chat = chat_backend.getRecentChat();
2476 guitext_chat->setText(recent_chat.c_str());
2478 // Update gui element size and position
2479 s32 chat_y = 5+(text_height+5);
2481 chat_y += (text_height+5);
2482 core::rect<s32> rect(
2486 chat_y + guitext_chat->getTextHeight()
2488 guitext_chat->setRelativePosition(rect);
2490 // Don't show chat if disabled or empty or profiler is enabled
2491 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2499 if(client.getPlayerItem() != new_playeritem)
2501 client.selectPlayerItem(new_playeritem);
2503 if(client.getLocalInventoryUpdated())
2505 //infostream<<"Updating local inventory"<<std::endl;
2506 client.getLocalInventory(local_inventory);
2508 update_wielded_item_trigger = true;
2510 if(update_wielded_item_trigger)
2512 update_wielded_item_trigger = false;
2513 // Update wielded tool
2514 InventoryList *mlist = local_inventory.getList("main");
2517 item = mlist->getItem(client.getPlayerItem());
2518 camera.wield(item, gamedef);
2525 TimeTaker tt_draw("mainloop: draw");
2529 TimeTaker timer("beginScene");
2530 //driver->beginScene(false, true, bgcolor);
2531 //driver->beginScene(true, true, bgcolor);
2532 driver->beginScene(true, true, skycolor);
2533 beginscenetime = timer.stop(true);
2538 //infostream<<"smgr->drawAll()"<<std::endl;
2540 TimeTaker timer("smgr");
2542 scenetime = timer.stop(true);
2546 //TimeTaker timer9("auxiliary drawings");
2550 //TimeTaker //timer10("//timer10");
2556 driver->setMaterial(m);
2558 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2562 for(core::list<aabb3f>::Iterator i=hilightboxes.begin();
2563 i != hilightboxes.end(); i++)
2565 /*infostream<<"hilightbox min="
2566 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2568 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2570 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2579 // Warning: This clears the Z buffer.
2580 camera.drawWieldedTool();
2587 client.getEnv().getClientMap().renderPostFx();
2593 if(show_profiler_graph)
2595 graph.draw(10, screensize.Y - 10, driver, font);
2603 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2604 displaycenter + core::vector2d<s32>(10,0),
2605 video::SColor(255,255,255,255));
2606 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2607 displaycenter + core::vector2d<s32>(0,10),
2608 video::SColor(255,255,255,255));
2614 //TimeTaker //timer11("//timer11");
2627 draw_hotbar(driver, font, gamedef,
2628 v2s32(displaycenter.X, screensize.Y),
2629 hotbar_imagesize, hotbar_itemcount, &local_inventory,
2630 client.getHP(), client.getPlayerItem());
2636 if(damage_flash_timer > 0.0)
2638 damage_flash_timer -= dtime;
2640 video::SColor color(128,255,0,0);
2641 driver->draw2DRectangle(color,
2642 core::rect<s32>(0,0,screensize.X,screensize.Y),
2647 driver->clearZBuffer();
2648 // Draw some sky things
2649 //draw_horizon(driver, camera.getCameraNode());
2655 TimeTaker timer("endScene");
2657 endscenetime = timer.stop(true);
2660 drawtime = tt_draw.stop(true);
2661 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
2667 static s16 lastFPS = 0;
2668 //u16 fps = driver->getFPS();
2669 u16 fps = (1.0/dtime_avg1);
2673 core::stringw str = L"Minetest [";
2674 str += driver->getName();
2678 device->setWindowCaption(str.c_str());
2683 Log times and stuff for visualization
2685 Profiler::GraphValues values;
2686 g_profiler->graphGet(values);
2695 if(gui_chat_console)
2696 gui_chat_console->drop();
2699 Draw a "shutting down" screen, which will be shown while the map
2700 generator and other stuff quits
2703 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2704 draw_load_screen(L"Shutting down stuff...", driver, font);
2705 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2708 gui_shuttingdowntext->remove();*/
2711 chat_backend.addMessage(L"", L"# Disconnected.");
2712 chat_backend.addMessage(L"", L"");
2714 // Client scope (client is destructed before destructing *def and tsrc)