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>
28 #include "IMeshCache.h"
31 #include "guiPauseMenu.h"
32 #include "guiPasswordChange.h"
33 #include "guiVolumeChange.h"
34 #include "guiFormSpecMenu.h"
35 #include "guiTextInputMenu.h"
36 #include "guiDeathScreen.h"
38 #include "guiChatConsole.h"
41 #include "particles.h"
47 #include "mainmenumanager.h"
51 // Needed for determining pointing to nodes
53 #include "nodemetadata.h"
54 #include "main.h" // For g_settings
56 #include "tile.h" // For TextureSource
57 #include "shader.h" // For ShaderSource
58 #include "logoutputbuffer.h"
60 #include "quicktune_shortcutter.h"
61 #include "clientmap.h"
66 #include "sound_openal.h"
68 #include "event_manager.h"
70 #include "util/directiontables.h"
76 struct TextDestChat : public TextDest
78 TextDestChat(Client *client)
82 void gotText(std::wstring text)
84 m_client->typeChatMessage(text);
86 void gotText(std::map<std::string, std::string> fields)
88 m_client->typeChatMessage(narrow_to_wide(fields["text"]));
94 struct TextDestNodeMetadata : public TextDest
96 TextDestNodeMetadata(v3s16 p, Client *client)
101 // This is deprecated I guess? -celeron55
102 void gotText(std::wstring text)
104 std::string ntext = wide_to_narrow(text);
105 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
106 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
107 std::map<std::string, std::string> fields;
108 fields["text"] = ntext;
109 m_client->sendNodemetaFields(m_p, "", fields);
111 void gotText(std::map<std::string, std::string> fields)
113 m_client->sendNodemetaFields(m_p, "", fields);
120 struct TextDestPlayerInventory : public TextDest
122 TextDestPlayerInventory(Client *client)
127 TextDestPlayerInventory(Client *client, std::string formname)
130 m_formname = formname;
132 void gotText(std::map<std::string, std::string> fields)
134 m_client->sendInventoryFields(m_formname, fields);
138 std::string m_formname;
141 /* Respawn menu callback */
143 class MainRespawnInitiator: public IRespawnInitiator
146 MainRespawnInitiator(bool *active, Client *client):
147 m_active(active), m_client(client)
154 m_client->sendRespawn();
161 /* Form update callback */
163 class NodeMetadataFormSource: public IFormSource
166 NodeMetadataFormSource(ClientMap *map, v3s16 p):
171 std::string getForm()
173 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
176 return meta->getString("formspec");
178 std::string resolveText(std::string str)
180 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
183 return meta->resolveString(str);
190 class PlayerInventoryFormSource: public IFormSource
193 PlayerInventoryFormSource(Client *client):
197 std::string getForm()
199 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
200 return player->inventory_formspec;
206 class FormspecFormSource: public IFormSource
209 FormspecFormSource(std::string formspec,FormspecFormSource** game_formspec)
211 m_formspec = formspec;
212 m_game_formspec = game_formspec;
215 ~FormspecFormSource()
217 *m_game_formspec = 0;
220 void setForm(std::string formspec) {
221 m_formspec = formspec;
224 std::string getForm()
229 std::string m_formspec;
230 FormspecFormSource** m_game_formspec;
234 Check if a node is pointable
236 inline bool isPointableNode(const MapNode& n,
237 Client *client, bool liquids_pointable)
239 const ContentFeatures &features = client->getNodeDefManager()->get(n);
240 return features.pointable ||
241 (liquids_pointable && features.isLiquid());
245 Find what the player is pointing at
247 PointedThing getPointedThing(Client *client, v3f player_position,
248 v3f camera_direction, v3f camera_position,
249 core::line3d<f32> shootline, f32 d,
250 bool liquids_pointable,
251 bool look_for_object,
252 std::vector<aabb3f> &hilightboxes,
253 ClientActiveObject *&selected_object)
257 hilightboxes.clear();
258 selected_object = NULL;
260 INodeDefManager *nodedef = client->getNodeDefManager();
261 ClientMap &map = client->getEnv().getClientMap();
263 // First try to find a pointed at active object
266 selected_object = client->getSelectedActiveObject(d*BS,
267 camera_position, shootline);
269 if(selected_object != NULL)
271 if(selected_object->doShowSelectionBox())
273 aabb3f *selection_box = selected_object->getSelectionBox();
274 // Box should exist because object was
275 // returned in the first place
276 assert(selection_box);
278 v3f pos = selected_object->getPosition();
279 hilightboxes.push_back(aabb3f(
280 selection_box->MinEdge + pos,
281 selection_box->MaxEdge + pos));
285 result.type = POINTEDTHING_OBJECT;
286 result.object_id = selected_object->getId();
291 // That didn't work, try to find a pointed at node
293 f32 mindistance = BS * 1001;
295 v3s16 pos_i = floatToInt(player_position, BS);
297 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
301 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
302 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
303 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
304 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
305 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
306 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
308 // Prevent signed number overflow
316 for(s16 y = ystart; y <= yend; y++)
317 for(s16 z = zstart; z <= zend; z++)
318 for(s16 x = xstart; x <= xend; x++)
323 n = map.getNode(v3s16(x,y,z));
325 catch(InvalidPositionException &e)
329 if(!isPointableNode(n, client, liquids_pointable))
332 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
335 v3f npf = intToFloat(np, BS);
337 for(std::vector<aabb3f>::const_iterator
339 i != boxes.end(); i++)
345 for(u16 j=0; j<6; j++)
347 v3s16 facedir = g_6dirs[j];
348 aabb3f facebox = box;
352 facebox.MinEdge.X = facebox.MaxEdge.X-d;
353 else if(facedir.X < 0)
354 facebox.MaxEdge.X = facebox.MinEdge.X+d;
355 else if(facedir.Y > 0)
356 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
357 else if(facedir.Y < 0)
358 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
359 else if(facedir.Z > 0)
360 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
361 else if(facedir.Z < 0)
362 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
364 v3f centerpoint = facebox.getCenter();
365 f32 distance = (centerpoint - camera_position).getLength();
366 if(distance >= mindistance)
368 if(!facebox.intersectsWithLine(shootline))
371 v3s16 np_above = np + facedir;
373 result.type = POINTEDTHING_NODE;
374 result.node_undersurface = np;
375 result.node_abovesurface = np_above;
376 mindistance = distance;
378 hilightboxes.clear();
379 for(std::vector<aabb3f>::const_iterator
381 i2 != boxes.end(); i2++)
384 box.MinEdge += npf + v3f(-d,-d,-d);
385 box.MaxEdge += npf + v3f(d,d,d);
386 hilightboxes.push_back(box);
396 Draws a screen with a single text on it.
397 Text will be removed when the screen is drawn the next time.
399 /*gui::IGUIStaticText **/
400 void draw_load_screen(const std::wstring &text,
401 video::IVideoDriver* driver, gui::IGUIFont* font)
403 v2u32 screensize = driver->getScreenSize();
404 const wchar_t *loadingtext = text.c_str();
405 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
406 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
407 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
408 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
410 gui::IGUIStaticText *guitext = guienv->addStaticText(
411 loadingtext, textrect, false, false);
412 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
414 driver->beginScene(true, true, video::SColor(255,0,0,0));
423 /* Profiler display */
425 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
426 gui::IGUIFont *font, u32 text_height,
427 u32 show_profiler, u32 show_profiler_max)
429 if(show_profiler == 0)
431 guitext_profiler->setVisible(false);
436 std::ostringstream os(std::ios_base::binary);
437 g_profiler->printPage(os, show_profiler, show_profiler_max);
438 std::wstring text = narrow_to_wide(os.str());
439 guitext_profiler->setText(text.c_str());
440 guitext_profiler->setVisible(true);
442 s32 w = font->getDimension(text.c_str()).Width;
445 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
446 8+(text_height+5)*2 +
447 font->getDimension(text.c_str()).Height);
448 guitext_profiler->setRelativePosition(rect);
449 guitext_profiler->setVisible(true);
457 Profiler::GraphValues values;
463 Meta(float initial=0, video::SColor color=
464 video::SColor(255,255,255,255)):
470 std::list<Piece> m_log;
478 void put(const Profiler::GraphValues &values)
481 piece.values = values;
482 m_log.push_back(piece);
483 while(m_log.size() > m_log_max_size)
484 m_log.erase(m_log.begin());
487 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
488 gui::IGUIFont* font) const
490 std::map<std::string, Meta> m_meta;
491 for(std::list<Piece>::const_iterator k = m_log.begin();
492 k != m_log.end(); k++)
494 const Piece &piece = *k;
495 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
496 i != piece.values.end(); i++){
497 const std::string &id = i->first;
498 const float &value = i->second;
499 std::map<std::string, Meta>::iterator j =
501 if(j == m_meta.end()){
502 m_meta[id] = Meta(value);
505 if(value < j->second.min)
506 j->second.min = value;
507 if(value > j->second.max)
508 j->second.max = value;
513 static const video::SColor usable_colors[] = {
514 video::SColor(255,255,100,100),
515 video::SColor(255,90,225,90),
516 video::SColor(255,100,100,255),
517 video::SColor(255,255,150,50),
518 video::SColor(255,220,220,100)
520 static const u32 usable_colors_count =
521 sizeof(usable_colors) / sizeof(*usable_colors);
522 u32 next_color_i = 0;
523 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
524 i != m_meta.end(); i++){
525 Meta &meta = i->second;
526 video::SColor color(255,200,200,200);
527 if(next_color_i < usable_colors_count)
528 color = usable_colors[next_color_i++];
533 s32 textx = x_left + m_log_max_size + 15;
534 s32 textx2 = textx + 200 - 15;
538 u32 num_graphs = m_meta.size();
539 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
541 video::SColor bgcolor(120,0,0,0);
542 driver->draw2DRectangle(bgcolor, rect, NULL);
546 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
547 i != m_meta.end(); i++){
548 const std::string &id = i->first;
549 const Meta &meta = i->second;
551 s32 y = y_bottom - meta_i * 50;
552 float show_min = meta.min;
553 float show_max = meta.max;
554 if(show_min >= -0.0001 && show_max >= -0.0001){
555 if(show_min <= show_max * 0.5)
560 snprintf(buf, 10, "%.3g", show_max);
561 font->draw(narrow_to_wide(buf).c_str(),
562 core::rect<s32>(textx, y - graphh,
563 textx2, y - graphh + texth),
565 snprintf(buf, 10, "%.3g", show_min);
566 font->draw(narrow_to_wide(buf).c_str(),
567 core::rect<s32>(textx, y - texth,
570 font->draw(narrow_to_wide(id).c_str(),
571 core::rect<s32>(textx, y - graphh/2 - texth/2,
572 textx2, y - graphh/2 + texth/2),
575 s32 graph1h = graphh;
576 bool relativegraph = (show_min != 0 && show_min != show_max);
577 float lastscaledvalue = 0.0;
578 bool lastscaledvalue_exists = false;
579 for(std::list<Piece>::const_iterator j = m_log.begin();
580 j != m_log.end(); j++)
582 const Piece &piece = *j;
584 bool value_exists = false;
585 Profiler::GraphValues::const_iterator k =
586 piece.values.find(id);
587 if(k != piece.values.end()){
593 lastscaledvalue_exists = false;
596 float scaledvalue = 1.0;
597 if(show_max != show_min)
598 scaledvalue = (value - show_min) / (show_max - show_min);
599 if(scaledvalue == 1.0 && value == 0){
601 lastscaledvalue_exists = false;
605 if(lastscaledvalue_exists){
606 s32 ivalue1 = lastscaledvalue * graph1h;
607 s32 ivalue2 = scaledvalue * graph1h;
608 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
609 v2s32(x, graph1y - ivalue2), meta.color);
611 lastscaledvalue = scaledvalue;
612 lastscaledvalue_exists = true;
614 s32 ivalue = scaledvalue * graph1h;
615 driver->draw2DLine(v2s32(x, graph1y),
616 v2s32(x, graph1y - ivalue), meta.color);
625 class NodeDugEvent: public MtEvent
631 NodeDugEvent(v3s16 p, MapNode n):
635 const char* getType() const
641 ISoundManager *m_sound;
642 INodeDefManager *m_ndef;
644 float m_player_step_timer;
646 SimpleSoundSpec m_player_step_sound;
647 SimpleSoundSpec m_player_leftpunch_sound;
648 SimpleSoundSpec m_player_rightpunch_sound;
650 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
653 m_player_step_timer(0)
657 void playPlayerStep()
659 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
660 m_player_step_timer = 0.03;
661 m_sound->playSound(m_player_step_sound, false);
665 static void viewBobbingStep(MtEvent *e, void *data)
667 SoundMaker *sm = (SoundMaker*)data;
668 sm->playPlayerStep();
671 static void playerRegainGround(MtEvent *e, void *data)
673 SoundMaker *sm = (SoundMaker*)data;
674 sm->playPlayerStep();
677 static void playerJump(MtEvent *e, void *data)
679 //SoundMaker *sm = (SoundMaker*)data;
682 static void cameraPunchLeft(MtEvent *e, void *data)
684 SoundMaker *sm = (SoundMaker*)data;
685 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
688 static void cameraPunchRight(MtEvent *e, void *data)
690 SoundMaker *sm = (SoundMaker*)data;
691 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
694 static void nodeDug(MtEvent *e, void *data)
696 SoundMaker *sm = (SoundMaker*)data;
697 NodeDugEvent *nde = (NodeDugEvent*)e;
698 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
701 void registerReceiver(MtEventManager *mgr)
703 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
704 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
705 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
706 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
707 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
708 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
711 void step(float dtime)
713 m_player_step_timer -= dtime;
717 // Locally stored sounds don't need to be preloaded because of this
718 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
720 std::set<std::string> m_fetched;
723 void fetchSounds(const std::string &name,
724 std::set<std::string> &dst_paths,
725 std::set<std::string> &dst_datas)
727 if(m_fetched.count(name))
729 m_fetched.insert(name);
730 std::string base = porting::path_share + DIR_DELIM + "testsounds";
731 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
732 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
733 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
734 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
735 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
736 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
737 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
738 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
739 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
740 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
741 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
745 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
748 bool *m_force_fog_off;
753 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
754 f32 *fog_range, Client *client):
756 m_force_fog_off(force_fog_off),
757 m_fog_range(fog_range),
760 ~GameGlobalShaderConstantSetter() {}
762 virtual void onSetConstants(video::IMaterialRendererServices *services,
769 video::SColor bgcolor = m_sky->getBgColor();
770 video::SColorf bgcolorf(bgcolor);
771 float bgcolorfa[4] = {
777 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
780 float fog_distance = *m_fog_range;
782 fog_distance = 10000*BS;
783 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
786 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
787 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
788 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
796 IrrlichtDevice *device,
799 std::string playername,
800 std::string password,
801 std::string address, // If "", local server is used
803 std::wstring &error_message,
804 std::string configpath,
805 ChatBackend &chat_backend,
806 const SubgameSpec &gamespec, // Used for local game,
807 bool simple_singleplayer_mode
810 FormspecFormSource* current_formspec = 0;
811 video::IVideoDriver* driver = device->getVideoDriver();
812 scene::ISceneManager* smgr = device->getSceneManager();
814 // Calculate text height using the font
815 u32 text_height = font->getDimension(L"Random test string").Height;
817 v2u32 last_screensize(0,0);
818 v2u32 screensize = driver->getScreenSize();
821 Draw "Loading" screen
824 draw_load_screen(L"Loading...", driver, font);
826 // Create texture source
827 IWritableTextureSource *tsrc = createTextureSource(device);
829 // Create shader source
830 IWritableShaderSource *shsrc = createShaderSource(device);
832 // These will be filled by data received from the server
833 // Create item definition manager
834 IWritableItemDefManager *itemdef = createItemDefManager();
835 // Create node definition manager
836 IWritableNodeDefManager *nodedef = createNodeDefManager();
838 // Sound fetcher (useful when testing)
839 GameOnDemandSoundFetcher soundfetcher;
842 ISoundManager *sound = NULL;
843 bool sound_is_dummy = false;
845 if(g_settings->getBool("enable_sound")){
846 infostream<<"Attempting to use OpenAL audio"<<std::endl;
847 sound = createOpenALSoundManager(&soundfetcher);
849 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
851 infostream<<"Sound disabled."<<std::endl;
855 infostream<<"Using dummy audio."<<std::endl;
856 sound = &dummySoundManager;
857 sound_is_dummy = true;
860 Server *server = NULL;
864 EventManager eventmgr;
867 SoundMaker soundmaker(sound, nodedef);
868 soundmaker.registerReceiver(&eventmgr);
870 // Add chat log output for errors to be shown in chat
871 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
873 // Create UI for modifying quicktune values
874 QuicktuneShortcutter quicktune;
881 draw_load_screen(L"Creating server...", driver, font);
882 infostream<<"Creating server"<<std::endl;
883 server = new Server(map_dir, configpath, gamespec,
884 simple_singleplayer_mode);
888 do{ // Client scope (breakable do-while(0))
894 draw_load_screen(L"Creating client...", driver, font);
895 infostream<<"Creating client"<<std::endl;
897 MapDrawControl draw_control;
899 Client client(device, playername.c_str(), password, draw_control,
900 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr);
902 // Client acts as our GameDef
903 IGameDef *gamedef = &client;
905 draw_load_screen(L"Resolving address...", driver, font);
906 Address connect_address(0,0,0,0, port);
909 //connect_address.Resolve("localhost");
910 connect_address.setAddress(127,0,0,1);
912 connect_address.Resolve(address.c_str());
914 catch(ResolveError &e)
916 error_message = L"Couldn't resolve address";
917 errorstream<<wide_to_narrow(error_message)<<std::endl;
918 // Break out of client scope
923 Attempt to connect to the server
926 infostream<<"Connecting to server at ";
927 connect_address.print(&infostream);
928 infostream<<std::endl;
929 client.connect(connect_address);
932 Wait for server to accept connection
934 bool could_connect = false;
935 bool connect_aborted = false;
937 float frametime = 0.033;
938 float time_counter = 0.0;
942 // Update client and server
943 client.step(frametime);
945 server->step(frametime);
948 if(client.connectedAndInitialized()){
949 could_connect = true;
953 if(client.accessDenied()){
954 error_message = L"Access denied. Reason: "
955 +client.accessDeniedReason();
956 errorstream<<wide_to_narrow(error_message)<<std::endl;
959 if(input->wasKeyDown(EscapeKey)){
960 connect_aborted = true;
961 infostream<<"Connect aborted [Escape]"<<std::endl;
966 std::wostringstream ss;
967 ss<<L"Connecting to server... (press Escape to cancel)\n";
968 std::wstring animation = L"/-\\|";
969 ss<<animation[(int)(time_counter/0.2)%4];
970 draw_load_screen(ss.str(), driver, font);
973 sleep_ms(1000*frametime);
974 time_counter += frametime;
977 catch(con::PeerNotFoundException &e)
981 Handle failure to connect
984 if(error_message == L"" && !connect_aborted){
985 error_message = L"Connection failed";
986 errorstream<<wide_to_narrow(error_message)<<std::endl;
988 // Break out of client scope
993 Wait until content has been received
995 bool got_content = false;
996 bool content_aborted = false;
998 float frametime = 0.033;
999 float time_counter = 0.0;
1001 while(device->run())
1003 // Update client and server
1004 client.step(frametime);
1006 server->step(frametime);
1009 if(client.texturesReceived() &&
1010 client.itemdefReceived() &&
1011 client.nodedefReceived()){
1016 if(!client.connectedAndInitialized()){
1017 error_message = L"Client disconnected";
1018 errorstream<<wide_to_narrow(error_message)<<std::endl;
1021 if(input->wasKeyDown(EscapeKey)){
1022 content_aborted = true;
1023 infostream<<"Connect aborted [Escape]"<<std::endl;
1028 std::wostringstream ss;
1029 ss<<L"Waiting content... (press Escape to cancel)\n";
1031 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
1032 ss<<L" Item definitions\n";
1033 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
1034 ss<<L" Node definitions\n";
1035 ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1038 draw_load_screen(ss.str(), driver, font);
1041 sleep_ms(1000*frametime);
1042 time_counter += frametime;
1047 if(error_message == L"" && !content_aborted){
1048 error_message = L"Something failed";
1049 errorstream<<wide_to_narrow(error_message)<<std::endl;
1051 // Break out of client scope
1056 After all content has been received:
1057 Update cached textures, meshes and materials
1059 client.afterContentReceived();
1062 Create the camera node
1064 Camera camera(smgr, draw_control, gamedef);
1065 if (!camera.successfullyCreated(error_message))
1068 f32 camera_yaw = 0; // "right/left"
1069 f32 camera_pitch = 0; // "up/down"
1075 Clouds *clouds = NULL;
1076 if(g_settings->getBool("enable_clouds"))
1078 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1086 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1092 FarMesh *farmesh = NULL;
1093 if(g_settings->getBool("enable_farmesh"))
1095 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1099 A copy of the local inventory
1101 Inventory local_inventory(itemdef);
1104 Find out size of crack animation
1106 int crack_animation_length = 5;
1108 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1109 v2u32 size = t->getOriginalSize();
1110 crack_animation_length = size.Y / size.X;
1117 // First line of debug text
1118 gui::IGUIStaticText *guitext = guienv->addStaticText(
1120 core::rect<s32>(5, 5, 795, 5+text_height),
1122 // Second line of debug text
1123 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1125 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1127 // At the middle of the screen
1128 // Object infos are shown in this
1129 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1131 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1134 // Status text (displays info when showing and hiding GUI stuff, etc.)
1135 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1137 core::rect<s32>(0,0,0,0),
1139 guitext_status->setVisible(false);
1141 std::wstring statustext;
1142 float statustext_time = 0;
1145 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1147 core::rect<s32>(0,0,0,0),
1148 //false, false); // Disable word wrap as of now
1150 // Remove stale "recent" chat messages from previous connections
1151 chat_backend.clearRecentChat();
1152 // Chat backend and console
1153 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1155 // Profiler text (size is updated when text is updated)
1156 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1158 core::rect<s32>(0,0,0,0),
1160 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1161 guitext_profiler->setVisible(false);
1164 Some statistics are collected in these
1167 u32 beginscenetime = 0;
1169 u32 endscenetime = 0;
1171 float recent_turn_speed = 0.0;
1173 ProfilerGraph graph;
1174 // Initially clear the profiler
1175 Profiler::GraphValues dummyvalues;
1176 g_profiler->graphGet(dummyvalues);
1178 float nodig_delay_timer = 0.0;
1179 float dig_time = 0.0;
1181 PointedThing pointed_old;
1182 bool digging = false;
1183 bool ldown_for_dig = false;
1185 float damage_flash = 0;
1186 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1188 float jump_timer = 0;
1189 bool reset_jump_timer = false;
1191 const float object_hit_delay = 0.2;
1192 float object_hit_delay_timer = 0.0;
1193 float time_from_last_punch = 10;
1195 float update_draw_list_timer = 0.0;
1196 v3f update_draw_list_last_cam_dir;
1198 bool invert_mouse = g_settings->getBool("invert_mouse");
1200 bool respawn_menu_active = false;
1201 bool update_wielded_item_trigger = false;
1203 bool show_hud = true;
1204 bool show_chat = true;
1205 bool force_fog_off = false;
1206 f32 fog_range = 100*BS;
1207 bool disable_camera_update = false;
1208 bool show_debug = g_settings->getBool("show_debug");
1209 bool show_profiler_graph = false;
1210 u32 show_profiler = 0;
1211 u32 show_profiler_max = 3; // Number of pages
1213 float time_of_day = 0;
1214 float time_of_day_smooth = 0;
1216 float repeat_rightclick_timer = 0;
1221 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1222 sky, &force_fog_off, &fog_range, &client));
1228 bool first_loop_after_window_activation = true;
1230 // TODO: Convert the static interval timers to these
1231 // Interval limiter for profiler
1232 IntervalLimiter m_profiler_interval;
1234 // Time is in milliseconds
1235 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1236 // NOTE: So we have to use getTime() and call run()s between them
1237 u32 lasttime = device->getTimer()->getTime();
1239 LocalPlayer* player = client.getEnv().getLocalPlayer();
1240 player->hurt_tilt_timer = 0;
1241 player->hurt_tilt_strength = 0;
1246 Hud hud(driver, guienv, font, text_height,
1247 gamedef, player, &local_inventory);
1251 if(device->run() == false || kill == true)
1254 // Time of frame without fps limit
1258 // not using getRealTime is necessary for wine
1259 u32 time = device->getTimer()->getTime();
1261 busytime_u32 = time - lasttime;
1264 busytime = busytime_u32 / 1000.0;
1267 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1269 // Necessary for device->getTimer()->getTime()
1277 float fps_max = g_settings->getFloat("fps_max");
1278 u32 frametime_min = 1000./fps_max;
1280 if(busytime_u32 < frametime_min)
1282 u32 sleeptime = frametime_min - busytime_u32;
1283 device->sleep(sleeptime);
1284 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1288 // Necessary for device->getTimer()->getTime()
1292 Time difference calculation
1294 f32 dtime; // in seconds
1296 u32 time = device->getTimer()->getTime();
1298 dtime = (time - lasttime) / 1000.0;
1303 g_profiler->graphAdd("mainloop_dtime", dtime);
1307 if(nodig_delay_timer >= 0)
1308 nodig_delay_timer -= dtime;
1309 if(object_hit_delay_timer >= 0)
1310 object_hit_delay_timer -= dtime;
1311 time_from_last_punch += dtime;
1313 g_profiler->add("Elapsed time", dtime);
1314 g_profiler->avg("FPS", 1./dtime);
1317 Time average and jitter calculation
1320 static f32 dtime_avg1 = 0.0;
1321 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1322 f32 dtime_jitter1 = dtime - dtime_avg1;
1324 static f32 dtime_jitter1_max_sample = 0.0;
1325 static f32 dtime_jitter1_max_fraction = 0.0;
1327 static f32 jitter1_max = 0.0;
1328 static f32 counter = 0.0;
1329 if(dtime_jitter1 > jitter1_max)
1330 jitter1_max = dtime_jitter1;
1335 dtime_jitter1_max_sample = jitter1_max;
1336 dtime_jitter1_max_fraction
1337 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1343 Busytime average and jitter calculation
1346 static f32 busytime_avg1 = 0.0;
1347 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1348 f32 busytime_jitter1 = busytime - busytime_avg1;
1350 static f32 busytime_jitter1_max_sample = 0.0;
1351 static f32 busytime_jitter1_min_sample = 0.0;
1353 static f32 jitter1_max = 0.0;
1354 static f32 jitter1_min = 0.0;
1355 static f32 counter = 0.0;
1356 if(busytime_jitter1 > jitter1_max)
1357 jitter1_max = busytime_jitter1;
1358 if(busytime_jitter1 < jitter1_min)
1359 jitter1_min = busytime_jitter1;
1363 busytime_jitter1_max_sample = jitter1_max;
1364 busytime_jitter1_min_sample = jitter1_min;
1371 Handle miscellaneous stuff
1374 if(client.accessDenied())
1376 error_message = L"Access denied. Reason: "
1377 +client.accessDeniedReason();
1378 errorstream<<wide_to_narrow(error_message)<<std::endl;
1382 if(g_gamecallback->disconnect_requested)
1384 g_gamecallback->disconnect_requested = false;
1388 if(g_gamecallback->changepassword_requested)
1390 (new GUIPasswordChange(guienv, guiroot, -1,
1391 &g_menumgr, &client))->drop();
1392 g_gamecallback->changepassword_requested = false;
1395 if(g_gamecallback->changevolume_requested)
1397 (new GUIVolumeChange(guienv, guiroot, -1,
1398 &g_menumgr, &client))->drop();
1399 g_gamecallback->changevolume_requested = false;
1402 /* Process TextureSource's queue */
1403 tsrc->processQueue();
1405 /* Process ItemDefManager's queue */
1406 itemdef->processQueue(gamedef);
1409 Process ShaderSource's queue
1411 shsrc->processQueue();
1416 last_screensize = screensize;
1417 screensize = driver->getScreenSize();
1418 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1419 //bool screensize_changed = screensize != last_screensize;
1422 // Update HUD values
1423 hud.screensize = screensize;
1424 hud.displaycenter = displaycenter;
1427 // Hilight boxes collected during the loop and displayed
1428 std::vector<aabb3f> hilightboxes;
1431 std::wstring infotext;
1434 Debug info for client
1437 static float counter = 0.0;
1442 client.printDebugInfo(infostream);
1449 float profiler_print_interval =
1450 g_settings->getFloat("profiler_print_interval");
1451 bool print_to_log = true;
1452 if(profiler_print_interval == 0){
1453 print_to_log = false;
1454 profiler_print_interval = 5;
1456 if(m_profiler_interval.step(dtime, profiler_print_interval))
1459 infostream<<"Profiler:"<<std::endl;
1460 g_profiler->print(infostream);
1463 update_profiler_gui(guitext_profiler, font, text_height,
1464 show_profiler, show_profiler_max);
1466 g_profiler->clear();
1470 Direct handling of user input
1473 // Reset input if window not active or some menu is active
1474 if(device->isWindowActive() == false
1475 || noMenuActive() == false
1476 || guienv->hasFocus(gui_chat_console))
1481 // Input handler step() (used by the random input generator)
1484 // Increase timer for doubleclick of "jump"
1485 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1486 jump_timer += dtime;
1489 Launch menus and trigger stuff according to keys
1491 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1493 // drop selected item
1494 IDropAction *a = new IDropAction();
1496 a->from_inv.setCurrentPlayer();
1497 a->from_list = "main";
1498 a->from_i = client.getPlayerItem();
1499 client.inventoryAction(a);
1501 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1503 infostream<<"the_game: "
1504 <<"Launching inventory"<<std::endl;
1506 GUIFormSpecMenu *menu =
1507 new GUIFormSpecMenu(device, guiroot, -1,
1511 InventoryLocation inventoryloc;
1512 inventoryloc.setCurrentPlayer();
1514 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1516 menu->setFormSpec(src->getForm(), inventoryloc);
1517 menu->setFormSource(src);
1518 menu->setTextDest(new TextDestPlayerInventory(&client));
1521 else if(input->wasKeyDown(EscapeKey))
1523 infostream<<"the_game: "
1524 <<"Launching pause menu"<<std::endl;
1525 // It will delete itself by itself
1526 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1527 &g_menumgr, simple_singleplayer_mode))->drop();
1529 // Move mouse cursor on top of the disconnect button
1530 if(simple_singleplayer_mode)
1531 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1533 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1535 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1537 TextDest *dest = new TextDestChat(&client);
1539 (new GUITextInputMenu(guienv, guiroot, -1,
1543 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1545 TextDest *dest = new TextDestChat(&client);
1547 (new GUITextInputMenu(guienv, guiroot, -1,
1551 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1553 if (!gui_chat_console->isOpenInhibited())
1555 // Open up to over half of the screen
1556 gui_chat_console->openConsole(0.6);
1557 guienv->setFocus(gui_chat_console);
1560 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1562 if(g_settings->getBool("free_move"))
1564 g_settings->set("free_move","false");
1565 statustext = L"free_move disabled";
1566 statustext_time = 0;
1570 g_settings->set("free_move","true");
1571 statustext = L"free_move enabled";
1572 statustext_time = 0;
1573 if(!client.checkPrivilege("fly"))
1574 statustext += L" (note: no 'fly' privilege)";
1577 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1579 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1581 if(g_settings->getBool("free_move"))
1583 g_settings->set("free_move","false");
1584 statustext = L"free_move disabled";
1585 statustext_time = 0;
1589 g_settings->set("free_move","true");
1590 statustext = L"free_move enabled";
1591 statustext_time = 0;
1592 if(!client.checkPrivilege("fly"))
1593 statustext += L" (note: no 'fly' privilege)";
1596 reset_jump_timer = true;
1598 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1600 if(g_settings->getBool("fast_move"))
1602 g_settings->set("fast_move","false");
1603 statustext = L"fast_move disabled";
1604 statustext_time = 0;
1608 g_settings->set("fast_move","true");
1609 statustext = L"fast_move enabled";
1610 statustext_time = 0;
1611 if(!client.checkPrivilege("fast"))
1612 statustext += L" (note: no 'fast' privilege)";
1615 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1617 if(g_settings->getBool("noclip"))
1619 g_settings->set("noclip","false");
1620 statustext = L"noclip disabled";
1621 statustext_time = 0;
1625 g_settings->set("noclip","true");
1626 statustext = L"noclip enabled";
1627 statustext_time = 0;
1628 if(!client.checkPrivilege("noclip"))
1629 statustext += L" (note: no 'noclip' privilege)";
1632 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1634 irr::video::IImage* const image = driver->createScreenShot();
1636 irr::c8 filename[256];
1637 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1638 g_settings->get("screenshot_path").c_str(),
1639 device->getTimer()->getRealTime());
1640 if (driver->writeImageToFile(image, filename)) {
1641 std::wstringstream sstr;
1642 sstr<<"Saved screenshot to '"<<filename<<"'";
1643 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1644 statustext = sstr.str();
1645 statustext_time = 0;
1647 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1652 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1654 show_hud = !show_hud;
1656 statustext = L"HUD shown";
1658 statustext = L"HUD hidden";
1659 statustext_time = 0;
1661 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1663 show_chat = !show_chat;
1665 statustext = L"Chat shown";
1667 statustext = L"Chat hidden";
1668 statustext_time = 0;
1670 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1672 force_fog_off = !force_fog_off;
1674 statustext = L"Fog disabled";
1676 statustext = L"Fog enabled";
1677 statustext_time = 0;
1679 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1681 disable_camera_update = !disable_camera_update;
1682 if(disable_camera_update)
1683 statustext = L"Camera update disabled";
1685 statustext = L"Camera update enabled";
1686 statustext_time = 0;
1688 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1690 // Initial / 3x toggle: Chat only
1691 // 1x toggle: Debug text with chat
1692 // 2x toggle: Debug text with profiler graph
1696 show_profiler_graph = false;
1697 statustext = L"Debug info shown";
1698 statustext_time = 0;
1700 else if(show_profiler_graph)
1703 show_profiler_graph = false;
1704 statustext = L"Debug info and profiler graph hidden";
1705 statustext_time = 0;
1709 show_profiler_graph = true;
1710 statustext = L"Profiler graph shown";
1711 statustext_time = 0;
1714 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1716 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1718 // FIXME: This updates the profiler with incomplete values
1719 update_profiler_gui(guitext_profiler, font, text_height,
1720 show_profiler, show_profiler_max);
1722 if(show_profiler != 0)
1724 std::wstringstream sstr;
1725 sstr<<"Profiler shown (page "<<show_profiler
1726 <<" of "<<show_profiler_max<<")";
1727 statustext = sstr.str();
1728 statustext_time = 0;
1732 statustext = L"Profiler hidden";
1733 statustext_time = 0;
1736 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1738 s16 range = g_settings->getS16("viewing_range_nodes_min");
1739 s16 range_new = range + 10;
1740 g_settings->set("viewing_range_nodes_min", itos(range_new));
1741 statustext = narrow_to_wide(
1742 "Minimum viewing range changed to "
1744 statustext_time = 0;
1746 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1748 s16 range = g_settings->getS16("viewing_range_nodes_min");
1749 s16 range_new = range - 10;
1752 g_settings->set("viewing_range_nodes_min",
1754 statustext = narrow_to_wide(
1755 "Minimum viewing range changed to "
1757 statustext_time = 0;
1761 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
1763 reset_jump_timer = false;
1767 // Handle QuicktuneShortcutter
1768 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1770 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1772 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1774 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1777 std::string msg = quicktune.getMessage();
1779 statustext = narrow_to_wide(msg);
1780 statustext_time = 0;
1784 // Item selection with mouse wheel
1785 u16 new_playeritem = client.getPlayerItem();
1787 s32 wheel = input->getMouseWheel();
1788 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1789 hud.hotbar_itemcount-1);
1793 if(new_playeritem < max_item)
1800 if(new_playeritem > 0)
1803 new_playeritem = max_item;
1808 for(u16 i=0; i<10; i++)
1810 const KeyPress *kp = NumberKey + (i + 1) % 10;
1811 if(input->wasKeyDown(*kp))
1813 if(i < PLAYER_INVENTORY_SIZE && i < hud.hotbar_itemcount)
1817 infostream<<"Selected item: "
1818 <<new_playeritem<<std::endl;
1823 // Viewing range selection
1824 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1826 draw_control.range_all = !draw_control.range_all;
1827 if(draw_control.range_all)
1829 infostream<<"Enabled full viewing range"<<std::endl;
1830 statustext = L"Enabled full viewing range";
1831 statustext_time = 0;
1835 infostream<<"Disabled full viewing range"<<std::endl;
1836 statustext = L"Disabled full viewing range";
1837 statustext_time = 0;
1841 // Print debug stacks
1842 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1844 dstream<<"-----------------------------------------"
1846 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1847 dstream<<"-----------------------------------------"
1849 debug_stacks_print();
1853 Mouse and camera control
1854 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1857 float turn_amount = 0;
1858 if((device->isWindowActive() && noMenuActive()) || random_input)
1862 // Mac OSX gets upset if this is set every frame
1863 if(device->getCursorControl()->isVisible())
1864 device->getCursorControl()->setVisible(false);
1867 if(first_loop_after_window_activation){
1868 //infostream<<"window active, first loop"<<std::endl;
1869 first_loop_after_window_activation = false;
1872 s32 dx = input->getMousePos().X - displaycenter.X;
1873 s32 dy = input->getMousePos().Y - displaycenter.Y;
1876 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1878 /*const float keyspeed = 500;
1879 if(input->isKeyDown(irr::KEY_UP))
1880 dy -= dtime * keyspeed;
1881 if(input->isKeyDown(irr::KEY_DOWN))
1882 dy += dtime * keyspeed;
1883 if(input->isKeyDown(irr::KEY_LEFT))
1884 dx -= dtime * keyspeed;
1885 if(input->isKeyDown(irr::KEY_RIGHT))
1886 dx += dtime * keyspeed;*/
1890 camera_pitch += dy*d;
1891 if(camera_pitch < -89.5) camera_pitch = -89.5;
1892 if(camera_pitch > 89.5) camera_pitch = 89.5;
1894 turn_amount = v2f(dx, dy).getLength() * d;
1896 input->setMousePos(displaycenter.X, displaycenter.Y);
1899 // Mac OSX gets upset if this is set every frame
1900 if(device->getCursorControl()->isVisible() == false)
1901 device->getCursorControl()->setVisible(true);
1903 //infostream<<"window inactive"<<std::endl;
1904 first_loop_after_window_activation = true;
1906 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1907 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1910 Player speed control
1924 PlayerControl control(
1925 input->isKeyDown(getKeySetting("keymap_forward")),
1926 input->isKeyDown(getKeySetting("keymap_backward")),
1927 input->isKeyDown(getKeySetting("keymap_left")),
1928 input->isKeyDown(getKeySetting("keymap_right")),
1929 input->isKeyDown(getKeySetting("keymap_jump")),
1930 input->isKeyDown(getKeySetting("keymap_special1")),
1931 input->isKeyDown(getKeySetting("keymap_sneak")),
1932 input->getLeftState(),
1933 input->getRightState(),
1937 client.setPlayerControl(control);
1939 1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
1940 2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
1941 4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
1942 8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
1943 16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
1944 32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
1945 64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
1946 128*(int)input->getLeftState()+
1947 256*(int)input->getRightState();
1948 LocalPlayer* player = client.getEnv().getLocalPlayer();
1949 player->keyPressed=keyPressed;
1958 //TimeTaker timer("server->step(dtime)");
1959 server->step(dtime);
1967 //TimeTaker timer("client.step(dtime)");
1969 //client.step(dtime_avg1);
1973 // Read client events
1976 ClientEvent event = client.getClientEvent();
1977 if(event.type == CE_NONE)
1981 else if(event.type == CE_PLAYER_DAMAGE &&
1982 client.getHP() != 0)
1984 //u16 damage = event.player_damage.amount;
1985 //infostream<<"Player damage: "<<damage<<std::endl;
1987 damage_flash += 100.0;
1988 damage_flash += 8.0 * event.player_damage.amount;
1990 player->hurt_tilt_timer = 1.5;
1991 player->hurt_tilt_strength = event.player_damage.amount/2;
1992 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
1994 else if(event.type == CE_PLAYER_FORCE_MOVE)
1996 camera_yaw = event.player_force_move.yaw;
1997 camera_pitch = event.player_force_move.pitch;
1999 else if(event.type == CE_DEATHSCREEN)
2001 if(respawn_menu_active)
2004 /*bool set_camera_point_target =
2005 event.deathscreen.set_camera_point_target;
2006 v3f camera_point_target;
2007 camera_point_target.X = event.deathscreen.camera_point_target_x;
2008 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2009 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2010 MainRespawnInitiator *respawner =
2011 new MainRespawnInitiator(
2012 &respawn_menu_active, &client);
2013 GUIDeathScreen *menu =
2014 new GUIDeathScreen(guienv, guiroot, -1,
2015 &g_menumgr, respawner);
2018 chat_backend.addMessage(L"", L"You died.");
2020 /* Handle visualization */
2024 LocalPlayer* player = client.getEnv().getLocalPlayer();
2025 player->hurt_tilt_timer = 0;
2026 player->hurt_tilt_strength = 0;
2028 /*LocalPlayer* player = client.getLocalPlayer();
2029 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2030 camera.update(player, busytime, screensize);*/
2032 else if (event.type == CE_SHOW_FORMSPEC)
2034 if (current_formspec == 0)
2037 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2039 GUIFormSpecMenu *menu =
2040 new GUIFormSpecMenu(device, guiroot, -1,
2043 menu->setFormSource(current_formspec);
2044 menu->setTextDest(new TextDestPlayerInventory(&client,*(event.show_formspec.formname)));
2050 current_formspec->setForm(*(event.show_formspec.formspec));
2052 delete(event.show_formspec.formspec);
2053 delete(event.show_formspec.formname);
2055 else if(event.type == CE_TEXTURES_UPDATED)
2057 update_wielded_item_trigger = true;
2059 else if(event.type == CE_SPAWN_PARTICLE)
2061 LocalPlayer* player = client.getEnv().getLocalPlayer();
2063 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2065 new Particle(gamedef, smgr, player, client.getEnv(),
2066 *event.spawn_particle.pos,
2067 *event.spawn_particle.vel,
2068 *event.spawn_particle.acc,
2069 event.spawn_particle.expirationtime,
2070 event.spawn_particle.size,
2071 event.spawn_particle.collisiondetection, ap);
2073 else if(event.type == CE_ADD_PARTICLESPAWNER)
2075 LocalPlayer* player = client.getEnv().getLocalPlayer();
2077 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2079 new ParticleSpawner(gamedef, smgr, player,
2080 event.add_particlespawner.amount,
2081 event.add_particlespawner.spawntime,
2082 *event.add_particlespawner.minpos,
2083 *event.add_particlespawner.maxpos,
2084 *event.add_particlespawner.minvel,
2085 *event.add_particlespawner.maxvel,
2086 *event.add_particlespawner.minacc,
2087 *event.add_particlespawner.maxacc,
2088 event.add_particlespawner.minexptime,
2089 event.add_particlespawner.maxexptime,
2090 event.add_particlespawner.minsize,
2091 event.add_particlespawner.maxsize,
2092 event.add_particlespawner.collisiondetection,
2094 event.add_particlespawner.id);
2096 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2098 delete_particlespawner (event.delete_particlespawner.id);
2100 else if (event.type == CE_HUDADD)
2102 u32 id = event.hudadd.id;
2103 size_t nhudelem = player->hud.size();
2104 if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2105 delete event.hudadd.pos;
2106 delete event.hudadd.name;
2107 delete event.hudadd.scale;
2108 delete event.hudadd.text;
2109 delete event.hudadd.align;
2110 delete event.hudadd.offset;
2114 HudElement *e = new HudElement;
2115 e->type = (HudElementType)event.hudadd.type;
2116 e->pos = *event.hudadd.pos;
2117 e->name = *event.hudadd.name;
2118 e->scale = *event.hudadd.scale;
2119 e->text = *event.hudadd.text;
2120 e->number = event.hudadd.number;
2121 e->item = event.hudadd.item;
2122 e->dir = event.hudadd.dir;
2123 e->align = *event.hudadd.align;
2124 e->offset = *event.hudadd.offset;
2127 player->hud.push_back(e);
2129 player->hud[id] = e;
2131 delete event.hudadd.pos;
2132 delete event.hudadd.name;
2133 delete event.hudadd.scale;
2134 delete event.hudadd.text;
2135 delete event.hudadd.align;
2136 delete event.hudadd.offset;
2138 else if (event.type == CE_HUDRM)
2140 u32 id = event.hudrm.id;
2141 if (id < player->hud.size() && player->hud[id]) {
2142 delete player->hud[id];
2143 player->hud[id] = NULL;
2146 else if (event.type == CE_HUDCHANGE)
2148 u32 id = event.hudchange.id;
2149 if (id >= player->hud.size() || !player->hud[id]) {
2150 delete event.hudchange.v2fdata;
2151 delete event.hudchange.sdata;
2155 HudElement* e = player->hud[id];
2156 switch (event.hudchange.stat) {
2158 e->pos = *event.hudchange.v2fdata;
2161 e->name = *event.hudchange.sdata;
2163 case HUD_STAT_SCALE:
2164 e->scale = *event.hudchange.v2fdata;
2167 e->text = *event.hudchange.sdata;
2169 case HUD_STAT_NUMBER:
2170 e->number = event.hudchange.data;
2173 e->item = event.hudchange.data;
2176 e->dir = event.hudchange.data;
2178 case HUD_STAT_ALIGN:
2179 e->align = *event.hudchange.v2fdata;
2181 case HUD_STAT_OFFSET:
2182 e->offset = *event.hudchange.v2fdata;
2186 delete event.hudchange.v2fdata;
2187 delete event.hudchange.sdata;
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_node.png"){
2351 infotext = L"Unknown node: ";
2352 infotext += narrow_to_wide(nodedef->get(n).name);
2360 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2364 infostream<<"Started digging"<<std::endl;
2365 client.interact(0, pointed);
2367 ldown_for_dig = true;
2369 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2371 // NOTE: Similar piece of code exists on the server side for
2373 // Get digging parameters
2374 DigParams params = getDigParams(nodedef->get(n).groups,
2375 &playeritem_toolcap);
2376 // If can't dig, try hand
2377 if(!params.diggable){
2378 const ItemDefinition &hand = itemdef->get("");
2379 const ToolCapabilities *tp = hand.tool_capabilities;
2381 params = getDigParams(nodedef->get(n).groups, tp);
2384 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2385 if(sound_dig.exists()){
2386 if(sound_dig.name == "__group"){
2387 if(params.main_group != ""){
2388 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2389 soundmaker.m_player_leftpunch_sound.name =
2390 std::string("default_dig_") +
2394 soundmaker.m_player_leftpunch_sound = sound_dig;
2398 float dig_time_complete = 0.0;
2400 if(params.diggable == false)
2402 // I guess nobody will wait for this long
2403 dig_time_complete = 10000000.0;
2407 dig_time_complete = params.time;
2408 if (g_settings->getBool("enable_particles"))
2410 const ContentFeatures &features =
2411 client.getNodeDefManager()->get(n);
2412 addPunchingParticles
2413 (gamedef, smgr, player, client.getEnv(),
2414 nodepos, features.tiles);
2418 if(dig_time_complete >= 0.001)
2420 dig_index = (u16)((float)crack_animation_length
2421 * dig_time/dig_time_complete);
2423 // This is for torches
2426 dig_index = crack_animation_length;
2429 // Don't show cracks if not diggable
2430 if(dig_time_complete >= 100000.0)
2433 else if(dig_index < crack_animation_length)
2435 //TimeTaker timer("client.setTempMod");
2436 //infostream<<"dig_index="<<dig_index<<std::endl;
2437 client.setCrack(dig_index, nodepos);
2441 infostream<<"Digging completed"<<std::endl;
2442 client.interact(2, pointed);
2443 client.setCrack(-1, v3s16(0,0,0));
2444 MapNode wasnode = map.getNode(nodepos);
2445 client.removeNode(nodepos);
2447 if (g_settings->getBool("enable_particles"))
2449 const ContentFeatures &features =
2450 client.getNodeDefManager()->get(wasnode);
2452 (gamedef, smgr, player, client.getEnv(),
2453 nodepos, features.tiles);
2459 nodig_delay_timer = dig_time_complete
2460 / (float)crack_animation_length;
2462 // We don't want a corresponding delay to
2463 // very time consuming nodes
2464 if(nodig_delay_timer > 0.3)
2465 nodig_delay_timer = 0.3;
2466 // We want a slight delay to very little
2467 // time consuming nodes
2468 float mindelay = 0.15;
2469 if(nodig_delay_timer < mindelay)
2470 nodig_delay_timer = mindelay;
2472 // Send event to trigger sound
2473 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2474 gamedef->event()->put(e);
2479 camera.setDigging(0); // left click animation
2482 if(input->getRightClicked() ||
2483 repeat_rightclick_timer >= g_settings->getFloat("repeat_rightclick_time"))
2485 repeat_rightclick_timer = 0;
2486 infostream<<"Ground right-clicked"<<std::endl;
2488 // Sign special case, at least until formspec is properly implemented.
2490 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2492 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2494 infostream<<"Launching metadata text input"<<std::endl;
2496 // Get a new text for it
2498 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2500 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2502 (new GUITextInputMenu(guienv, guiroot, -1,
2506 // If metadata provides an inventory view, activate it
2507 else if(meta && meta->getString("formspec") != "" && !random_input
2508 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2510 infostream<<"Launching custom inventory view"<<std::endl;
2512 InventoryLocation inventoryloc;
2513 inventoryloc.setNodeMeta(nodepos);
2517 GUIFormSpecMenu *menu =
2518 new GUIFormSpecMenu(device, guiroot, -1,
2521 menu->setFormSpec(meta->getString("formspec"),
2523 menu->setFormSource(new NodeMetadataFormSource(
2524 &client.getEnv().getClientMap(), nodepos));
2525 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2528 // Otherwise report right click to server
2532 client.interact(3, pointed);
2533 camera.setDigging(1); // right click animation
2535 // If the wielded item has node placement prediction,
2537 const ItemDefinition &def =
2538 playeritem.getDefinition(itemdef);
2539 if(def.node_placement_prediction != ""
2540 && !nodedef->get(map.getNode(nodepos)).rightclickable)
2542 verbosestream<<"Node placement prediction for "
2543 <<playeritem.name<<" is "
2544 <<def.node_placement_prediction<<std::endl;
2545 v3s16 p = neighbourpos;
2546 // Place inside node itself if buildable_to
2548 MapNode n_under = map.getNode(nodepos);
2549 if(nodedef->get(n_under).buildable_to)
2551 }catch(InvalidPositionException &e){}
2552 // Find id of predicted node
2555 nodedef->getId(def.node_placement_prediction, id);
2557 errorstream<<"Node placement prediction failed for "
2558 <<playeritem.name<<" (places "
2559 <<def.node_placement_prediction
2560 <<") - Name not known"<<std::endl;
2565 // This triggers the required mesh update too
2566 client.addNode(p, n);
2567 }catch(InvalidPositionException &e){
2568 errorstream<<"Node placement prediction failed for "
2569 <<playeritem.name<<" (places "
2570 <<def.node_placement_prediction
2571 <<") - Position not loaded"<<std::endl;
2576 soundmaker.m_player_rightpunch_sound = def.sound_place;
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());
2737 allparticlespawners_step(dtime, client.getEnv());
2743 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2747 video::EFT_FOG_LINEAR,
2759 video::EFT_FOG_LINEAR,
2769 Update gui stuff (0ms)
2772 //TimeTaker guiupdatetimer("Gui updating");
2774 const char program_name_and_version[] =
2775 "Minetest " VERSION_STRING;
2779 static float drawtime_avg = 0;
2780 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2781 /*static float beginscenetime_avg = 0;
2782 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2783 static float scenetime_avg = 0;
2784 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2785 static float endscenetime_avg = 0;
2786 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2789 snprintf(temptext, 300, "%s ("
2792 " drawtime=%.0f, dtime_jitter = % .1f %%"
2793 ", v_range = %.1f, RTT = %.3f",
2794 program_name_and_version,
2795 draw_control.range_all,
2797 dtime_jitter1_max_fraction * 100.0,
2798 draw_control.wanted_range,
2802 guitext->setText(narrow_to_wide(temptext).c_str());
2803 guitext->setVisible(true);
2805 else if(show_hud || show_chat)
2807 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2808 guitext->setVisible(true);
2812 guitext->setVisible(false);
2818 snprintf(temptext, 300,
2819 "(% .1f, % .1f, % .1f)"
2820 " (yaw = %.1f) (seed = %llu)",
2821 player_position.X/BS,
2822 player_position.Y/BS,
2823 player_position.Z/BS,
2824 wrapDegrees_0_360(camera_yaw),
2825 (unsigned long long)client.getMapSeed());
2827 guitext2->setText(narrow_to_wide(temptext).c_str());
2828 guitext2->setVisible(true);
2832 guitext2->setVisible(false);
2836 guitext_info->setText(infotext.c_str());
2837 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2841 float statustext_time_max = 1.5;
2842 if(!statustext.empty())
2844 statustext_time += dtime;
2845 if(statustext_time >= statustext_time_max)
2848 statustext_time = 0;
2851 guitext_status->setText(statustext.c_str());
2852 guitext_status->setVisible(!statustext.empty());
2854 if(!statustext.empty())
2856 s32 status_y = screensize.Y - 130;
2857 core::rect<s32> rect(
2859 status_y - guitext_status->getTextHeight(),
2863 guitext_status->setRelativePosition(rect);
2866 video::SColor initial_color(255,0,0,0);
2867 if(guienv->getSkin())
2868 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2869 video::SColor final_color = initial_color;
2870 final_color.setAlpha(0);
2871 video::SColor fade_color =
2872 initial_color.getInterpolated_quadratic(
2875 pow(statustext_time / (float)statustext_time_max, 2.0f));
2876 guitext_status->setOverrideColor(fade_color);
2877 guitext_status->enableOverrideColor(true);
2882 Get chat messages from client
2885 // Get new messages from error log buffer
2886 while(!chat_log_error_buf.empty())
2888 chat_backend.addMessage(L"", narrow_to_wide(
2889 chat_log_error_buf.get()));
2891 // Get new messages from client
2892 std::wstring message;
2893 while(client.getChatMessage(message))
2895 chat_backend.addUnparsedMessage(message);
2897 // Remove old messages
2898 chat_backend.step(dtime);
2900 // Display all messages in a static text element
2901 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2902 std::wstring recent_chat = chat_backend.getRecentChat();
2903 guitext_chat->setText(recent_chat.c_str());
2905 // Update gui element size and position
2906 s32 chat_y = 5+(text_height+5);
2908 chat_y += (text_height+5);
2909 core::rect<s32> rect(
2913 chat_y + guitext_chat->getTextHeight()
2915 guitext_chat->setRelativePosition(rect);
2917 // Don't show chat if disabled or empty or profiler is enabled
2918 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2926 if(client.getPlayerItem() != new_playeritem)
2928 client.selectPlayerItem(new_playeritem);
2930 if(client.getLocalInventoryUpdated())
2932 //infostream<<"Updating local inventory"<<std::endl;
2933 client.getLocalInventory(local_inventory);
2935 update_wielded_item_trigger = true;
2937 if(update_wielded_item_trigger)
2939 update_wielded_item_trigger = false;
2940 // Update wielded tool
2941 InventoryList *mlist = local_inventory.getList("main");
2944 item = mlist->getItem(client.getPlayerItem());
2949 Update block draw list every 200ms or when camera direction has
2952 update_draw_list_timer += dtime;
2953 if(update_draw_list_timer >= 0.2 ||
2954 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
2955 update_draw_list_timer = 0;
2956 client.getEnv().getClientMap().updateDrawList(driver);
2957 update_draw_list_last_cam_dir = camera_direction;
2964 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);
3069 hud.drawSelectionBoxes(hilightboxes);
3075 // Warning: This clears the Z buffer.
3076 camera.drawWieldedTool();
3083 client.getEnv().getClientMap().renderPostFx();
3089 if(show_profiler_graph)
3091 graph.draw(10, screensize.Y - 10, driver, font);
3098 hud.drawCrosshair();
3103 //TimeTaker //timer11("//timer11");
3111 hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
3112 client.getHP(), client.getPlayerItem());
3118 if(damage_flash > 0.0)
3120 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3121 driver->draw2DRectangle(color,
3122 core::rect<s32>(0,0,screensize.X,screensize.Y),
3125 damage_flash -= 100.0*dtime;
3131 if(player->hurt_tilt_timer > 0.0)
3133 player->hurt_tilt_timer -= dtime*5;
3134 if(player->hurt_tilt_timer < 0)
3135 player->hurt_tilt_strength = 0;
3142 hud.drawLuaElements();
3154 TimeTaker timer("endScene");
3156 endscenetime = timer.stop(true);
3159 drawtime = tt_draw.stop(true);
3160 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3166 static s16 lastFPS = 0;
3167 //u16 fps = driver->getFPS();
3168 u16 fps = (1.0/dtime_avg1);
3172 core::stringw str = L"Minetest [";
3173 str += driver->getName();
3177 device->setWindowCaption(str.c_str());
3182 Log times and stuff for visualization
3184 Profiler::GraphValues values;
3185 g_profiler->graphGet(values);
3194 if (gui_chat_console)
3195 gui_chat_console->drop();
3199 Draw a "shutting down" screen, which will be shown while the map
3200 generator and other stuff quits
3203 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3204 draw_load_screen(L"Shutting down stuff...", driver, font);
3205 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3208 gui_shuttingdowntext->remove();*/
3211 chat_backend.addMessage(L"", L"# Disconnected.");
3212 chat_backend.addMessage(L"", L"");
3214 // Client scope (client is destructed before destructing *def and tsrc)
3217 catch(SerializationError &e)
3219 error_message = L"A serialization error occurred:\n"
3220 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3221 L" running a different version of Minetest.";
3222 errorstream<<wide_to_narrow(error_message)<<std::endl;
3224 catch(ServerError &e)
3226 error_message = narrow_to_wide(e.what());
3227 errorstream<<wide_to_narrow(error_message)<<std::endl;
3231 errorstream<<e.what()<<std::endl;
3232 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3240 //has to be deleted first to stop all server threads
3248 //extended resource accounting
3249 infostream << "Irrlicht resources after cleanup:" << std::endl;
3250 infostream << "\tRemaining meshes : "
3251 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3252 infostream << "\tRemaining textures : "
3253 << driver->getTextureCount() << std::endl;
3254 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3255 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3256 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3259 infostream << "\tRemaining materials: "
3260 << driver-> getMaterialRendererCount ()
3261 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;