3 Copyright (C) 2010-2013 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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "irrlichttypes_extrabloated.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
27 #include <IMaterialRendererServices.h>
30 #include "guiPauseMenu.h"
31 #include "guiPasswordChange.h"
32 #include "guiVolumeChange.h"
33 #include "guiFormSpecMenu.h"
34 #include "guiTextInputMenu.h"
35 #include "guiDeathScreen.h"
37 #include "guiChatConsole.h"
40 #include "particles.h"
46 #include "mainmenumanager.h"
50 // Needed for determining pointing to nodes
52 #include "nodemetadata.h"
53 #include "main.h" // For g_settings
55 #include "tile.h" // For TextureSource
56 #include "shader.h" // For ShaderSource
57 #include "logoutputbuffer.h"
59 #include "quicktune_shortcutter.h"
60 #include "clientmap.h"
64 #include "sound_openal.h"
66 #include "event_manager.h"
68 #include "util/directiontables.h"
74 struct TextDestChat : public TextDest
76 TextDestChat(Client *client)
80 void gotText(std::wstring text)
82 m_client->typeChatMessage(text);
84 void gotText(std::map<std::string, std::string> fields)
86 m_client->typeChatMessage(narrow_to_wide(fields["text"]));
92 struct TextDestNodeMetadata : public TextDest
94 TextDestNodeMetadata(v3s16 p, Client *client)
99 // This is deprecated I guess? -celeron55
100 void gotText(std::wstring text)
102 std::string ntext = wide_to_narrow(text);
103 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
104 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
105 std::map<std::string, std::string> fields;
106 fields["text"] = ntext;
107 m_client->sendNodemetaFields(m_p, "", fields);
109 void gotText(std::map<std::string, std::string> fields)
111 m_client->sendNodemetaFields(m_p, "", fields);
118 struct TextDestPlayerInventory : public TextDest
120 TextDestPlayerInventory(Client *client)
125 TextDestPlayerInventory(Client *client, std::string formname)
128 m_formname = formname;
130 void gotText(std::map<std::string, std::string> fields)
132 m_client->sendInventoryFields(m_formname, fields);
136 std::string m_formname;
139 /* Respawn menu callback */
141 class MainRespawnInitiator: public IRespawnInitiator
144 MainRespawnInitiator(bool *active, Client *client):
145 m_active(active), m_client(client)
152 m_client->sendRespawn();
159 /* Form update callback */
161 class NodeMetadataFormSource: public IFormSource
164 NodeMetadataFormSource(ClientMap *map, v3s16 p):
169 std::string getForm()
171 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
174 return meta->getString("formspec");
176 std::string resolveText(std::string str)
178 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
181 return meta->resolveString(str);
188 class PlayerInventoryFormSource: public IFormSource
191 PlayerInventoryFormSource(Client *client):
195 std::string getForm()
197 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
198 return player->inventory_formspec;
204 class FormspecFormSource: public IFormSource
207 FormspecFormSource(std::string formspec,FormspecFormSource** game_formspec)
209 m_formspec = formspec;
210 m_game_formspec = game_formspec;
213 ~FormspecFormSource()
215 *m_game_formspec = 0;
218 void setForm(std::string formspec) {
219 m_formspec = formspec;
222 std::string getForm()
227 std::string m_formspec;
228 FormspecFormSource** m_game_formspec;
233 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
235 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
236 Inventory *inventory, s32 halfheartcount, u16 playeritem)
238 InventoryList *mainlist = inventory->getList("main");
241 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
245 s32 padding = imgsize/12;
246 //s32 height = imgsize + padding*2;
247 s32 width = itemcount*(imgsize+padding*2);
249 // Position of upper left corner of bar
250 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
252 // Draw background color
253 /*core::rect<s32> barrect(0,0,width,height);
255 video::SColor bgcolor(255,128,128,128);
256 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
258 core::rect<s32> imgrect(0,0,imgsize,imgsize);
260 for(s32 i=0; i<itemcount; i++)
262 const ItemStack &item = mainlist->getItem(i);
264 core::rect<s32> rect = imgrect + pos
265 + v2s32(padding+i*(imgsize+padding*2), padding);
269 video::SColor c_outside(255,255,0,0);
270 //video::SColor c_outside(255,0,0,0);
271 //video::SColor c_inside(255,192,192,192);
272 s32 x1 = rect.UpperLeftCorner.X;
273 s32 y1 = rect.UpperLeftCorner.Y;
274 s32 x2 = rect.LowerRightCorner.X;
275 s32 y2 = rect.LowerRightCorner.Y;
276 // Black base borders
277 driver->draw2DRectangle(c_outside,
279 v2s32(x1 - padding, y1 - padding),
280 v2s32(x2 + padding, y1)
282 driver->draw2DRectangle(c_outside,
284 v2s32(x1 - padding, y2),
285 v2s32(x2 + padding, y2 + padding)
287 driver->draw2DRectangle(c_outside,
289 v2s32(x1 - padding, y1),
292 driver->draw2DRectangle(c_outside,
295 v2s32(x2 + padding, y2)
297 /*// Light inside borders
298 driver->draw2DRectangle(c_inside,
300 v2s32(x1 - padding/2, y1 - padding/2),
301 v2s32(x2 + padding/2, y1)
303 driver->draw2DRectangle(c_inside,
305 v2s32(x1 - padding/2, y2),
306 v2s32(x2 + padding/2, y2 + padding/2)
308 driver->draw2DRectangle(c_inside,
310 v2s32(x1 - padding/2, y1),
313 driver->draw2DRectangle(c_inside,
316 v2s32(x2 + padding/2, y2)
321 video::SColor bgcolor2(128,0,0,0);
322 driver->draw2DRectangle(bgcolor2, rect, NULL);
323 drawItemStack(driver, font, item, rect, NULL, gamedef);
329 video::ITexture *heart_texture =
330 gamedef->getTextureSource()->getTextureRaw("heart.png");
333 v2s32 p = pos + v2s32(0, -20);
334 for(s32 i=0; i<halfheartcount/2; i++)
336 const video::SColor color(255,255,255,255);
337 const video::SColor colors[] = {color,color,color,color};
338 core::rect<s32> rect(0,0,16,16);
340 driver->draw2DImage(heart_texture, rect,
341 core::rect<s32>(core::position2d<s32>(0,0),
342 core::dimension2di(heart_texture->getOriginalSize())),
346 if(halfheartcount % 2 == 1)
348 const video::SColor color(255,255,255,255);
349 const video::SColor colors[] = {color,color,color,color};
350 core::rect<s32> rect(0,0,16/2,16);
352 core::dimension2di srcd(heart_texture->getOriginalSize());
354 driver->draw2DImage(heart_texture, rect,
355 core::rect<s32>(core::position2d<s32>(0,0), srcd),
363 Check if a node is pointable
365 inline bool isPointableNode(const MapNode& n,
366 Client *client, bool liquids_pointable)
368 const ContentFeatures &features = client->getNodeDefManager()->get(n);
369 return features.pointable ||
370 (liquids_pointable && features.isLiquid());
374 Find what the player is pointing at
376 PointedThing getPointedThing(Client *client, v3f player_position,
377 v3f camera_direction, v3f camera_position,
378 core::line3d<f32> shootline, f32 d,
379 bool liquids_pointable,
380 bool look_for_object,
381 std::vector<aabb3f> &hilightboxes,
382 ClientActiveObject *&selected_object)
386 hilightboxes.clear();
387 selected_object = NULL;
389 INodeDefManager *nodedef = client->getNodeDefManager();
390 ClientMap &map = client->getEnv().getClientMap();
392 // First try to find a pointed at active object
395 selected_object = client->getSelectedActiveObject(d*BS,
396 camera_position, shootline);
398 if(selected_object != NULL)
400 if(selected_object->doShowSelectionBox())
402 aabb3f *selection_box = selected_object->getSelectionBox();
403 // Box should exist because object was
404 // returned in the first place
405 assert(selection_box);
407 v3f pos = selected_object->getPosition();
408 hilightboxes.push_back(aabb3f(
409 selection_box->MinEdge + pos,
410 selection_box->MaxEdge + pos));
414 result.type = POINTEDTHING_OBJECT;
415 result.object_id = selected_object->getId();
420 // That didn't work, try to find a pointed at node
422 f32 mindistance = BS * 1001;
424 v3s16 pos_i = floatToInt(player_position, BS);
426 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
430 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
431 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
432 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
433 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
434 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
435 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
437 // Prevent signed number overflow
445 for(s16 y = ystart; y <= yend; y++)
446 for(s16 z = zstart; z <= zend; z++)
447 for(s16 x = xstart; x <= xend; x++)
452 n = map.getNode(v3s16(x,y,z));
454 catch(InvalidPositionException &e)
458 if(!isPointableNode(n, client, liquids_pointable))
461 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
464 v3f npf = intToFloat(np, BS);
466 for(std::vector<aabb3f>::const_iterator
468 i != boxes.end(); i++)
474 for(u16 j=0; j<6; j++)
476 v3s16 facedir = g_6dirs[j];
477 aabb3f facebox = box;
481 facebox.MinEdge.X = facebox.MaxEdge.X-d;
482 else if(facedir.X < 0)
483 facebox.MaxEdge.X = facebox.MinEdge.X+d;
484 else if(facedir.Y > 0)
485 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
486 else if(facedir.Y < 0)
487 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
488 else if(facedir.Z > 0)
489 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
490 else if(facedir.Z < 0)
491 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
493 v3f centerpoint = facebox.getCenter();
494 f32 distance = (centerpoint - camera_position).getLength();
495 if(distance >= mindistance)
497 if(!facebox.intersectsWithLine(shootline))
500 v3s16 np_above = np + facedir;
502 result.type = POINTEDTHING_NODE;
503 result.node_undersurface = np;
504 result.node_abovesurface = np_above;
505 mindistance = distance;
507 hilightboxes.clear();
508 for(std::vector<aabb3f>::const_iterator
510 i2 != boxes.end(); i2++)
513 box.MinEdge += npf + v3f(-d,-d,-d);
514 box.MaxEdge += npf + v3f(d,d,d);
515 hilightboxes.push_back(box);
525 Draws a screen with a single text on it.
526 Text will be removed when the screen is drawn the next time.
528 /*gui::IGUIStaticText **/
529 void draw_load_screen(const std::wstring &text,
530 video::IVideoDriver* driver, gui::IGUIFont* font)
532 v2u32 screensize = driver->getScreenSize();
533 const wchar_t *loadingtext = text.c_str();
534 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
535 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
536 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
537 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
539 gui::IGUIStaticText *guitext = guienv->addStaticText(
540 loadingtext, textrect, false, false);
541 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
543 driver->beginScene(true, true, video::SColor(255,0,0,0));
552 /* Profiler display */
554 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
555 gui::IGUIFont *font, u32 text_height,
556 u32 show_profiler, u32 show_profiler_max)
558 if(show_profiler == 0)
560 guitext_profiler->setVisible(false);
565 std::ostringstream os(std::ios_base::binary);
566 g_profiler->printPage(os, show_profiler, show_profiler_max);
567 std::wstring text = narrow_to_wide(os.str());
568 guitext_profiler->setText(text.c_str());
569 guitext_profiler->setVisible(true);
571 s32 w = font->getDimension(text.c_str()).Width;
574 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
575 8+(text_height+5)*2 +
576 font->getDimension(text.c_str()).Height);
577 guitext_profiler->setRelativePosition(rect);
578 guitext_profiler->setVisible(true);
586 Profiler::GraphValues values;
592 Meta(float initial=0, video::SColor color=
593 video::SColor(255,255,255,255)):
599 std::list<Piece> m_log;
607 void put(const Profiler::GraphValues &values)
610 piece.values = values;
611 m_log.push_back(piece);
612 while(m_log.size() > m_log_max_size)
613 m_log.erase(m_log.begin());
616 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
617 gui::IGUIFont* font) const
619 std::map<std::string, Meta> m_meta;
620 for(std::list<Piece>::const_iterator k = m_log.begin();
621 k != m_log.end(); k++)
623 const Piece &piece = *k;
624 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
625 i != piece.values.end(); i++){
626 const std::string &id = i->first;
627 const float &value = i->second;
628 std::map<std::string, Meta>::iterator j =
630 if(j == m_meta.end()){
631 m_meta[id] = Meta(value);
634 if(value < j->second.min)
635 j->second.min = value;
636 if(value > j->second.max)
637 j->second.max = value;
642 static const video::SColor usable_colors[] = {
643 video::SColor(255,255,100,100),
644 video::SColor(255,90,225,90),
645 video::SColor(255,100,100,255),
646 video::SColor(255,255,150,50),
647 video::SColor(255,220,220,100)
649 static const u32 usable_colors_count =
650 sizeof(usable_colors) / sizeof(*usable_colors);
651 u32 next_color_i = 0;
652 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
653 i != m_meta.end(); i++){
654 Meta &meta = i->second;
655 video::SColor color(255,200,200,200);
656 if(next_color_i < usable_colors_count)
657 color = usable_colors[next_color_i++];
662 s32 textx = x_left + m_log_max_size + 15;
663 s32 textx2 = textx + 200 - 15;
667 u32 num_graphs = m_meta.size();
668 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
670 video::SColor bgcolor(120,0,0,0);
671 driver->draw2DRectangle(bgcolor, rect, NULL);
675 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
676 i != m_meta.end(); i++){
677 const std::string &id = i->first;
678 const Meta &meta = i->second;
680 s32 y = y_bottom - meta_i * 50;
681 float show_min = meta.min;
682 float show_max = meta.max;
683 if(show_min >= -0.0001 && show_max >= -0.0001){
684 if(show_min <= show_max * 0.5)
689 snprintf(buf, 10, "%.3g", show_max);
690 font->draw(narrow_to_wide(buf).c_str(),
691 core::rect<s32>(textx, y - graphh,
692 textx2, y - graphh + texth),
694 snprintf(buf, 10, "%.3g", show_min);
695 font->draw(narrow_to_wide(buf).c_str(),
696 core::rect<s32>(textx, y - texth,
699 font->draw(narrow_to_wide(id).c_str(),
700 core::rect<s32>(textx, y - graphh/2 - texth/2,
701 textx2, y - graphh/2 + texth/2),
704 s32 graph1h = graphh;
705 bool relativegraph = (show_min != 0 && show_min != show_max);
706 float lastscaledvalue = 0.0;
707 bool lastscaledvalue_exists = false;
708 for(std::list<Piece>::const_iterator j = m_log.begin();
709 j != m_log.end(); j++)
711 const Piece &piece = *j;
713 bool value_exists = false;
714 Profiler::GraphValues::const_iterator k =
715 piece.values.find(id);
716 if(k != piece.values.end()){
722 lastscaledvalue_exists = false;
725 float scaledvalue = 1.0;
726 if(show_max != show_min)
727 scaledvalue = (value - show_min) / (show_max - show_min);
728 if(scaledvalue == 1.0 && value == 0){
730 lastscaledvalue_exists = false;
734 if(lastscaledvalue_exists){
735 s32 ivalue1 = lastscaledvalue * graph1h;
736 s32 ivalue2 = scaledvalue * graph1h;
737 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
738 v2s32(x, graph1y - ivalue2), meta.color);
740 lastscaledvalue = scaledvalue;
741 lastscaledvalue_exists = true;
743 s32 ivalue = scaledvalue * graph1h;
744 driver->draw2DLine(v2s32(x, graph1y),
745 v2s32(x, graph1y - ivalue), meta.color);
754 class NodeDugEvent: public MtEvent
760 NodeDugEvent(v3s16 p, MapNode n):
764 const char* getType() const
770 ISoundManager *m_sound;
771 INodeDefManager *m_ndef;
773 float m_player_step_timer;
775 SimpleSoundSpec m_player_step_sound;
776 SimpleSoundSpec m_player_leftpunch_sound;
777 SimpleSoundSpec m_player_rightpunch_sound;
779 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
782 m_player_step_timer(0)
786 void playPlayerStep()
788 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
789 m_player_step_timer = 0.03;
790 m_sound->playSound(m_player_step_sound, false);
794 static void viewBobbingStep(MtEvent *e, void *data)
796 SoundMaker *sm = (SoundMaker*)data;
797 sm->playPlayerStep();
800 static void playerRegainGround(MtEvent *e, void *data)
802 SoundMaker *sm = (SoundMaker*)data;
803 sm->playPlayerStep();
806 static void playerJump(MtEvent *e, void *data)
808 //SoundMaker *sm = (SoundMaker*)data;
811 static void cameraPunchLeft(MtEvent *e, void *data)
813 SoundMaker *sm = (SoundMaker*)data;
814 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
817 static void cameraPunchRight(MtEvent *e, void *data)
819 SoundMaker *sm = (SoundMaker*)data;
820 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
823 static void nodeDug(MtEvent *e, void *data)
825 SoundMaker *sm = (SoundMaker*)data;
826 NodeDugEvent *nde = (NodeDugEvent*)e;
827 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
830 void registerReceiver(MtEventManager *mgr)
832 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
833 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
834 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
835 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
836 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
837 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
840 void step(float dtime)
842 m_player_step_timer -= dtime;
846 // Locally stored sounds don't need to be preloaded because of this
847 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
849 std::set<std::string> m_fetched;
852 void fetchSounds(const std::string &name,
853 std::set<std::string> &dst_paths,
854 std::set<std::string> &dst_datas)
856 if(m_fetched.count(name))
858 m_fetched.insert(name);
859 std::string base = porting::path_share + DIR_DELIM + "testsounds";
860 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
861 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
862 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
863 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
864 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
865 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
866 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
867 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
868 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
869 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
870 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
874 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
877 bool *m_force_fog_off;
882 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
883 f32 *fog_range, Client *client):
885 m_force_fog_off(force_fog_off),
886 m_fog_range(fog_range),
889 ~GameGlobalShaderConstantSetter() {}
891 virtual void onSetConstants(video::IMaterialRendererServices *services,
898 video::SColor bgcolor = m_sky->getBgColor();
899 video::SColorf bgcolorf(bgcolor);
900 float bgcolorfa[4] = {
906 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
909 float fog_distance = *m_fog_range;
911 fog_distance = 10000*BS;
912 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
915 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
916 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
917 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
925 IrrlichtDevice *device,
928 std::string playername,
929 std::string password,
930 std::string address, // If "", local server is used
932 std::wstring &error_message,
933 std::string configpath,
934 ChatBackend &chat_backend,
935 const SubgameSpec &gamespec, // Used for local game,
936 bool simple_singleplayer_mode
939 FormspecFormSource* current_formspec = 0;
940 video::IVideoDriver* driver = device->getVideoDriver();
941 scene::ISceneManager* smgr = device->getSceneManager();
943 // Calculate text height using the font
944 u32 text_height = font->getDimension(L"Random test string").Height;
946 v2u32 screensize(0,0);
947 v2u32 last_screensize(0,0);
948 screensize = driver->getScreenSize();
950 const s32 hotbar_itemcount = 8;
951 //const s32 hotbar_imagesize = 36;
952 //const s32 hotbar_imagesize = 64;
953 s32 hotbar_imagesize = 48;
956 Draw "Loading" screen
959 draw_load_screen(L"Loading...", driver, font);
961 // Create texture source
962 IWritableTextureSource *tsrc = createTextureSource(device);
964 // Create shader source
965 IWritableShaderSource *shsrc = createShaderSource(device);
967 // These will be filled by data received from the server
968 // Create item definition manager
969 IWritableItemDefManager *itemdef = createItemDefManager();
970 // Create node definition manager
971 IWritableNodeDefManager *nodedef = createNodeDefManager();
973 // Sound fetcher (useful when testing)
974 GameOnDemandSoundFetcher soundfetcher;
977 ISoundManager *sound = NULL;
978 bool sound_is_dummy = false;
980 if(g_settings->getBool("enable_sound")){
981 infostream<<"Attempting to use OpenAL audio"<<std::endl;
982 sound = createOpenALSoundManager(&soundfetcher);
984 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
986 infostream<<"Sound disabled."<<std::endl;
990 infostream<<"Using dummy audio."<<std::endl;
991 sound = &dummySoundManager;
992 sound_is_dummy = true;
996 EventManager eventmgr;
999 SoundMaker soundmaker(sound, nodedef);
1000 soundmaker.registerReceiver(&eventmgr);
1002 // Add chat log output for errors to be shown in chat
1003 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1005 // Create UI for modifying quicktune values
1006 QuicktuneShortcutter quicktune;
1010 SharedPtr will delete it when it goes out of scope.
1012 SharedPtr<Server> server;
1014 draw_load_screen(L"Creating server...", driver, font);
1015 infostream<<"Creating server"<<std::endl;
1016 server = new Server(map_dir, configpath, gamespec,
1017 simple_singleplayer_mode);
1018 server->start(port);
1022 do{ // Client scope (breakable do-while(0))
1028 draw_load_screen(L"Creating client...", driver, font);
1029 infostream<<"Creating client"<<std::endl;
1031 MapDrawControl draw_control;
1033 Client client(device, playername.c_str(), password, draw_control,
1034 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr);
1036 // Client acts as our GameDef
1037 IGameDef *gamedef = &client;
1039 draw_load_screen(L"Resolving address...", driver, font);
1040 Address connect_address(0,0,0,0, port);
1043 //connect_address.Resolve("localhost");
1044 connect_address.setAddress(127,0,0,1);
1046 connect_address.Resolve(address.c_str());
1048 catch(ResolveError &e)
1050 error_message = L"Couldn't resolve address";
1051 errorstream<<wide_to_narrow(error_message)<<std::endl;
1052 // Break out of client scope
1057 Attempt to connect to the server
1060 infostream<<"Connecting to server at ";
1061 connect_address.print(&infostream);
1062 infostream<<std::endl;
1063 client.connect(connect_address);
1066 Wait for server to accept connection
1068 bool could_connect = false;
1069 bool connect_aborted = false;
1071 float frametime = 0.033;
1072 float time_counter = 0.0;
1074 while(device->run())
1076 // Update client and server
1077 client.step(frametime);
1079 server->step(frametime);
1082 if(client.connectedAndInitialized()){
1083 could_connect = true;
1087 if(client.accessDenied()){
1088 error_message = L"Access denied. Reason: "
1089 +client.accessDeniedReason();
1090 errorstream<<wide_to_narrow(error_message)<<std::endl;
1093 if(input->wasKeyDown(EscapeKey)){
1094 connect_aborted = true;
1095 infostream<<"Connect aborted [Escape]"<<std::endl;
1100 std::wostringstream ss;
1101 ss<<L"Connecting to server... (press Escape to cancel)\n";
1102 std::wstring animation = L"/-\\|";
1103 ss<<animation[(int)(time_counter/0.2)%4];
1104 draw_load_screen(ss.str(), driver, font);
1107 sleep_ms(1000*frametime);
1108 time_counter += frametime;
1111 catch(con::PeerNotFoundException &e)
1115 Handle failure to connect
1118 if(error_message == L"" && !connect_aborted){
1119 error_message = L"Connection failed";
1120 errorstream<<wide_to_narrow(error_message)<<std::endl;
1122 // Break out of client scope
1127 Wait until content has been received
1129 bool got_content = false;
1130 bool content_aborted = false;
1132 float frametime = 0.033;
1133 float time_counter = 0.0;
1135 while(device->run())
1137 // Update client and server
1138 client.step(frametime);
1140 server->step(frametime);
1143 if(client.texturesReceived() &&
1144 client.itemdefReceived() &&
1145 client.nodedefReceived()){
1150 if(!client.connectedAndInitialized()){
1151 error_message = L"Client disconnected";
1152 errorstream<<wide_to_narrow(error_message)<<std::endl;
1155 if(input->wasKeyDown(EscapeKey)){
1156 content_aborted = true;
1157 infostream<<"Connect aborted [Escape]"<<std::endl;
1162 std::wostringstream ss;
1163 ss<<L"Waiting content... (press Escape to cancel)\n";
1165 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
1166 ss<<L" Item definitions\n";
1167 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
1168 ss<<L" Node definitions\n";
1169 ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1172 draw_load_screen(ss.str(), driver, font);
1175 sleep_ms(1000*frametime);
1176 time_counter += frametime;
1181 if(error_message == L"" && !content_aborted){
1182 error_message = L"Something failed";
1183 errorstream<<wide_to_narrow(error_message)<<std::endl;
1185 // Break out of client scope
1190 After all content has been received:
1191 Update cached textures, meshes and materials
1193 client.afterContentReceived();
1196 Create the camera node
1198 Camera camera(smgr, draw_control, gamedef);
1199 if (!camera.successfullyCreated(error_message))
1202 f32 camera_yaw = 0; // "right/left"
1203 f32 camera_pitch = 0; // "up/down"
1209 Clouds *clouds = NULL;
1210 if(g_settings->getBool("enable_clouds"))
1212 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1220 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1226 FarMesh *farmesh = NULL;
1227 if(g_settings->getBool("enable_farmesh"))
1229 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1233 A copy of the local inventory
1235 Inventory local_inventory(itemdef);
1238 Find out size of crack animation
1240 int crack_animation_length = 5;
1242 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1243 v2u32 size = t->getOriginalSize();
1244 crack_animation_length = size.Y / size.X;
1251 // First line of debug text
1252 gui::IGUIStaticText *guitext = guienv->addStaticText(
1254 core::rect<s32>(5, 5, 795, 5+text_height),
1256 // Second line of debug text
1257 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1259 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1261 // At the middle of the screen
1262 // Object infos are shown in this
1263 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1265 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1268 // Status text (displays info when showing and hiding GUI stuff, etc.)
1269 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1271 core::rect<s32>(0,0,0,0),
1273 guitext_status->setVisible(false);
1275 std::wstring statustext;
1276 float statustext_time = 0;
1279 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1281 core::rect<s32>(0,0,0,0),
1282 //false, false); // Disable word wrap as of now
1284 // Remove stale "recent" chat messages from previous connections
1285 chat_backend.clearRecentChat();
1286 // Chat backend and console
1287 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1289 // Profiler text (size is updated when text is updated)
1290 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1292 core::rect<s32>(0,0,0,0),
1294 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1295 guitext_profiler->setVisible(false);
1298 Some statistics are collected in these
1301 u32 beginscenetime = 0;
1303 u32 endscenetime = 0;
1305 float recent_turn_speed = 0.0;
1307 ProfilerGraph graph;
1308 // Initially clear the profiler
1309 Profiler::GraphValues dummyvalues;
1310 g_profiler->graphGet(dummyvalues);
1312 float nodig_delay_timer = 0.0;
1313 float dig_time = 0.0;
1315 PointedThing pointed_old;
1316 bool digging = false;
1317 bool ldown_for_dig = false;
1319 float damage_flash = 0;
1320 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1322 float jump_timer = 0;
1323 bool reset_jump_timer = false;
1325 const float object_hit_delay = 0.2;
1326 float object_hit_delay_timer = 0.0;
1327 float time_from_last_punch = 10;
1329 float update_draw_list_timer = 0.0;
1330 v3f update_draw_list_last_cam_dir;
1332 bool invert_mouse = g_settings->getBool("invert_mouse");
1334 bool respawn_menu_active = false;
1335 bool update_wielded_item_trigger = false;
1337 bool show_hud = true;
1338 bool show_chat = true;
1339 bool force_fog_off = false;
1340 f32 fog_range = 100*BS;
1341 bool disable_camera_update = false;
1342 bool show_debug = g_settings->getBool("show_debug");
1343 bool show_profiler_graph = false;
1344 u32 show_profiler = 0;
1345 u32 show_profiler_max = 3; // Number of pages
1347 float time_of_day = 0;
1348 float time_of_day_smooth = 0;
1350 float repeat_rightclick_timer = 0;
1355 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1356 sky, &force_fog_off, &fog_range, &client));
1362 bool first_loop_after_window_activation = true;
1364 // TODO: Convert the static interval timers to these
1365 // Interval limiter for profiler
1366 IntervalLimiter m_profiler_interval;
1368 // Time is in milliseconds
1369 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1370 // NOTE: So we have to use getTime() and call run()s between them
1371 u32 lasttime = device->getTimer()->getTime();
1373 LocalPlayer* player = client.getEnv().getLocalPlayer();
1374 player->hurt_tilt_timer = 0;
1375 player->hurt_tilt_strength = 0;
1379 if(device->run() == false || kill == true)
1382 // Time of frame without fps limit
1386 // not using getRealTime is necessary for wine
1387 u32 time = device->getTimer()->getTime();
1389 busytime_u32 = time - lasttime;
1392 busytime = busytime_u32 / 1000.0;
1395 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1397 // Necessary for device->getTimer()->getTime()
1405 float fps_max = g_settings->getFloat("fps_max");
1406 u32 frametime_min = 1000./fps_max;
1408 if(busytime_u32 < frametime_min)
1410 u32 sleeptime = frametime_min - busytime_u32;
1411 device->sleep(sleeptime);
1412 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1416 // Necessary for device->getTimer()->getTime()
1420 Time difference calculation
1422 f32 dtime; // in seconds
1424 u32 time = device->getTimer()->getTime();
1426 dtime = (time - lasttime) / 1000.0;
1431 g_profiler->graphAdd("mainloop_dtime", dtime);
1435 if(nodig_delay_timer >= 0)
1436 nodig_delay_timer -= dtime;
1437 if(object_hit_delay_timer >= 0)
1438 object_hit_delay_timer -= dtime;
1439 time_from_last_punch += dtime;
1441 g_profiler->add("Elapsed time", dtime);
1442 g_profiler->avg("FPS", 1./dtime);
1445 Time average and jitter calculation
1448 static f32 dtime_avg1 = 0.0;
1449 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1450 f32 dtime_jitter1 = dtime - dtime_avg1;
1452 static f32 dtime_jitter1_max_sample = 0.0;
1453 static f32 dtime_jitter1_max_fraction = 0.0;
1455 static f32 jitter1_max = 0.0;
1456 static f32 counter = 0.0;
1457 if(dtime_jitter1 > jitter1_max)
1458 jitter1_max = dtime_jitter1;
1463 dtime_jitter1_max_sample = jitter1_max;
1464 dtime_jitter1_max_fraction
1465 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1471 Busytime average and jitter calculation
1474 static f32 busytime_avg1 = 0.0;
1475 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1476 f32 busytime_jitter1 = busytime - busytime_avg1;
1478 static f32 busytime_jitter1_max_sample = 0.0;
1479 static f32 busytime_jitter1_min_sample = 0.0;
1481 static f32 jitter1_max = 0.0;
1482 static f32 jitter1_min = 0.0;
1483 static f32 counter = 0.0;
1484 if(busytime_jitter1 > jitter1_max)
1485 jitter1_max = busytime_jitter1;
1486 if(busytime_jitter1 < jitter1_min)
1487 jitter1_min = busytime_jitter1;
1491 busytime_jitter1_max_sample = jitter1_max;
1492 busytime_jitter1_min_sample = jitter1_min;
1499 Handle miscellaneous stuff
1502 if(client.accessDenied())
1504 error_message = L"Access denied. Reason: "
1505 +client.accessDeniedReason();
1506 errorstream<<wide_to_narrow(error_message)<<std::endl;
1510 if(g_gamecallback->disconnect_requested)
1512 g_gamecallback->disconnect_requested = false;
1516 if(g_gamecallback->changepassword_requested)
1518 (new GUIPasswordChange(guienv, guiroot, -1,
1519 &g_menumgr, &client))->drop();
1520 g_gamecallback->changepassword_requested = false;
1523 if(g_gamecallback->changevolume_requested)
1525 (new GUIVolumeChange(guienv, guiroot, -1,
1526 &g_menumgr, &client))->drop();
1527 g_gamecallback->changevolume_requested = false;
1530 /* Process TextureSource's queue */
1531 tsrc->processQueue();
1533 /* Process ItemDefManager's queue */
1534 itemdef->processQueue(gamedef);
1537 Process ShaderSource's queue
1539 shsrc->processQueue();
1544 last_screensize = screensize;
1545 screensize = driver->getScreenSize();
1546 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1547 //bool screensize_changed = screensize != last_screensize;
1550 if(screensize.Y <= 800)
1551 hotbar_imagesize = 32;
1552 else if(screensize.Y <= 1280)
1553 hotbar_imagesize = 48;
1555 hotbar_imagesize = 64;
1557 // Hilight boxes collected during the loop and displayed
1558 std::vector<aabb3f> hilightboxes;
1561 std::wstring infotext;
1564 Debug info for client
1567 static float counter = 0.0;
1572 client.printDebugInfo(infostream);
1579 float profiler_print_interval =
1580 g_settings->getFloat("profiler_print_interval");
1581 bool print_to_log = true;
1582 if(profiler_print_interval == 0){
1583 print_to_log = false;
1584 profiler_print_interval = 5;
1586 if(m_profiler_interval.step(dtime, profiler_print_interval))
1589 infostream<<"Profiler:"<<std::endl;
1590 g_profiler->print(infostream);
1593 update_profiler_gui(guitext_profiler, font, text_height,
1594 show_profiler, show_profiler_max);
1596 g_profiler->clear();
1600 Direct handling of user input
1603 // Reset input if window not active or some menu is active
1604 if(device->isWindowActive() == false
1605 || noMenuActive() == false
1606 || guienv->hasFocus(gui_chat_console))
1611 // Input handler step() (used by the random input generator)
1614 // Increase timer for doubleclick of "jump"
1615 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1616 jump_timer += dtime;
1619 Launch menus and trigger stuff according to keys
1621 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1623 // drop selected item
1624 IDropAction *a = new IDropAction();
1626 a->from_inv.setCurrentPlayer();
1627 a->from_list = "main";
1628 a->from_i = client.getPlayerItem();
1629 client.inventoryAction(a);
1631 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1633 infostream<<"the_game: "
1634 <<"Launching inventory"<<std::endl;
1636 GUIFormSpecMenu *menu =
1637 new GUIFormSpecMenu(device, guiroot, -1,
1641 InventoryLocation inventoryloc;
1642 inventoryloc.setCurrentPlayer();
1644 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1646 menu->setFormSpec(src->getForm(), inventoryloc);
1647 menu->setFormSource(src);
1648 menu->setTextDest(new TextDestPlayerInventory(&client));
1651 else if(input->wasKeyDown(EscapeKey))
1653 infostream<<"the_game: "
1654 <<"Launching pause menu"<<std::endl;
1655 // It will delete itself by itself
1656 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1657 &g_menumgr, simple_singleplayer_mode))->drop();
1659 // Move mouse cursor on top of the disconnect button
1660 if(simple_singleplayer_mode)
1661 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1663 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1665 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1667 TextDest *dest = new TextDestChat(&client);
1669 (new GUITextInputMenu(guienv, guiroot, -1,
1673 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1675 TextDest *dest = new TextDestChat(&client);
1677 (new GUITextInputMenu(guienv, guiroot, -1,
1681 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1683 if (!gui_chat_console->isOpenInhibited())
1685 // Open up to over half of the screen
1686 gui_chat_console->openConsole(0.6);
1687 guienv->setFocus(gui_chat_console);
1690 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1692 if(g_settings->getBool("free_move"))
1694 g_settings->set("free_move","false");
1695 statustext = L"free_move disabled";
1696 statustext_time = 0;
1700 g_settings->set("free_move","true");
1701 statustext = L"free_move enabled";
1702 statustext_time = 0;
1703 if(!client.checkPrivilege("fly"))
1704 statustext += L" (note: no 'fly' privilege)";
1707 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1709 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1711 if(g_settings->getBool("free_move"))
1713 g_settings->set("free_move","false");
1714 statustext = L"free_move disabled";
1715 statustext_time = 0;
1719 g_settings->set("free_move","true");
1720 statustext = L"free_move enabled";
1721 statustext_time = 0;
1722 if(!client.checkPrivilege("fly"))
1723 statustext += L" (note: no 'fly' privilege)";
1726 reset_jump_timer = true;
1728 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1730 if(g_settings->getBool("fast_move"))
1732 g_settings->set("fast_move","false");
1733 statustext = L"fast_move disabled";
1734 statustext_time = 0;
1738 g_settings->set("fast_move","true");
1739 statustext = L"fast_move enabled";
1740 statustext_time = 0;
1741 if(!client.checkPrivilege("fast"))
1742 statustext += L" (note: no 'fast' privilege)";
1745 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1747 if(g_settings->getBool("noclip"))
1749 g_settings->set("noclip","false");
1750 statustext = L"noclip disabled";
1751 statustext_time = 0;
1755 g_settings->set("noclip","true");
1756 statustext = L"noclip enabled";
1757 statustext_time = 0;
1758 if(!client.checkPrivilege("noclip"))
1759 statustext += L" (note: no 'noclip' privilege)";
1762 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1764 irr::video::IImage* const image = driver->createScreenShot();
1766 irr::c8 filename[256];
1767 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1768 g_settings->get("screenshot_path").c_str(),
1769 device->getTimer()->getRealTime());
1770 if (driver->writeImageToFile(image, filename)) {
1771 std::wstringstream sstr;
1772 sstr<<"Saved screenshot to '"<<filename<<"'";
1773 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1774 statustext = sstr.str();
1775 statustext_time = 0;
1777 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1782 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1784 show_hud = !show_hud;
1786 statustext = L"HUD shown";
1788 statustext = L"HUD hidden";
1789 statustext_time = 0;
1791 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1793 show_chat = !show_chat;
1795 statustext = L"Chat shown";
1797 statustext = L"Chat hidden";
1798 statustext_time = 0;
1800 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1802 force_fog_off = !force_fog_off;
1804 statustext = L"Fog disabled";
1806 statustext = L"Fog enabled";
1807 statustext_time = 0;
1809 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1811 disable_camera_update = !disable_camera_update;
1812 if(disable_camera_update)
1813 statustext = L"Camera update disabled";
1815 statustext = L"Camera update enabled";
1816 statustext_time = 0;
1818 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1820 // Initial / 3x toggle: Chat only
1821 // 1x toggle: Debug text with chat
1822 // 2x toggle: Debug text with profiler graph
1826 show_profiler_graph = false;
1827 statustext = L"Debug info shown";
1828 statustext_time = 0;
1830 else if(show_profiler_graph)
1833 show_profiler_graph = false;
1834 statustext = L"Debug info and profiler graph hidden";
1835 statustext_time = 0;
1839 show_profiler_graph = true;
1840 statustext = L"Profiler graph shown";
1841 statustext_time = 0;
1844 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1846 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1848 // FIXME: This updates the profiler with incomplete values
1849 update_profiler_gui(guitext_profiler, font, text_height,
1850 show_profiler, show_profiler_max);
1852 if(show_profiler != 0)
1854 std::wstringstream sstr;
1855 sstr<<"Profiler shown (page "<<show_profiler
1856 <<" of "<<show_profiler_max<<")";
1857 statustext = sstr.str();
1858 statustext_time = 0;
1862 statustext = L"Profiler hidden";
1863 statustext_time = 0;
1866 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1868 s16 range = g_settings->getS16("viewing_range_nodes_min");
1869 s16 range_new = range + 10;
1870 g_settings->set("viewing_range_nodes_min", itos(range_new));
1871 statustext = narrow_to_wide(
1872 "Minimum viewing range changed to "
1874 statustext_time = 0;
1876 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1878 s16 range = g_settings->getS16("viewing_range_nodes_min");
1879 s16 range_new = range - 10;
1882 g_settings->set("viewing_range_nodes_min",
1884 statustext = narrow_to_wide(
1885 "Minimum viewing range changed to "
1887 statustext_time = 0;
1891 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
1893 reset_jump_timer = false;
1897 // Handle QuicktuneShortcutter
1898 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1900 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1902 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1904 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1907 std::string msg = quicktune.getMessage();
1909 statustext = narrow_to_wide(msg);
1910 statustext_time = 0;
1914 // Item selection with mouse wheel
1915 u16 new_playeritem = client.getPlayerItem();
1917 s32 wheel = input->getMouseWheel();
1918 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1919 hotbar_itemcount-1);
1923 if(new_playeritem < max_item)
1930 if(new_playeritem > 0)
1933 new_playeritem = max_item;
1938 for(u16 i=0; i<10; i++)
1940 const KeyPress *kp = NumberKey + (i + 1) % 10;
1941 if(input->wasKeyDown(*kp))
1943 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1947 infostream<<"Selected item: "
1948 <<new_playeritem<<std::endl;
1953 // Viewing range selection
1954 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1956 draw_control.range_all = !draw_control.range_all;
1957 if(draw_control.range_all)
1959 infostream<<"Enabled full viewing range"<<std::endl;
1960 statustext = L"Enabled full viewing range";
1961 statustext_time = 0;
1965 infostream<<"Disabled full viewing range"<<std::endl;
1966 statustext = L"Disabled full viewing range";
1967 statustext_time = 0;
1971 // Print debug stacks
1972 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1974 dstream<<"-----------------------------------------"
1976 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1977 dstream<<"-----------------------------------------"
1979 debug_stacks_print();
1983 Mouse and camera control
1984 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1987 float turn_amount = 0;
1988 if((device->isWindowActive() && noMenuActive()) || random_input)
1992 // Mac OSX gets upset if this is set every frame
1993 if(device->getCursorControl()->isVisible())
1994 device->getCursorControl()->setVisible(false);
1997 if(first_loop_after_window_activation){
1998 //infostream<<"window active, first loop"<<std::endl;
1999 first_loop_after_window_activation = false;
2002 s32 dx = input->getMousePos().X - displaycenter.X;
2003 s32 dy = input->getMousePos().Y - displaycenter.Y;
2006 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2008 /*const float keyspeed = 500;
2009 if(input->isKeyDown(irr::KEY_UP))
2010 dy -= dtime * keyspeed;
2011 if(input->isKeyDown(irr::KEY_DOWN))
2012 dy += dtime * keyspeed;
2013 if(input->isKeyDown(irr::KEY_LEFT))
2014 dx -= dtime * keyspeed;
2015 if(input->isKeyDown(irr::KEY_RIGHT))
2016 dx += dtime * keyspeed;*/
2020 camera_pitch += dy*d;
2021 if(camera_pitch < -89.5) camera_pitch = -89.5;
2022 if(camera_pitch > 89.5) camera_pitch = 89.5;
2024 turn_amount = v2f(dx, dy).getLength() * d;
2026 input->setMousePos(displaycenter.X, displaycenter.Y);
2029 // Mac OSX gets upset if this is set every frame
2030 if(device->getCursorControl()->isVisible() == false)
2031 device->getCursorControl()->setVisible(true);
2033 //infostream<<"window inactive"<<std::endl;
2034 first_loop_after_window_activation = true;
2036 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2037 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2040 Player speed control
2054 PlayerControl control(
2055 input->isKeyDown(getKeySetting("keymap_forward")),
2056 input->isKeyDown(getKeySetting("keymap_backward")),
2057 input->isKeyDown(getKeySetting("keymap_left")),
2058 input->isKeyDown(getKeySetting("keymap_right")),
2059 input->isKeyDown(getKeySetting("keymap_jump")),
2060 input->isKeyDown(getKeySetting("keymap_special1")),
2061 input->isKeyDown(getKeySetting("keymap_sneak")),
2062 input->getLeftState(),
2063 input->getRightState(),
2067 client.setPlayerControl(control);
2069 1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2070 2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2071 4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2072 8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2073 16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2074 32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2075 64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2076 128*(int)input->getLeftState()+
2077 256*(int)input->getRightState();
2078 LocalPlayer* player = client.getEnv().getLocalPlayer();
2079 player->keyPressed=keyPressed;
2088 //TimeTaker timer("server->step(dtime)");
2089 server->step(dtime);
2097 //TimeTaker timer("client.step(dtime)");
2099 //client.step(dtime_avg1);
2103 // Read client events
2106 ClientEvent event = client.getClientEvent();
2107 if(event.type == CE_NONE)
2111 else if(event.type == CE_PLAYER_DAMAGE &&
2112 client.getHP() != 0)
2114 //u16 damage = event.player_damage.amount;
2115 //infostream<<"Player damage: "<<damage<<std::endl;
2117 damage_flash += 100.0;
2118 damage_flash += 8.0 * event.player_damage.amount;
2120 player->hurt_tilt_timer = 1.5;
2121 player->hurt_tilt_strength = event.player_damage.amount/2;
2122 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2124 else if(event.type == CE_PLAYER_FORCE_MOVE)
2126 camera_yaw = event.player_force_move.yaw;
2127 camera_pitch = event.player_force_move.pitch;
2129 else if(event.type == CE_DEATHSCREEN)
2131 if(respawn_menu_active)
2134 /*bool set_camera_point_target =
2135 event.deathscreen.set_camera_point_target;
2136 v3f camera_point_target;
2137 camera_point_target.X = event.deathscreen.camera_point_target_x;
2138 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2139 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2140 MainRespawnInitiator *respawner =
2141 new MainRespawnInitiator(
2142 &respawn_menu_active, &client);
2143 GUIDeathScreen *menu =
2144 new GUIDeathScreen(guienv, guiroot, -1,
2145 &g_menumgr, respawner);
2148 chat_backend.addMessage(L"", L"You died.");
2150 /* Handle visualization */
2154 LocalPlayer* player = client.getEnv().getLocalPlayer();
2155 player->hurt_tilt_timer = 0;
2156 player->hurt_tilt_strength = 0;
2158 /*LocalPlayer* player = client.getLocalPlayer();
2159 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2160 camera.update(player, busytime, screensize);*/
2162 else if (event.type == CE_SHOW_FORMSPEC)
2164 if (current_formspec == 0)
2167 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2169 GUIFormSpecMenu *menu =
2170 new GUIFormSpecMenu(device, guiroot, -1,
2173 menu->setFormSource(current_formspec);
2174 menu->setTextDest(new TextDestPlayerInventory(&client,*(event.show_formspec.formname)));
2180 current_formspec->setForm(*(event.show_formspec.formspec));
2182 delete(event.show_formspec.formspec);
2183 delete(event.show_formspec.formname);
2185 else if(event.type == CE_TEXTURES_UPDATED)
2187 update_wielded_item_trigger = true;
2192 //TimeTaker //timer2("//timer2");
2195 For interaction purposes, get info about the held item
2197 - Is it a usable item?
2198 - Can it point to liquids?
2200 ItemStack playeritem;
2201 bool playeritem_usable = false;
2202 bool playeritem_liquids_pointable = false;
2204 InventoryList *mlist = local_inventory.getList("main");
2207 playeritem = mlist->getItem(client.getPlayerItem());
2208 playeritem_usable = playeritem.getDefinition(itemdef).usable;
2209 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
2212 ToolCapabilities playeritem_toolcap =
2213 playeritem.getToolCapabilities(itemdef);
2219 LocalPlayer* player = client.getEnv().getLocalPlayer();
2220 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2221 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2222 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2223 camera.update(player, busytime, screensize, tool_reload_ratio);
2226 v3f player_position = player->getPosition();
2227 v3f camera_position = camera.getPosition();
2228 v3f camera_direction = camera.getDirection();
2229 f32 camera_fov = camera.getFovMax();
2231 if(!disable_camera_update){
2232 client.getEnv().getClientMap().updateCamera(camera_position,
2233 camera_direction, camera_fov);
2236 // Update sound listener
2237 sound->updateListener(camera.getCameraNode()->getPosition(),
2238 v3f(0,0,0), // velocity
2239 camera.getDirection(),
2240 camera.getCameraNode()->getUpVector());
2241 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2247 soundmaker.step(dtime);
2249 ClientMap &map = client.getEnv().getClientMap();
2250 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2251 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2255 Calculate what block is the crosshair pointing to
2258 //u32 t1 = device->getTimer()->getRealTime();
2260 f32 d = 4; // max. distance
2261 core::line3d<f32> shootline(camera_position,
2262 camera_position + camera_direction * BS * (d+1));
2264 ClientActiveObject *selected_object = NULL;
2266 PointedThing pointed = getPointedThing(
2268 &client, player_position, camera_direction,
2269 camera_position, shootline, d,
2270 playeritem_liquids_pointable, !ldown_for_dig,
2275 if(pointed != pointed_old)
2277 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2278 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2283 - releasing left mouse button
2284 - pointing away from node
2288 if(input->getLeftReleased())
2290 infostream<<"Left button released"
2291 <<" (stopped digging)"<<std::endl;
2294 else if(pointed != pointed_old)
2296 if (pointed.type == POINTEDTHING_NODE
2297 && pointed_old.type == POINTEDTHING_NODE
2298 && pointed.node_undersurface == pointed_old.node_undersurface)
2300 // Still pointing to the same node,
2301 // but a different face. Don't reset.
2305 infostream<<"Pointing away from node"
2306 <<" (stopped digging)"<<std::endl;
2312 client.interact(1, pointed_old);
2313 client.setCrack(-1, v3s16(0,0,0));
2317 if(!digging && ldown_for_dig && !input->getLeftState())
2319 ldown_for_dig = false;
2322 bool left_punch = false;
2323 soundmaker.m_player_leftpunch_sound.name = "";
2325 if(input->getRightState())
2326 repeat_rightclick_timer += dtime;
2328 repeat_rightclick_timer = 0;
2330 if(playeritem_usable && input->getLeftState())
2332 if(input->getLeftClicked())
2333 client.interact(4, pointed);
2335 else if(pointed.type == POINTEDTHING_NODE)
2337 v3s16 nodepos = pointed.node_undersurface;
2338 v3s16 neighbourpos = pointed.node_abovesurface;
2341 Check information text of node
2344 ClientMap &map = client.getEnv().getClientMap();
2345 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2347 infotext = narrow_to_wide(meta->getString("infotext"));
2349 MapNode n = map.getNode(nodepos);
2350 if(nodedef->get(n).tiledef[0].name == "unknown_block.png"){
2351 infotext = L"Unknown node: ";
2352 infotext += narrow_to_wide(nodedef->get(n).name);
2356 // We can't actually know, but assume the sound of right-clicking
2357 // to be the sound of placing a node
2358 soundmaker.m_player_rightpunch_sound.gain = 0.5;
2359 soundmaker.m_player_rightpunch_sound.name = "default_place_node";
2365 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2369 infostream<<"Started digging"<<std::endl;
2370 client.interact(0, pointed);
2372 ldown_for_dig = true;
2374 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2376 // NOTE: Similar piece of code exists on the server side for
2378 // Get digging parameters
2379 DigParams params = getDigParams(nodedef->get(n).groups,
2380 &playeritem_toolcap);
2381 // If can't dig, try hand
2382 if(!params.diggable){
2383 const ItemDefinition &hand = itemdef->get("");
2384 const ToolCapabilities *tp = hand.tool_capabilities;
2386 params = getDigParams(nodedef->get(n).groups, tp);
2389 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2390 if(sound_dig.exists()){
2391 if(sound_dig.name == "__group"){
2392 if(params.main_group != ""){
2393 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2394 soundmaker.m_player_leftpunch_sound.name =
2395 std::string("default_dig_") +
2399 soundmaker.m_player_leftpunch_sound = sound_dig;
2403 float dig_time_complete = 0.0;
2405 if(params.diggable == false)
2407 // I guess nobody will wait for this long
2408 dig_time_complete = 10000000.0;
2412 dig_time_complete = params.time;
2413 if (g_settings->getBool("enable_particles"))
2415 const ContentFeatures &features =
2416 client.getNodeDefManager()->get(n);
2417 addPunchingParticles
2418 (gamedef, smgr, player, nodepos, features.tiles);
2422 if(dig_time_complete >= 0.001)
2424 dig_index = (u16)((float)crack_animation_length
2425 * dig_time/dig_time_complete);
2427 // This is for torches
2430 dig_index = crack_animation_length;
2433 // Don't show cracks if not diggable
2434 if(dig_time_complete >= 100000.0)
2437 else if(dig_index < crack_animation_length)
2439 //TimeTaker timer("client.setTempMod");
2440 //infostream<<"dig_index="<<dig_index<<std::endl;
2441 client.setCrack(dig_index, nodepos);
2445 infostream<<"Digging completed"<<std::endl;
2446 client.interact(2, pointed);
2447 client.setCrack(-1, v3s16(0,0,0));
2448 MapNode wasnode = map.getNode(nodepos);
2449 client.removeNode(nodepos);
2451 if (g_settings->getBool("enable_particles"))
2453 const ContentFeatures &features =
2454 client.getNodeDefManager()->get(wasnode);
2456 (gamedef, smgr, player, nodepos, features.tiles);
2462 nodig_delay_timer = dig_time_complete
2463 / (float)crack_animation_length;
2465 // We don't want a corresponding delay to
2466 // very time consuming nodes
2467 if(nodig_delay_timer > 0.3)
2468 nodig_delay_timer = 0.3;
2469 // We want a slight delay to very little
2470 // time consuming nodes
2471 float mindelay = 0.15;
2472 if(nodig_delay_timer < mindelay)
2473 nodig_delay_timer = mindelay;
2475 // Send event to trigger sound
2476 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2477 gamedef->event()->put(e);
2482 camera.setDigging(0); // left click animation
2485 if(input->getRightClicked() ||
2486 repeat_rightclick_timer >= g_settings->getFloat("repeat_rightclick_time"))
2488 repeat_rightclick_timer = 0;
2489 infostream<<"Ground right-clicked"<<std::endl;
2491 // Sign special case, at least until formspec is properly implemented.
2493 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2495 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2497 infostream<<"Launching metadata text input"<<std::endl;
2499 // Get a new text for it
2501 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2503 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2505 (new GUITextInputMenu(guienv, guiroot, -1,
2509 // If metadata provides an inventory view, activate it
2510 else if(meta && meta->getString("formspec") != "" && !random_input
2511 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2513 infostream<<"Launching custom inventory view"<<std::endl;
2515 InventoryLocation inventoryloc;
2516 inventoryloc.setNodeMeta(nodepos);
2520 GUIFormSpecMenu *menu =
2521 new GUIFormSpecMenu(device, guiroot, -1,
2524 menu->setFormSpec(meta->getString("formspec"),
2526 menu->setFormSource(new NodeMetadataFormSource(
2527 &client.getEnv().getClientMap(), nodepos));
2528 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2531 // Otherwise report right click to server
2535 client.interact(3, pointed);
2536 camera.setDigging(1); // right click animation
2538 // If the wielded item has node placement prediction,
2540 const ItemDefinition &def =
2541 playeritem.getDefinition(itemdef);
2542 if(def.node_placement_prediction != ""
2543 && !nodedef->get(map.getNode(nodepos)).rightclickable)
2545 verbosestream<<"Node placement prediction for "
2546 <<playeritem.name<<" is "
2547 <<def.node_placement_prediction<<std::endl;
2548 v3s16 p = neighbourpos;
2549 // Place inside node itself if buildable_to
2551 MapNode n_under = map.getNode(nodepos);
2552 if(nodedef->get(n_under).buildable_to)
2554 }catch(InvalidPositionException &e){}
2555 // Find id of predicted node
2558 nodedef->getId(def.node_placement_prediction, id);
2560 errorstream<<"Node placement prediction failed for "
2561 <<playeritem.name<<" (places "
2562 <<def.node_placement_prediction
2563 <<") - Name not known"<<std::endl;
2568 // This triggers the required mesh update too
2569 client.addNode(p, n);
2570 }catch(InvalidPositionException &e){
2571 errorstream<<"Node placement prediction failed for "
2572 <<playeritem.name<<" (places "
2573 <<def.node_placement_prediction
2574 <<") - Position not loaded"<<std::endl;
2580 else if(pointed.type == POINTEDTHING_OBJECT)
2582 infotext = narrow_to_wide(selected_object->infoText());
2584 if(infotext == L"" && show_debug){
2585 infotext = narrow_to_wide(selected_object->debugInfoText());
2588 //if(input->getLeftClicked())
2589 if(input->getLeftState())
2591 bool do_punch = false;
2592 bool do_punch_damage = false;
2593 if(object_hit_delay_timer <= 0.0){
2595 do_punch_damage = true;
2596 object_hit_delay_timer = object_hit_delay;
2598 if(input->getLeftClicked()){
2602 infostream<<"Left-clicked object"<<std::endl;
2605 if(do_punch_damage){
2606 // Report direct punch
2607 v3f objpos = selected_object->getPosition();
2608 v3f dir = (objpos - player_position).normalize();
2610 bool disable_send = selected_object->directReportPunch(
2611 dir, &playeritem, time_from_last_punch);
2612 time_from_last_punch = 0;
2614 client.interact(0, pointed);
2617 else if(input->getRightClicked())
2619 infostream<<"Right-clicked object"<<std::endl;
2620 client.interact(3, pointed); // place
2623 else if(input->getLeftState())
2625 // When button is held down in air, show continuous animation
2629 pointed_old = pointed;
2631 if(left_punch || input->getLeftClicked())
2633 camera.setDigging(0); // left click animation
2636 input->resetLeftClicked();
2637 input->resetRightClicked();
2639 input->resetLeftReleased();
2640 input->resetRightReleased();
2643 Calculate stuff for drawing
2652 fog_range = BS*farmesh_range;
2656 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2658 if(draw_control.range_all)
2659 fog_range = 100000*BS;
2663 Calculate general brightness
2665 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2666 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2667 float direct_brightness = 0;
2668 bool sunlight_seen = false;
2669 if(g_settings->getBool("free_move")){
2670 direct_brightness = time_brightness;
2671 sunlight_seen = true;
2673 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2674 float old_brightness = sky->getBrightness();
2675 direct_brightness = (float)client.getEnv().getClientMap()
2676 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2677 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2681 time_of_day = client.getEnv().getTimeOfDayF();
2683 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2684 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2685 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2686 time_of_day_smooth = time_of_day;
2688 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2689 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2690 + (time_of_day+1.0) * todsm;
2692 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2693 + time_of_day * todsm;
2695 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2698 float brightness = sky->getBrightness();
2699 video::SColor bgcolor = sky->getBgColor();
2700 video::SColor skycolor = sky->getSkyColor();
2706 if(sky->getCloudsVisible()){
2707 clouds->setVisible(true);
2708 clouds->step(dtime);
2709 clouds->update(v2f(player_position.X, player_position.Z),
2710 sky->getCloudColor());
2712 clouds->setVisible(false);
2721 farmesh_range = draw_control.wanted_range * 10;
2722 if(draw_control.range_all && farmesh_range < 500)
2723 farmesh_range = 500;
2724 if(farmesh_range > 1000)
2725 farmesh_range = 1000;
2727 farmesh->step(dtime);
2728 farmesh->update(v2f(player_position.X, player_position.Z),
2729 brightness, farmesh_range);
2736 allparticles_step(dtime, client.getEnv());
2742 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2746 video::EFT_FOG_LINEAR,
2758 video::EFT_FOG_LINEAR,
2768 Update gui stuff (0ms)
2771 //TimeTaker guiupdatetimer("Gui updating");
2773 const char program_name_and_version[] =
2774 "Minetest " VERSION_STRING;
2778 static float drawtime_avg = 0;
2779 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2780 /*static float beginscenetime_avg = 0;
2781 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2782 static float scenetime_avg = 0;
2783 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2784 static float endscenetime_avg = 0;
2785 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2788 snprintf(temptext, 300, "%s ("
2791 " drawtime=%.0f, dtime_jitter = % .1f %%"
2792 ", v_range = %.1f, RTT = %.3f",
2793 program_name_and_version,
2794 draw_control.range_all,
2796 dtime_jitter1_max_fraction * 100.0,
2797 draw_control.wanted_range,
2801 guitext->setText(narrow_to_wide(temptext).c_str());
2802 guitext->setVisible(true);
2804 else if(show_hud || show_chat)
2806 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2807 guitext->setVisible(true);
2811 guitext->setVisible(false);
2817 snprintf(temptext, 300,
2818 "(% .1f, % .1f, % .1f)"
2819 " (yaw = %.1f) (seed = %llu)",
2820 player_position.X/BS,
2821 player_position.Y/BS,
2822 player_position.Z/BS,
2823 wrapDegrees_0_360(camera_yaw),
2824 (unsigned long long)client.getMapSeed());
2826 guitext2->setText(narrow_to_wide(temptext).c_str());
2827 guitext2->setVisible(true);
2831 guitext2->setVisible(false);
2835 guitext_info->setText(infotext.c_str());
2836 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2840 float statustext_time_max = 1.5;
2841 if(!statustext.empty())
2843 statustext_time += dtime;
2844 if(statustext_time >= statustext_time_max)
2847 statustext_time = 0;
2850 guitext_status->setText(statustext.c_str());
2851 guitext_status->setVisible(!statustext.empty());
2853 if(!statustext.empty())
2855 s32 status_y = screensize.Y - 130;
2856 core::rect<s32> rect(
2858 status_y - guitext_status->getTextHeight(),
2862 guitext_status->setRelativePosition(rect);
2865 video::SColor initial_color(255,0,0,0);
2866 if(guienv->getSkin())
2867 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2868 video::SColor final_color = initial_color;
2869 final_color.setAlpha(0);
2870 video::SColor fade_color =
2871 initial_color.getInterpolated_quadratic(
2874 pow(statustext_time / (float)statustext_time_max, 2.0f));
2875 guitext_status->setOverrideColor(fade_color);
2876 guitext_status->enableOverrideColor(true);
2881 Get chat messages from client
2884 // Get new messages from error log buffer
2885 while(!chat_log_error_buf.empty())
2887 chat_backend.addMessage(L"", narrow_to_wide(
2888 chat_log_error_buf.get()));
2890 // Get new messages from client
2891 std::wstring message;
2892 while(client.getChatMessage(message))
2894 chat_backend.addUnparsedMessage(message);
2896 // Remove old messages
2897 chat_backend.step(dtime);
2899 // Display all messages in a static text element
2900 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2901 std::wstring recent_chat = chat_backend.getRecentChat();
2902 guitext_chat->setText(recent_chat.c_str());
2904 // Update gui element size and position
2905 s32 chat_y = 5+(text_height+5);
2907 chat_y += (text_height+5);
2908 core::rect<s32> rect(
2912 chat_y + guitext_chat->getTextHeight()
2914 guitext_chat->setRelativePosition(rect);
2916 // Don't show chat if disabled or empty or profiler is enabled
2917 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2925 if(client.getPlayerItem() != new_playeritem)
2927 client.selectPlayerItem(new_playeritem);
2929 if(client.getLocalInventoryUpdated())
2931 //infostream<<"Updating local inventory"<<std::endl;
2932 client.getLocalInventory(local_inventory);
2934 update_wielded_item_trigger = true;
2936 if(update_wielded_item_trigger)
2938 update_wielded_item_trigger = false;
2939 // Update wielded tool
2940 InventoryList *mlist = local_inventory.getList("main");
2943 item = mlist->getItem(client.getPlayerItem());
2948 Update block draw list every 200ms or when camera direction has
2951 update_draw_list_timer += dtime;
2952 if(update_draw_list_timer >= 0.2 ||
2953 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
2954 update_draw_list_timer = 0;
2955 client.getEnv().getClientMap().updateDrawList(driver);
2956 update_draw_list_last_cam_dir = camera_direction;
2963 TimeTaker tt_draw("mainloop: draw");
2967 TimeTaker timer("beginScene");
2968 //driver->beginScene(false, true, bgcolor);
2969 //driver->beginScene(true, true, bgcolor);
2970 driver->beginScene(true, true, skycolor);
2971 beginscenetime = timer.stop(true);
2976 //infostream<<"smgr->drawAll()"<<std::endl;
2978 TimeTaker timer("smgr");
2981 if(g_settings->getBool("anaglyph"))
2983 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
2984 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
2986 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
2988 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
2989 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
2990 camera.getCameraNode()->getAbsolutePosition() ;
2993 irr::core::vector3df leftEye;
2994 irr::core::matrix4 leftMove;
2996 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
2997 leftEye=(startMatrix*leftMove).getTranslation();
2999 //clear the depth buffer, and color
3000 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3002 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3003 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3004 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3005 irr::scene::ESNRP_SOLID +
3006 irr::scene::ESNRP_TRANSPARENT +
3007 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3008 irr::scene::ESNRP_SHADOW;
3010 camera.getCameraNode()->setPosition( leftEye );
3011 camera.getCameraNode()->setTarget( focusPoint );
3013 smgr->drawAll(); // 'smgr->drawAll();' may go here
3017 irr::core::vector3df rightEye;
3018 irr::core::matrix4 rightMove;
3020 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3021 rightEye=(startMatrix*rightMove).getTranslation();
3023 //clear the depth buffer
3024 driver->clearZBuffer();
3026 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3027 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3028 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3029 irr::scene::ESNRP_SOLID +
3030 irr::scene::ESNRP_TRANSPARENT +
3031 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3032 irr::scene::ESNRP_SHADOW;
3034 camera.getCameraNode()->setPosition( rightEye );
3035 camera.getCameraNode()->setTarget( focusPoint );
3037 smgr->drawAll(); // 'smgr->drawAll();' may go here
3040 //driver->endScene();
3042 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3043 driver->getOverrideMaterial().EnableFlags=0;
3044 driver->getOverrideMaterial().EnablePasses=0;
3046 camera.getCameraNode()->setPosition( oldPosition );
3047 camera.getCameraNode()->setTarget( oldTarget );
3050 scenetime = timer.stop(true);
3054 //TimeTaker timer9("auxiliary drawings");
3058 //TimeTaker //timer10("//timer10");
3064 driver->setMaterial(m);
3066 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3070 v3f selectionbox_color = g_settings->getV3F("selectionbox_color");
3071 u32 selectionbox_color_r = rangelim(myround(selectionbox_color.X), 0, 255);
3072 u32 selectionbox_color_g = rangelim(myround(selectionbox_color.Y), 0, 255);
3073 u32 selectionbox_color_b = rangelim(myround(selectionbox_color.Z), 0, 255);
3075 for(std::vector<aabb3f>::const_iterator
3076 i = hilightboxes.begin();
3077 i != hilightboxes.end(); i++)
3079 /*infostream<<"hilightbox min="
3080 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
3082 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
3084 driver->draw3DBox(*i, video::SColor(255,selectionbox_color_r,selectionbox_color_g,selectionbox_color_b));
3093 // Warning: This clears the Z buffer.
3094 camera.drawWieldedTool();
3101 client.getEnv().getClientMap().renderPostFx();
3107 if(show_profiler_graph)
3109 graph.draw(10, screensize.Y - 10, driver, font);
3117 v3f crosshair_color = g_settings->getV3F("crosshair_color");
3118 u32 crosshair_color_r = rangelim(myround(crosshair_color.X), 0, 255);
3119 u32 crosshair_color_g = rangelim(myround(crosshair_color.Y), 0, 255);
3120 u32 crosshair_color_b = rangelim(myround(crosshair_color.Z), 0, 255);
3121 u32 crosshair_alpha = rangelim(g_settings->getS32("crosshair_alpha"), 0, 255);
3123 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
3124 displaycenter + core::vector2d<s32>(10,0),
3125 video::SColor(crosshair_alpha,crosshair_color_r,crosshair_color_g,crosshair_color_b));
3126 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
3127 displaycenter + core::vector2d<s32>(0,10),
3128 video::SColor(crosshair_alpha,crosshair_color_r,crosshair_color_g,crosshair_color_b));
3134 //TimeTaker //timer11("//timer11");
3142 draw_hotbar(driver, font, gamedef,
3143 v2s32(displaycenter.X, screensize.Y),
3144 hotbar_imagesize, hotbar_itemcount, &local_inventory,
3145 client.getHP(), client.getPlayerItem());
3151 if(damage_flash > 0.0)
3153 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3154 driver->draw2DRectangle(color,
3155 core::rect<s32>(0,0,screensize.X,screensize.Y),
3158 damage_flash -= 100.0*dtime;
3164 if(player->hurt_tilt_timer > 0.0)
3166 player->hurt_tilt_timer -= dtime*5;
3167 if(player->hurt_tilt_timer < 0)
3168 player->hurt_tilt_strength = 0;
3181 TimeTaker timer("endScene");
3183 endscenetime = timer.stop(true);
3186 drawtime = tt_draw.stop(true);
3187 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3193 static s16 lastFPS = 0;
3194 //u16 fps = driver->getFPS();
3195 u16 fps = (1.0/dtime_avg1);
3199 core::stringw str = L"Minetest [";
3200 str += driver->getName();
3204 device->setWindowCaption(str.c_str());
3209 Log times and stuff for visualization
3211 Profiler::GraphValues values;
3212 g_profiler->graphGet(values);
3221 if(gui_chat_console)
3222 gui_chat_console->drop();
3225 Draw a "shutting down" screen, which will be shown while the map
3226 generator and other stuff quits
3229 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3230 draw_load_screen(L"Shutting down stuff...", driver, font);
3231 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3234 gui_shuttingdowntext->remove();*/
3237 chat_backend.addMessage(L"", L"# Disconnected.");
3238 chat_backend.addMessage(L"", L"");
3240 // Client scope (client is destructed before destructing *def and tsrc)
3243 catch(SerializationError &e)
3245 error_message = L"A serialization error occurred:\n"
3246 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3247 L" running a different version of Minetest.";
3248 errorstream<<wide_to_narrow(error_message)<<std::endl;