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.
25 #include "client/tile.h" // For TextureSource
26 #include "clientmap.h"
29 #include "content_cao.h"
30 #include "drawscene.h"
31 #include "event_manager.h"
32 #include "fontengine.h"
37 #include "guiChatConsole.h"
38 #include "guiFormSpecMenu.h"
39 #include "guiKeyChangeMenu.h"
40 #include "guiPasswordChange.h"
41 #include "guiVolumeChange.h"
43 #include "mainmenumanager.h"
45 #include "nodedef.h" // Needed for determining pointing to nodes
46 #include "nodemetadata.h"
47 #include "particles.h"
49 #include "quicktune_shortcutter.h"
52 #include "shader.h" // For ShaderSource
56 #include "util/directiontables.h"
57 #include "util/pointedthing.h"
60 #include "mapblock_mesh.h"
65 #include "sound_openal.h"
68 #ifdef HAVE_TOUCHSCREENGUI
69 #include "touchscreengui.h"
72 extern Settings *g_settings;
73 extern Profiler *g_profiler;
79 struct TextDestNodeMetadata : public TextDest {
80 TextDestNodeMetadata(v3s16 p, Client *client)
85 // This is deprecated I guess? -celeron55
86 void gotText(std::wstring text)
88 std::string ntext = wide_to_utf8(text);
89 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
90 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
92 fields["text"] = ntext;
93 m_client->sendNodemetaFields(m_p, "", fields);
95 void gotText(const StringMap &fields)
97 m_client->sendNodemetaFields(m_p, "", fields);
104 struct TextDestPlayerInventory : public TextDest {
105 TextDestPlayerInventory(Client *client)
110 TextDestPlayerInventory(Client *client, std::string formname)
113 m_formname = formname;
115 void gotText(const StringMap &fields)
117 m_client->sendInventoryFields(m_formname, fields);
123 struct LocalFormspecHandler : public TextDest {
124 LocalFormspecHandler();
125 LocalFormspecHandler(std::string formname) :
128 m_formname = formname;
131 LocalFormspecHandler(std::string formname, Client *client) :
134 m_formname = formname;
137 void gotText(std::wstring message)
139 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
142 void gotText(const StringMap &fields)
144 if (m_formname == "MT_PAUSE_MENU") {
145 if (fields.find("btn_sound") != fields.end()) {
146 g_gamecallback->changeVolume();
150 if (fields.find("btn_key_config") != fields.end()) {
151 g_gamecallback->keyConfig();
155 if (fields.find("btn_exit_menu") != fields.end()) {
156 g_gamecallback->disconnect();
160 if (fields.find("btn_exit_os") != fields.end()) {
161 g_gamecallback->exitToOS();
165 if (fields.find("btn_change_password") != fields.end()) {
166 g_gamecallback->changePassword();
170 if (fields.find("quit") != fields.end()) {
174 if (fields.find("btn_continue") != fields.end()) {
179 if (m_formname == "MT_CHAT_MENU") {
180 assert(m_client != 0);
182 if ((fields.find("btn_send") != fields.end()) ||
183 (fields.find("quit") != fields.end())) {
184 StringMap::const_iterator it = fields.find("f_text");
185 if (it != fields.end())
186 m_client->typeChatMessage(utf8_to_wide(it->second));
192 if (m_formname == "MT_DEATH_SCREEN") {
193 assert(m_client != 0);
195 if ((fields.find("btn_respawn") != fields.end())) {
196 m_client->sendRespawn();
200 if (fields.find("quit") != fields.end()) {
201 m_client->sendRespawn();
206 // don't show error message for unhandled cursor keys
207 if ((fields.find("key_up") != fields.end()) ||
208 (fields.find("key_down") != fields.end()) ||
209 (fields.find("key_left") != fields.end()) ||
210 (fields.find("key_right") != fields.end())) {
214 errorstream << "LocalFormspecHandler::gotText unhandled >"
215 << m_formname << "< event" << std::endl;
218 StringMap::const_iterator it;
219 for (it = fields.begin(); it != fields.end(); ++it) {
220 errorstream << "\t" << i << ": " << it->first
221 << "=" << it->second << std::endl;
229 /* Form update callback */
231 class NodeMetadataFormSource: public IFormSource
234 NodeMetadataFormSource(ClientMap *map, v3s16 p):
239 std::string getForm()
241 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
246 return meta->getString("formspec");
248 std::string resolveText(std::string str)
250 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
255 return meta->resolveString(str);
262 class PlayerInventoryFormSource: public IFormSource
265 PlayerInventoryFormSource(Client *client):
269 std::string getForm()
271 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
272 return player->inventory_formspec;
279 Check if a node is pointable
281 inline bool isPointableNode(const MapNode &n,
282 Client *client, bool liquids_pointable)
284 const ContentFeatures &features = client->getNodeDefManager()->get(n);
285 return features.pointable ||
286 (liquids_pointable && features.isLiquid());
290 Find what the player is pointing at
292 PointedThing getPointedThing(Client *client, Hud *hud, const v3f &player_position,
293 const v3f &camera_direction, const v3f &camera_position,
294 core::line3d<f32> shootline, f32 d, bool liquids_pointable,
295 bool look_for_object, const v3s16 &camera_offset,
296 ClientActiveObject *&selected_object)
300 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
301 selectionboxes->clear();
302 selected_object = NULL;
304 INodeDefManager *nodedef = client->getNodeDefManager();
305 ClientMap &map = client->getEnv().getClientMap();
307 f32 min_distance = BS * 1001;
309 // First try to find a pointed at active object
310 if (look_for_object) {
311 selected_object = client->getSelectedActiveObject(d * BS,
312 camera_position, shootline);
314 if (selected_object != NULL) {
315 if (selected_object->doShowSelectionBox()) {
316 aabb3f *selection_box = selected_object->getSelectionBox();
317 // Box should exist because object was
318 // returned in the first place
319 assert(selection_box);
321 v3f pos = selected_object->getPosition();
322 selectionboxes->push_back(aabb3f(
323 selection_box->MinEdge, selection_box->MaxEdge));
324 hud->setSelectionPos(pos, camera_offset);
327 min_distance = (selected_object->getPosition() - camera_position).getLength();
329 result.type = POINTEDTHING_OBJECT;
330 result.object_id = selected_object->getId();
334 // That didn't work, try to find a pointed at node
336 v3s16 pos_i = floatToInt(player_position, BS);
338 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
342 s16 ystart = pos_i.Y - (camera_direction.Y < 0 ? a : 1);
343 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
344 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
345 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
346 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
347 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
349 // Prevent signed number overflow
359 v3s16 pointed_pos(0, 0, 0);
361 for (s16 y = ystart; y <= yend; y++) {
362 for (s16 z = zstart; z <= zend; z++) {
363 for (s16 x = xstart; x <= xend; x++) {
365 bool is_valid_position;
367 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
368 if (!is_valid_position) {
371 if (!isPointableNode(n, client, liquids_pointable)) {
374 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
377 v3f npf = intToFloat(np, BS);
378 for (std::vector<aabb3f>::const_iterator
380 i != boxes.end(); ++i) {
385 v3f centerpoint = box.getCenter();
386 f32 distance = (centerpoint - camera_position).getLength();
387 if (distance >= min_distance) {
390 if (!box.intersectsWithLine(shootline)) {
393 result.type = POINTEDTHING_NODE;
394 min_distance = distance;
401 if (result.type == POINTEDTHING_NODE) {
403 MapNode n = map.getNodeNoEx(pointed_pos);
404 v3f npf = intToFloat(pointed_pos, BS);
405 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
406 f32 face_min_distance = 1000 * BS;
407 for (std::vector<aabb3f>::const_iterator
409 i != boxes.end(); ++i) {
413 for (u16 j = 0; j < 6; j++) {
414 v3s16 facedir = g_6dirs[j];
415 aabb3f facebox = box;
417 facebox.MinEdge.X = facebox.MaxEdge.X - d;
418 } else if (facedir.X < 0) {
419 facebox.MaxEdge.X = facebox.MinEdge.X + d;
420 } else if (facedir.Y > 0) {
421 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
422 } else if (facedir.Y < 0) {
423 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
424 } else if (facedir.Z > 0) {
425 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
426 } else if (facedir.Z < 0) {
427 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
429 v3f centerpoint = facebox.getCenter();
430 f32 distance = (centerpoint - camera_position).getLength();
431 if (distance >= face_min_distance)
433 if (!facebox.intersectsWithLine(shootline))
435 result.node_abovesurface = pointed_pos + facedir;
436 face_min_distance = distance;
439 selectionboxes->clear();
440 for (std::vector<aabb3f>::const_iterator
442 i != boxes.end(); ++i) {
444 box.MinEdge += v3f(-d, -d, -d);
445 box.MaxEdge += v3f(d, d, d);
446 selectionboxes->push_back(box);
448 hud->setSelectionPos(intToFloat(pointed_pos, BS), camera_offset);
449 result.node_undersurface = pointed_pos;
452 // Update selection mesh light level and vertex colors
453 if (selectionboxes->size() > 0) {
454 v3f pf = hud->getSelectionPos();
455 v3s16 p = floatToInt(pf, BS);
457 // Get selection mesh light level
458 MapNode n = map.getNodeNoEx(p);
459 u16 node_light = getInteriorLight(n, -1, nodedef);
460 u16 light_level = node_light;
462 for (u8 i = 0; i < 6; i++) {
463 n = map.getNodeNoEx(p + g_6dirs[i]);
464 node_light = getInteriorLight(n, -1, nodedef);
465 if (node_light > light_level)
466 light_level = node_light;
469 video::SColor c = MapBlock_LightColor(255, light_level, 0);
471 u8 night = c.getGreen();
472 u32 daynight_ratio = client->getEnv().getDayNightRatio();
473 finalColorBlend(c, day, night, daynight_ratio);
475 // Modify final color a bit with time
476 u32 timer = porting::getTimeMs() % 5000;
477 float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
478 float sin_r = 0.08 * sin(timerf);
479 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
480 float sin_b = 0.08 * sin(timerf + irr::core::PI);
481 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
482 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
483 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
485 // Set mesh final color
486 hud->setSelectionMeshColor(c);
491 /* Profiler display */
493 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
494 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
496 if (show_profiler == 0) {
497 guitext_profiler->setVisible(false);
500 std::ostringstream os(std::ios_base::binary);
501 g_profiler->printPage(os, show_profiler, show_profiler_max);
502 std::wstring text = utf8_to_wide(os.str());
503 guitext_profiler->setText(text.c_str());
504 guitext_profiler->setVisible(true);
506 s32 w = fe->getTextWidth(text.c_str());
511 unsigned text_height = fe->getTextHeight();
513 core::position2di upper_left, lower_right;
516 upper_left.Y = (text_height + 5) * 2;
517 lower_right.X = 12 + w;
518 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
520 if (lower_right.Y > screen_height * 2 / 3)
521 lower_right.Y = screen_height * 2 / 3;
523 core::rect<s32> rect(upper_left, lower_right);
525 guitext_profiler->setRelativePosition(rect);
526 guitext_profiler->setVisible(true);
534 Profiler::GraphValues values;
540 Meta(float initial = 0,
541 video::SColor color = video::SColor(255, 255, 255, 255)):
547 std::deque<Piece> m_log;
555 void put(const Profiler::GraphValues &values)
558 piece.values = values;
559 m_log.push_back(piece);
561 while (m_log.size() > m_log_max_size)
562 m_log.erase(m_log.begin());
565 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
566 gui::IGUIFont *font) const
568 std::map<std::string, Meta> m_meta;
570 for (std::deque<Piece>::const_iterator k = m_log.begin();
571 k != m_log.end(); ++k) {
572 const Piece &piece = *k;
574 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
575 i != piece.values.end(); ++i) {
576 const std::string &id = i->first;
577 const float &value = i->second;
578 std::map<std::string, Meta>::iterator j =
581 if (j == m_meta.end()) {
582 m_meta[id] = Meta(value);
586 if (value < j->second.min)
587 j->second.min = value;
589 if (value > j->second.max)
590 j->second.max = value;
595 static const video::SColor usable_colors[] = {
596 video::SColor(255, 255, 100, 100),
597 video::SColor(255, 90, 225, 90),
598 video::SColor(255, 100, 100, 255),
599 video::SColor(255, 255, 150, 50),
600 video::SColor(255, 220, 220, 100)
602 static const u32 usable_colors_count =
603 sizeof(usable_colors) / sizeof(*usable_colors);
604 u32 next_color_i = 0;
606 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
607 i != m_meta.end(); ++i) {
608 Meta &meta = i->second;
609 video::SColor color(255, 200, 200, 200);
611 if (next_color_i < usable_colors_count)
612 color = usable_colors[next_color_i++];
618 s32 textx = x_left + m_log_max_size + 15;
619 s32 textx2 = textx + 200 - 15;
622 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
623 i != m_meta.end(); ++i) {
624 const std::string &id = i->first;
625 const Meta &meta = i->second;
627 s32 y = y_bottom - meta_i * 50;
628 float show_min = meta.min;
629 float show_max = meta.max;
631 if (show_min >= -0.0001 && show_max >= -0.0001) {
632 if (show_min <= show_max * 0.5)
638 snprintf(buf, 10, "%.3g", show_max);
639 font->draw(utf8_to_wide(buf).c_str(),
640 core::rect<s32>(textx, y - graphh,
641 textx2, y - graphh + texth),
643 snprintf(buf, 10, "%.3g", show_min);
644 font->draw(utf8_to_wide(buf).c_str(),
645 core::rect<s32>(textx, y - texth,
648 font->draw(utf8_to_wide(id).c_str(),
649 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
650 textx2, y - graphh / 2 + texth / 2),
653 s32 graph1h = graphh;
654 bool relativegraph = (show_min != 0 && show_min != show_max);
655 float lastscaledvalue = 0.0;
656 bool lastscaledvalue_exists = false;
658 for (std::deque<Piece>::const_iterator j = m_log.begin();
659 j != m_log.end(); ++j) {
660 const Piece &piece = *j;
662 bool value_exists = false;
663 Profiler::GraphValues::const_iterator k =
664 piece.values.find(id);
666 if (k != piece.values.end()) {
673 lastscaledvalue_exists = false;
677 float scaledvalue = 1.0;
679 if (show_max != show_min)
680 scaledvalue = (value - show_min) / (show_max - show_min);
682 if (scaledvalue == 1.0 && value == 0) {
684 lastscaledvalue_exists = false;
689 if (lastscaledvalue_exists) {
690 s32 ivalue1 = lastscaledvalue * graph1h;
691 s32 ivalue2 = scaledvalue * graph1h;
692 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
693 v2s32(x, graph1y - ivalue2), meta.color);
696 lastscaledvalue = scaledvalue;
697 lastscaledvalue_exists = true;
699 s32 ivalue = scaledvalue * graph1h;
700 driver->draw2DLine(v2s32(x, graph1y),
701 v2s32(x, graph1y - ivalue), meta.color);
712 class NodeDugEvent: public MtEvent
718 NodeDugEvent(v3s16 p, MapNode n):
722 const char *getType() const
730 ISoundManager *m_sound;
731 INodeDefManager *m_ndef;
733 float m_player_step_timer;
735 SimpleSoundSpec m_player_step_sound;
736 SimpleSoundSpec m_player_leftpunch_sound;
737 SimpleSoundSpec m_player_rightpunch_sound;
739 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
742 m_player_step_timer(0)
746 void playPlayerStep()
748 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
749 m_player_step_timer = 0.03;
750 m_sound->playSound(m_player_step_sound, false);
754 static void viewBobbingStep(MtEvent *e, void *data)
756 SoundMaker *sm = (SoundMaker *)data;
757 sm->playPlayerStep();
760 static void playerRegainGround(MtEvent *e, void *data)
762 SoundMaker *sm = (SoundMaker *)data;
763 sm->playPlayerStep();
766 static void playerJump(MtEvent *e, void *data)
768 //SoundMaker *sm = (SoundMaker*)data;
771 static void cameraPunchLeft(MtEvent *e, void *data)
773 SoundMaker *sm = (SoundMaker *)data;
774 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
777 static void cameraPunchRight(MtEvent *e, void *data)
779 SoundMaker *sm = (SoundMaker *)data;
780 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
783 static void nodeDug(MtEvent *e, void *data)
785 SoundMaker *sm = (SoundMaker *)data;
786 NodeDugEvent *nde = (NodeDugEvent *)e;
787 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
790 static void playerDamage(MtEvent *e, void *data)
792 SoundMaker *sm = (SoundMaker *)data;
793 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
796 static void playerFallingDamage(MtEvent *e, void *data)
798 SoundMaker *sm = (SoundMaker *)data;
799 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
802 void registerReceiver(MtEventManager *mgr)
804 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
805 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
806 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
807 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
808 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
809 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
810 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
811 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
814 void step(float dtime)
816 m_player_step_timer -= dtime;
820 // Locally stored sounds don't need to be preloaded because of this
821 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
823 std::set<std::string> m_fetched;
825 void fetchSounds(const std::string &name,
826 std::set<std::string> &dst_paths,
827 std::set<std::string> &dst_datas)
829 if (m_fetched.count(name))
832 m_fetched.insert(name);
833 std::string base = porting::path_share + DIR_DELIM + "testsounds";
834 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
835 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
836 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
837 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
838 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
839 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
840 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
841 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
842 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
843 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
844 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
848 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
851 bool *m_force_fog_off;
857 void onSettingsChange(const std::string &name)
859 if (name == "enable_fog")
860 m_fogEnabled = g_settings->getBool("enable_fog");
863 static void SettingsCallback(const std::string &name, void *userdata)
865 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
868 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
869 f32 *fog_range, Client *client) :
871 m_force_fog_off(force_fog_off),
872 m_fog_range(fog_range),
875 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
876 m_fogEnabled = g_settings->getBool("enable_fog");
879 ~GameGlobalShaderConstantSetter()
881 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
884 virtual void onSetConstants(video::IMaterialRendererServices *services,
891 video::SColor bgcolor = m_sky->getBgColor();
892 video::SColorf bgcolorf(bgcolor);
893 float bgcolorfa[4] = {
899 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
902 float fog_distance = 10000 * BS;
904 if (m_fogEnabled && !*m_force_fog_off)
905 fog_distance = *m_fog_range;
907 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
910 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
911 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
912 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
914 u32 animation_timer = porting::getTimeMs() % 100000;
915 float animation_timer_f = (float)animation_timer / 100000.0;
916 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
917 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
919 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
920 v3f eye_position = player->getEyePosition();
921 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
922 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
924 v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
925 services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
927 // Uniform sampler layers
928 // before 1.8 there isn't a "integer interface", only float
929 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
933 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
934 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
935 services->setPixelShaderConstant("textureFlags" , (irr::f32 *)&layer2, 1);
940 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
941 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
942 services->setPixelShaderConstant("textureFlags" , (irr::s32 *)&layer2, 1);
947 bool nodePlacementPrediction(Client &client,
948 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
950 std::string prediction = playeritem_def.node_placement_prediction;
951 INodeDefManager *nodedef = client.ndef();
952 ClientMap &map = client.getEnv().getClientMap();
954 bool is_valid_position;
956 node = map.getNodeNoEx(nodepos, &is_valid_position);
957 if (!is_valid_position)
960 if (prediction != "" && !nodedef->get(node).rightclickable) {
961 verbosestream << "Node placement prediction for "
962 << playeritem_def.name << " is "
963 << prediction << std::endl;
964 v3s16 p = neighbourpos;
966 // Place inside node itself if buildable_to
967 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
968 if (is_valid_position)
970 if (nodedef->get(n_under).buildable_to)
973 node = map.getNodeNoEx(p, &is_valid_position);
974 if (is_valid_position &&!nodedef->get(node).buildable_to)
979 // Find id of predicted node
981 bool found = nodedef->getId(prediction, id);
984 errorstream << "Node placement prediction failed for "
985 << playeritem_def.name << " (places "
987 << ") - Name not known" << std::endl;
991 // Predict param2 for facedir and wallmounted nodes
994 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
995 v3s16 dir = nodepos - neighbourpos;
997 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
998 param2 = dir.Y < 0 ? 1 : 0;
999 } else if (abs(dir.X) > abs(dir.Z)) {
1000 param2 = dir.X < 0 ? 3 : 2;
1002 param2 = dir.Z < 0 ? 5 : 4;
1006 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
1007 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
1009 if (abs(dir.X) > abs(dir.Z)) {
1010 param2 = dir.X < 0 ? 3 : 1;
1012 param2 = dir.Z < 0 ? 2 : 0;
1016 assert(param2 <= 5);
1018 //Check attachment if node is in group attached_node
1019 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
1020 static v3s16 wallmounted_dirs[8] = {
1030 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
1031 pp = p + wallmounted_dirs[param2];
1033 pp = p + v3s16(0, -1, 0);
1035 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
1039 // Add node to client map
1040 MapNode n(id, 0, param2);
1043 LocalPlayer *player = client.getEnv().getLocalPlayer();
1045 // Dont place node when player would be inside new node
1046 // NOTE: This is to be eventually implemented by a mod as client-side Lua
1047 if (!nodedef->get(n).walkable ||
1048 g_settings->getBool("enable_build_where_you_stand") ||
1049 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1050 (nodedef->get(n).walkable &&
1051 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1052 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1054 // This triggers the required mesh update too
1055 client.addNode(p, n);
1058 } catch (InvalidPositionException &e) {
1059 errorstream << "Node placement prediction failed for "
1060 << playeritem_def.name << " (places "
1062 << ") - Position not loaded" << std::endl;
1069 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1070 InventoryManager *invmgr, IGameDef *gamedef,
1071 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1072 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1075 if (*cur_formspec == 0) {
1076 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1077 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1078 (*cur_formspec)->doPause = false;
1081 Caution: do not call (*cur_formspec)->drop() here --
1082 the reference might outlive the menu, so we will
1083 periodically check if *cur_formspec is the only
1084 remaining reference (i.e. the menu was removed)
1085 and delete it in that case.
1089 (*cur_formspec)->setFormSource(fs_src);
1090 (*cur_formspec)->setTextDest(txt_dest);
1095 #define SIZE_TAG "size[11,5.5]"
1097 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1100 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1101 InventoryManager *invmgr, IGameDef *gamedef,
1102 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1103 Client *client, std::string text)
1105 std::string formspec =
1106 FORMSPEC_VERSION_STRING
1108 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1109 "button_exit[4,3;3,0.5;btn_send;" + strgettext("Proceed") + "]"
1113 /* Note: FormspecFormSource and LocalFormspecHandler
1114 * are deleted by guiFormSpecMenu */
1115 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1116 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1118 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1121 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1122 InventoryManager *invmgr, IGameDef *gamedef,
1123 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1125 std::string formspec =
1126 std::string(FORMSPEC_VERSION_STRING) +
1128 "bgcolor[#320000b4;true]"
1129 "label[4.85,1.35;" + gettext("You died.") + "]"
1130 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1134 /* Note: FormspecFormSource and LocalFormspecHandler
1135 * are deleted by guiFormSpecMenu */
1136 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1137 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1139 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1142 /******************************************************************************/
1143 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1144 InventoryManager *invmgr, IGameDef *gamedef,
1145 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1146 bool singleplayermode)
1149 std::string control_text = strgettext("Default Controls:\n"
1150 "No menu visible:\n"
1151 "- single tap: button activate\n"
1152 "- double tap: place/use\n"
1153 "- slide finger: look around\n"
1154 "Menu/Inventory visible:\n"
1155 "- double tap (outside):\n"
1157 "- touch stack, touch slot:\n"
1159 "- touch&drag, tap 2nd finger\n"
1160 " --> place single item to slot\n"
1163 std::string control_text = strgettext("Default Controls:\n"
1165 "- Space: jump/climb\n"
1166 "- Shift: sneak/go down\n"
1169 "- Mouse: turn/look\n"
1170 "- Mouse left: dig/punch\n"
1171 "- Mouse right: place/use\n"
1172 "- Mouse wheel: select item\n"
1177 float ypos = singleplayermode ? 0.5 : 0.1;
1178 std::ostringstream os;
1180 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1181 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1182 << strgettext("Continue") << "]";
1184 if (!singleplayermode) {
1185 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1186 << strgettext("Change Password") << "]";
1190 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1191 << strgettext("Sound Volume") << "]";
1192 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1193 << strgettext("Change Keys") << "]";
1195 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1196 << strgettext("Exit to Menu") << "]";
1197 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1198 << strgettext("Exit to OS") << "]"
1199 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1200 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1201 << g_build_info << "\n"
1202 << "path_user = " << wrap_rows(porting::path_user, 20)
1206 /* Note: FormspecFormSource and LocalFormspecHandler *
1207 * are deleted by guiFormSpecMenu */
1208 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1209 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1211 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1212 std::string con("btn_continue");
1213 (*cur_formspec)->setFocus(con);
1214 (*cur_formspec)->doPause = true;
1217 /******************************************************************************/
1218 static void updateChat(Client &client, f32 dtime, bool show_debug,
1219 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1220 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1222 // Add chat log output for errors to be shown in chat
1223 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1225 // Get new messages from error log buffer
1226 while (!chat_log_error_buf.empty()) {
1227 chat_backend.addMessage(L"", utf8_to_wide(chat_log_error_buf.get()));
1230 // Get new messages from client
1231 std::wstring message;
1233 while (client.getChatMessage(message)) {
1234 chat_backend.addUnparsedMessage(message);
1237 // Remove old messages
1238 chat_backend.step(dtime);
1240 // Display all messages in a static text element
1241 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1242 std::wstring recent_chat = chat_backend.getRecentChat();
1243 unsigned int line_height = g_fontengine->getLineHeight();
1245 guitext_chat->setText(recent_chat.c_str());
1247 // Update gui element size and position
1248 s32 chat_y = 5 + line_height;
1251 chat_y += line_height;
1253 // first pass to calculate height of text to be set
1254 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1255 porting::getWindowSize().X - 20);
1256 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1257 guitext_chat->setRelativePosition(rect);
1259 //now use real height of text and adjust rect according to this size
1260 rect = core::rect<s32>(10, chat_y, width,
1261 chat_y + guitext_chat->getTextHeight());
1264 guitext_chat->setRelativePosition(rect);
1265 // Don't show chat if disabled or empty or profiler is enabled
1266 guitext_chat->setVisible(
1267 show_chat && recent_chat_count != 0 && !show_profiler);
1271 /****************************************************************************
1272 Fast key cache for main game loop
1273 ****************************************************************************/
1275 /* This is faster than using getKeySetting with the tradeoff that functions
1276 * using it must make sure that it's initialised before using it and there is
1277 * no error handling (for example bounds checking). This is really intended for
1278 * use only in the main running loop of the client (the_game()) where the faster
1279 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1280 * (e.g. formspecs) should continue using getKeySetting().
1284 KeyCache() { populate(); }
1299 KEYMAP_ID_INVENTORY,
1307 KEYMAP_ID_CINEMATIC,
1308 KEYMAP_ID_SCREENSHOT,
1309 KEYMAP_ID_TOGGLE_HUD,
1310 KEYMAP_ID_TOGGLE_CHAT,
1311 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1312 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1313 KEYMAP_ID_TOGGLE_DEBUG,
1314 KEYMAP_ID_TOGGLE_PROFILER,
1315 KEYMAP_ID_CAMERA_MODE,
1316 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1317 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1318 KEYMAP_ID_RANGESELECT,
1320 KEYMAP_ID_QUICKTUNE_NEXT,
1321 KEYMAP_ID_QUICKTUNE_PREV,
1322 KEYMAP_ID_QUICKTUNE_INC,
1323 KEYMAP_ID_QUICKTUNE_DEC,
1325 KEYMAP_ID_DEBUG_STACKS,
1327 // Fake keycode for array size and internal checks
1328 KEYMAP_INTERNAL_ENUM_COUNT
1335 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1338 void KeyCache::populate()
1340 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1341 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1342 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1343 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1344 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1345 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1346 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1348 key[KEYMAP_ID_AUTORUN] = getKeySetting("keymap_autorun");
1350 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1351 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1352 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1353 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1354 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1355 key[KEYMAP_ID_MINIMAP] = getKeySetting("keymap_minimap");
1356 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1357 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1358 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1359 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1360 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1361 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1362 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1363 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1364 = getKeySetting("keymap_toggle_force_fog_off");
1365 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1366 = getKeySetting("keymap_toggle_update_camera");
1367 key[KEYMAP_ID_TOGGLE_DEBUG]
1368 = getKeySetting("keymap_toggle_debug");
1369 key[KEYMAP_ID_TOGGLE_PROFILER]
1370 = getKeySetting("keymap_toggle_profiler");
1371 key[KEYMAP_ID_CAMERA_MODE]
1372 = getKeySetting("keymap_camera_mode");
1373 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1374 = getKeySetting("keymap_increase_viewing_range_min");
1375 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1376 = getKeySetting("keymap_decrease_viewing_range_min");
1377 key[KEYMAP_ID_RANGESELECT]
1378 = getKeySetting("keymap_rangeselect");
1380 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1381 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1382 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1383 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1385 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1389 /****************************************************************************
1391 ****************************************************************************/
1393 const float object_hit_delay = 0.2;
1396 u32 last_time, busy_time, sleep_time;
1400 /* The reason the following structs are not anonymous structs within the
1401 * class is that they are not used by the majority of member functions and
1402 * many functions that do require objects of thse types do not modify them
1403 * (so they can be passed as a const qualified parameter)
1405 struct CameraOrientation {
1406 f32 camera_yaw; // "right/left"
1407 f32 camera_pitch; // "up/down"
1410 struct GameRunData {
1413 PointedThing pointed_old;
1417 bool update_wielded_item_trigger;
1418 bool reset_jump_timer;
1419 float nodig_delay_timer;
1421 float dig_time_complete;
1422 float repeat_rightclick_timer;
1423 float object_hit_delay_timer;
1424 float time_from_last_punch;
1425 ClientActiveObject *selected_object;
1429 float update_draw_list_timer;
1430 float statustext_time;
1434 v3f update_draw_list_last_cam_dir;
1436 u32 profiler_current_page;
1437 u32 profiler_max_page; // Number of pages
1440 float time_of_day_smooth;
1444 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1452 Jitter dtime_jitter, busy_time_jitter;
1455 /* Flags that can, or may, change during main game loop
1457 struct VolatileRunFlags {
1464 bool show_profiler_graph;
1465 bool disable_camera_update;
1466 bool first_loop_after_window_activation;
1467 bool camera_offset_changed;
1471 /****************************************************************************
1473 ****************************************************************************/
1475 /* This is not intended to be a public class. If a public class becomes
1476 * desirable then it may be better to create another 'wrapper' class that
1477 * hides most of the stuff in this class (nothing in this class is required
1478 * by any other file) but exposes the public methods/data only.
1485 bool startup(bool *kill,
1487 InputHandler *input,
1488 IrrlichtDevice *device,
1489 const std::string &map_dir,
1490 const std::string &playername,
1491 const std::string &password,
1492 // If address is "", local server is used and address is updated
1493 std::string *address,
1495 std::string &error_message,
1497 ChatBackend *chat_backend,
1498 const SubgameSpec &gamespec, // Used for local game
1499 bool simple_singleplayer_mode);
1506 void extendedResourceCleanup();
1508 // Basic initialisation
1509 bool init(const std::string &map_dir, std::string *address,
1511 const SubgameSpec &gamespec);
1513 bool createSingleplayerServer(const std::string map_dir,
1514 const SubgameSpec &gamespec, u16 port, std::string *address);
1517 bool createClient(const std::string &playername,
1518 const std::string &password, std::string *address, u16 port);
1521 // Client connection
1522 bool connectToServer(const std::string &playername,
1523 const std::string &password, std::string *address, u16 port,
1524 bool *connect_ok, bool *aborted);
1525 bool getServerContent(bool *aborted);
1529 void updateInteractTimers(GameRunData *runData, f32 dtime);
1530 bool checkConnection();
1531 bool handleCallbacks();
1532 void processQueues();
1533 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1534 const FpsControl &draw_times, f32 dtime);
1535 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1537 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1539 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1541 void processKeyboardInput(VolatileRunFlags *flags,
1542 float *statustext_time,
1544 bool *reset_jump_timer,
1545 u32 *profiler_current_page,
1546 u32 profiler_max_page);
1547 void processItemSelection(u16 *new_playeritem);
1549 void dropSelectedItem();
1550 void openInventory();
1552 void toggleFreeMove(float *statustext_time);
1553 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1554 void toggleFast(float *statustext_time);
1555 void toggleNoClip(float *statustext_time);
1556 void toggleCinematic(float *statustext_time);
1557 void toggleAutorun(float *statustext_time);
1559 void toggleChat(float *statustext_time, bool *flag);
1560 void toggleHud(float *statustext_time, bool *flag);
1561 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1562 bool shift_pressed);
1563 void toggleFog(float *statustext_time, bool *flag);
1564 void toggleDebug(float *statustext_time, bool *show_debug,
1565 bool *show_profiler_graph);
1566 void toggleUpdateCamera(float *statustext_time, bool *flag);
1567 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1568 u32 profiler_max_page);
1570 void increaseViewRange(float *statustext_time);
1571 void decreaseViewRange(float *statustext_time);
1572 void toggleFullViewRange(float *statustext_time);
1574 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1575 void updateCameraOrientation(CameraOrientation *cam,
1576 const VolatileRunFlags &flags);
1577 void updatePlayerControl(const CameraOrientation &cam);
1578 void step(f32 *dtime);
1579 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1580 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1581 float time_from_last_punch);
1582 void updateSound(f32 dtime);
1583 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1585 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1586 void handlePointingAtNode(GameRunData *runData,
1587 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1588 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1589 void handlePointingAtObject(GameRunData *runData,
1590 const PointedThing &pointed, const ItemStack &playeritem,
1591 const v3f &player_position, bool show_debug);
1592 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1593 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1595 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1596 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1597 void updateGui(float *statustext_time, const RunStats &stats,
1598 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1599 const CameraOrientation &cam);
1600 void updateProfilerGraphs(ProfilerGraph *graph);
1603 void limitFps(FpsControl *fps_timings, f32 *dtime);
1605 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1606 bool draw_clouds = true);
1608 static void settingChangedCallback(const std::string &setting_name, void *data);
1609 void readSettings();
1612 InputHandler *input;
1617 IWritableTextureSource *texture_src;
1618 IWritableShaderSource *shader_src;
1620 // When created, these will be filled with data received from the server
1621 IWritableItemDefManager *itemdef_manager;
1622 IWritableNodeDefManager *nodedef_manager;
1624 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1625 ISoundManager *sound;
1626 bool sound_is_dummy;
1627 SoundMaker *soundmaker;
1629 ChatBackend *chat_backend;
1631 GUIFormSpecMenu *current_formspec;
1633 EventManager *eventmgr;
1634 QuicktuneShortcutter *quicktune;
1636 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1637 MapDrawControl *draw_control;
1639 Clouds *clouds; // Free using ->Drop()
1640 Sky *sky; // Free using ->Drop()
1641 Inventory *local_inventory;
1646 This class does take ownership/responsibily for cleaning up etc of any of
1647 these items (e.g. device)
1649 IrrlichtDevice *device;
1650 video::IVideoDriver *driver;
1651 scene::ISceneManager *smgr;
1653 std::string *error_message;
1654 bool *reconnect_requested;
1655 IGameDef *gamedef; // Convenience (same as *client)
1656 scene::ISceneNode *skybox;
1659 bool simple_singleplayer_mode;
1662 /* Pre-calculated values
1664 int crack_animation_length;
1668 gui::IGUIStaticText *guitext; // First line of debug text
1669 gui::IGUIStaticText *guitext2; // Second line of debug text
1670 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1671 gui::IGUIStaticText *guitext_status;
1672 gui::IGUIStaticText *guitext_chat; // Chat text
1673 gui::IGUIStaticText *guitext_profiler; // Profiler text
1675 std::wstring infotext;
1676 std::wstring statustext;
1680 IntervalLimiter profiler_interval;
1683 * TODO: Local caching of settings is not optimal and should at some stage
1684 * be updated to use a global settings object for getting thse values
1685 * (as opposed to the this local caching). This can be addressed in
1688 bool m_cache_doubletap_jump;
1689 bool m_cache_enable_clouds;
1690 bool m_cache_enable_particles;
1691 bool m_cache_enable_fog;
1692 f32 m_cache_mouse_sensitivity;
1693 f32 m_repeat_right_click_time;
1696 bool m_cache_hold_aux1;
1706 itemdef_manager(NULL),
1707 nodedef_manager(NULL),
1709 sound_is_dummy(false),
1712 current_formspec(NULL),
1715 gui_chat_console(NULL),
1720 local_inventory(NULL),
1724 g_settings->registerChangedCallback("doubletap_jump",
1725 &settingChangedCallback, this);
1726 g_settings->registerChangedCallback("enable_clouds",
1727 &settingChangedCallback, this);
1728 g_settings->registerChangedCallback("enable_particles",
1729 &settingChangedCallback, this);
1730 g_settings->registerChangedCallback("enable_fog",
1731 &settingChangedCallback, this);
1732 g_settings->registerChangedCallback("mouse_sensitivity",
1733 &settingChangedCallback, this);
1734 g_settings->registerChangedCallback("repeat_rightclick_time",
1735 &settingChangedCallback, this);
1740 m_cache_hold_aux1 = false; // This is initialised properly later
1747 /****************************************************************************
1749 ****************************************************************************/
1755 if (!sound_is_dummy)
1758 delete server; // deleted first to stop all server threads
1761 delete local_inventory;
1767 delete nodedef_manager;
1768 delete itemdef_manager;
1769 delete draw_control;
1771 extendedResourceCleanup();
1773 g_settings->deregisterChangedCallback("doubletap_jump",
1774 &settingChangedCallback, this);
1775 g_settings->deregisterChangedCallback("enable_clouds",
1776 &settingChangedCallback, this);
1777 g_settings->deregisterChangedCallback("enable_particles",
1778 &settingChangedCallback, this);
1779 g_settings->deregisterChangedCallback("enable_fog",
1780 &settingChangedCallback, this);
1781 g_settings->deregisterChangedCallback("mouse_sensitivity",
1782 &settingChangedCallback, this);
1783 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1784 &settingChangedCallback, this);
1787 bool Game::startup(bool *kill,
1789 InputHandler *input,
1790 IrrlichtDevice *device,
1791 const std::string &map_dir,
1792 const std::string &playername,
1793 const std::string &password,
1794 std::string *address, // can change if simple_singleplayer_mode
1796 std::string &error_message,
1798 ChatBackend *chat_backend,
1799 const SubgameSpec &gamespec,
1800 bool simple_singleplayer_mode)
1803 this->device = device;
1805 this->error_message = &error_message;
1806 this->reconnect_requested = reconnect;
1807 this->random_input = random_input;
1808 this->input = input;
1809 this->chat_backend = chat_backend;
1810 this->simple_singleplayer_mode = simple_singleplayer_mode;
1812 driver = device->getVideoDriver();
1813 smgr = device->getSceneManager();
1815 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1817 if (!init(map_dir, address, port, gamespec))
1820 if (!createClient(playername, password, address, port))
1829 ProfilerGraph graph;
1830 RunStats stats = { 0 };
1831 CameraOrientation cam_view_target = { 0 };
1832 CameraOrientation cam_view = { 0 };
1833 GameRunData runData = { 0 };
1834 FpsControl draw_times = { 0 };
1835 VolatileRunFlags flags = { 0 };
1836 f32 dtime; // in seconds
1838 runData.time_from_last_punch = 10.0;
1839 runData.profiler_max_page = 3;
1840 runData.update_wielded_item_trigger = true;
1842 flags.show_chat = true;
1843 flags.show_hud = true;
1844 flags.show_minimap = g_settings->getBool("enable_minimap");
1845 flags.show_debug = g_settings->getBool("show_debug");
1846 flags.invert_mouse = g_settings->getBool("invert_mouse");
1847 flags.first_loop_after_window_activation = true;
1849 /* Clear the profiler */
1850 Profiler::GraphValues dummyvalues;
1851 g_profiler->graphGet(dummyvalues);
1853 draw_times.last_time = device->getTimer()->getTime();
1855 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1857 &flags.force_fog_off,
1861 set_light_table(g_settings->getFloat("display_gamma"));
1864 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1865 && client->checkPrivilege("fast");
1868 while (device->run()
1869 && !(*kill || g_gamecallback->shutdown_requested
1870 || (server && server->getShutdownRequested()))) {
1872 /* Must be called immediately after a device->run() call because it
1873 * uses device->getTimer()->getTime()
1875 limitFps(&draw_times, &dtime);
1877 updateStats(&stats, draw_times, dtime);
1878 updateInteractTimers(&runData, dtime);
1880 if (!checkConnection())
1882 if (!handleCallbacks())
1888 hud->resizeHotbar();
1890 updateProfilers(runData, stats, draw_times, dtime);
1891 processUserInput(&flags, &runData, dtime);
1892 // Update camera before player movement to avoid camera lag of one frame
1893 updateCameraDirection(&cam_view_target, &flags);
1894 float cam_smoothing = 0;
1895 if (g_settings->getBool("cinematic"))
1896 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1898 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1899 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1900 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1901 cam_view.camera_yaw) * cam_smoothing;
1902 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1903 cam_view.camera_pitch) * cam_smoothing;
1904 updatePlayerControl(cam_view);
1906 processClientEvents(&cam_view_target, &runData.damage_flash);
1907 updateCamera(&flags, draw_times.busy_time, dtime,
1908 runData.time_from_last_punch);
1910 processPlayerInteraction(&runData, dtime, flags.show_hud,
1912 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1913 updateProfilerGraphs(&graph);
1915 // Update if minimap has been disabled by the server
1916 flags.show_minimap &= !client->isMinimapDisabledByServer();
1921 void Game::shutdown()
1923 if (g_settings->get("3d_mode") == "pageflip") {
1924 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1927 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1932 if (gui_chat_console)
1933 gui_chat_console->drop();
1939 while (g_menumgr.menuCount() > 0) {
1940 g_menumgr.m_stack.front()->setVisible(false);
1941 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1944 if (current_formspec) {
1945 current_formspec->drop();
1946 current_formspec = NULL;
1949 chat_backend->addMessage(L"", L"# Disconnected.");
1950 chat_backend->addMessage(L"", L"");
1954 while (!client->isShutdown()) {
1955 assert(texture_src != NULL);
1956 assert(shader_src != NULL);
1957 texture_src->processQueue();
1958 shader_src->processQueue();
1965 /****************************************************************************/
1966 /****************************************************************************
1968 ****************************************************************************/
1969 /****************************************************************************/
1972 const std::string &map_dir,
1973 std::string *address,
1975 const SubgameSpec &gamespec)
1977 showOverlayMessage(wgettext("Loading..."), 0, 0);
1979 texture_src = createTextureSource(device);
1980 shader_src = createShaderSource(device);
1982 itemdef_manager = createItemDefManager();
1983 nodedef_manager = createNodeDefManager();
1985 eventmgr = new EventManager();
1986 quicktune = new QuicktuneShortcutter();
1988 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1989 && eventmgr && quicktune))
1995 // Create a server if not connecting to an existing one
1996 if (*address == "") {
1997 if (!createSingleplayerServer(map_dir, gamespec, port, address))
2004 bool Game::initSound()
2007 if (g_settings->getBool("enable_sound")) {
2008 infostream << "Attempting to use OpenAL audio" << std::endl;
2009 sound = createOpenALSoundManager(&soundfetcher);
2011 infostream << "Failed to initialize OpenAL audio" << std::endl;
2013 infostream << "Sound disabled." << std::endl;
2017 infostream << "Using dummy audio." << std::endl;
2018 sound = &dummySoundManager;
2019 sound_is_dummy = true;
2022 soundmaker = new SoundMaker(sound, nodedef_manager);
2026 soundmaker->registerReceiver(eventmgr);
2031 bool Game::createSingleplayerServer(const std::string map_dir,
2032 const SubgameSpec &gamespec, u16 port, std::string *address)
2034 showOverlayMessage(wgettext("Creating server..."), 0, 5);
2036 std::string bind_str = g_settings->get("bind_address");
2037 Address bind_addr(0, 0, 0, 0, port);
2039 if (g_settings->getBool("ipv6_server")) {
2040 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2044 bind_addr.Resolve(bind_str.c_str());
2045 } catch (ResolveError &e) {
2046 infostream << "Resolving bind address \"" << bind_str
2047 << "\" failed: " << e.what()
2048 << " -- Listening on all addresses." << std::endl;
2051 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2052 *error_message = "Unable to listen on " +
2053 bind_addr.serializeString() +
2054 " because IPv6 is disabled";
2055 errorstream << *error_message << std::endl;
2059 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2060 bind_addr.isIPv6());
2062 server->start(bind_addr);
2067 bool Game::createClient(const std::string &playername,
2068 const std::string &password, std::string *address, u16 port)
2070 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2072 draw_control = new MapDrawControl;
2076 bool could_connect, connect_aborted;
2078 if (!connectToServer(playername, password, address, port,
2079 &could_connect, &connect_aborted))
2082 if (!could_connect) {
2083 if (error_message->empty() && !connect_aborted) {
2084 // Should not happen if error messages are set properly
2085 *error_message = "Connection failed for unknown reason";
2086 errorstream << *error_message << std::endl;
2091 if (!getServerContent(&connect_aborted)) {
2092 if (error_message->empty() && !connect_aborted) {
2093 // Should not happen if error messages are set properly
2094 *error_message = "Connection failed for unknown reason";
2095 errorstream << *error_message << std::endl;
2100 // Update cached textures, meshes and materials
2101 client->afterContentReceived(device);
2105 camera = new Camera(smgr, *draw_control, gamedef);
2106 if (!camera || !camera->successfullyCreated(*error_message))
2108 client->setCamera(camera);
2112 if (m_cache_enable_clouds) {
2113 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2115 *error_message = "Memory allocation error (clouds)";
2116 errorstream << *error_message << std::endl;
2123 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2124 skybox = NULL; // This is used/set later on in the main run loop
2126 local_inventory = new Inventory(itemdef_manager);
2128 if (!(sky && local_inventory)) {
2129 *error_message = "Memory allocation error (sky or local inventory)";
2130 errorstream << *error_message << std::endl;
2134 /* Pre-calculated values
2136 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2138 v2u32 size = t->getOriginalSize();
2139 crack_animation_length = size.Y / size.X;
2141 crack_animation_length = 5;
2147 /* Set window caption
2149 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2151 str += driver->getName();
2153 device->setWindowCaption(str.c_str());
2155 LocalPlayer *player = client->getEnv().getLocalPlayer();
2156 player->hurt_tilt_timer = 0;
2157 player->hurt_tilt_strength = 0;
2159 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2162 *error_message = "Memory error: could not create HUD";
2163 errorstream << *error_message << std::endl;
2167 mapper = client->getMapper();
2168 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2173 bool Game::initGui()
2175 // First line of debug text
2176 guitext = guienv->addStaticText(
2177 utf8_to_wide(PROJECT_NAME_C).c_str(),
2178 core::rect<s32>(0, 0, 0, 0),
2179 false, false, guiroot);
2181 // Second line of debug text
2182 guitext2 = guienv->addStaticText(
2184 core::rect<s32>(0, 0, 0, 0),
2185 false, false, guiroot);
2187 // At the middle of the screen
2188 // Object infos are shown in this
2189 guitext_info = guienv->addStaticText(
2191 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2192 false, true, guiroot);
2194 // Status text (displays info when showing and hiding GUI stuff, etc.)
2195 guitext_status = guienv->addStaticText(
2197 core::rect<s32>(0, 0, 0, 0),
2198 false, false, guiroot);
2199 guitext_status->setVisible(false);
2202 guitext_chat = guienv->addStaticText(
2204 core::rect<s32>(0, 0, 0, 0),
2205 //false, false); // Disable word wrap as of now
2206 false, true, guiroot);
2207 // Remove stale "recent" chat messages from previous connections
2208 chat_backend->clearRecentChat();
2210 // Chat backend and console
2211 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2212 -1, chat_backend, client);
2213 if (!gui_chat_console) {
2214 *error_message = "Could not allocate memory for chat console";
2215 errorstream << *error_message << std::endl;
2219 // Profiler text (size is updated when text is updated)
2220 guitext_profiler = guienv->addStaticText(
2222 core::rect<s32>(0, 0, 0, 0),
2223 false, false, guiroot);
2224 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2225 guitext_profiler->setVisible(false);
2226 guitext_profiler->setWordWrap(true);
2228 #ifdef HAVE_TOUCHSCREENGUI
2230 if (g_touchscreengui)
2231 g_touchscreengui->init(texture_src);
2238 bool Game::connectToServer(const std::string &playername,
2239 const std::string &password, std::string *address, u16 port,
2240 bool *connect_ok, bool *aborted)
2242 *connect_ok = false; // Let's not be overly optimistic
2244 bool local_server_mode = false;
2246 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2248 Address connect_address(0, 0, 0, 0, port);
2251 connect_address.Resolve(address->c_str());
2253 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2254 //connect_address.Resolve("localhost");
2255 if (connect_address.isIPv6()) {
2256 IPv6AddressBytes addr_bytes;
2257 addr_bytes.bytes[15] = 1;
2258 connect_address.setAddress(&addr_bytes);
2260 connect_address.setAddress(127, 0, 0, 1);
2262 local_server_mode = true;
2264 } catch (ResolveError &e) {
2265 *error_message = std::string("Couldn't resolve address: ") + e.what();
2266 errorstream << *error_message << std::endl;
2270 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2271 *error_message = "Unable to connect to " +
2272 connect_address.serializeString() +
2273 " because IPv6 is disabled";
2274 errorstream << *error_message << std::endl;
2278 client = new Client(device,
2279 playername.c_str(), password,
2280 *draw_control, texture_src, shader_src,
2281 itemdef_manager, nodedef_manager, sound, eventmgr,
2282 connect_address.isIPv6());
2287 gamedef = client; // Client acts as our GameDef
2289 infostream << "Connecting to server at ";
2290 connect_address.print(&infostream);
2291 infostream << std::endl;
2293 client->connect(connect_address, *address,
2294 simple_singleplayer_mode || local_server_mode);
2297 Wait for server to accept connection
2303 FpsControl fps_control = { 0 };
2305 f32 wait_time = 0; // in seconds
2307 fps_control.last_time = device->getTimer()->getTime();
2309 while (device->run()) {
2311 limitFps(&fps_control, &dtime);
2313 // Update client and server
2314 client->step(dtime);
2317 server->step(dtime);
2320 if (client->getState() == LC_Init) {
2326 if (client->accessDenied()) {
2327 *error_message = "Access denied. Reason: "
2328 + client->accessDeniedReason();
2329 *reconnect_requested = client->reconnectRequested();
2330 errorstream << *error_message << std::endl;
2334 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2336 infostream << "Connect aborted [Escape]" << std::endl;
2341 // Only time out if we aren't waiting for the server we started
2342 if ((*address != "") && (wait_time > 10)) {
2343 *error_message = "Connection timed out.";
2344 errorstream << *error_message << std::endl;
2349 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2351 } catch (con::PeerNotFoundException &e) {
2352 // TODO: Should something be done here? At least an info/error
2360 bool Game::getServerContent(bool *aborted)
2364 FpsControl fps_control = { 0 };
2365 f32 dtime; // in seconds
2367 fps_control.last_time = device->getTimer()->getTime();
2369 while (device->run()) {
2371 limitFps(&fps_control, &dtime);
2373 // Update client and server
2374 client->step(dtime);
2377 server->step(dtime);
2380 if (client->mediaReceived() && client->itemdefReceived() &&
2381 client->nodedefReceived()) {
2386 if (!checkConnection())
2389 if (client->getState() < LC_Init) {
2390 *error_message = "Client disconnected";
2391 errorstream << *error_message << std::endl;
2395 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2397 infostream << "Connect aborted [Escape]" << std::endl;
2404 if (!client->itemdefReceived()) {
2405 const wchar_t *text = wgettext("Item definitions...");
2407 draw_load_screen(text, device, guienv, dtime, progress);
2409 } else if (!client->nodedefReceived()) {
2410 const wchar_t *text = wgettext("Node definitions...");
2412 draw_load_screen(text, device, guienv, dtime, progress);
2415 std::stringstream message;
2416 message.precision(3);
2417 message << gettext("Media...");
2419 if ((USE_CURL == 0) ||
2420 (!g_settings->getBool("enable_remote_media_server"))) {
2421 float cur = client->getCurRate();
2422 std::string cur_unit = gettext("KiB/s");
2426 cur_unit = gettext("MiB/s");
2429 message << " (" << cur << ' ' << cur_unit << ")";
2432 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2433 draw_load_screen(utf8_to_wide(message.str()), device,
2434 guienv, dtime, progress);
2442 /****************************************************************************/
2443 /****************************************************************************
2445 ****************************************************************************/
2446 /****************************************************************************/
2448 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2450 if (runData->nodig_delay_timer >= 0)
2451 runData->nodig_delay_timer -= dtime;
2453 if (runData->object_hit_delay_timer >= 0)
2454 runData->object_hit_delay_timer -= dtime;
2456 runData->time_from_last_punch += dtime;
2460 /* returns false if game should exit, otherwise true
2462 inline bool Game::checkConnection()
2464 if (client->accessDenied()) {
2465 *error_message = "Access denied. Reason: "
2466 + client->accessDeniedReason();
2467 *reconnect_requested = client->reconnectRequested();
2468 errorstream << *error_message << std::endl;
2476 /* returns false if game should exit, otherwise true
2478 inline bool Game::handleCallbacks()
2480 if (g_gamecallback->disconnect_requested) {
2481 g_gamecallback->disconnect_requested = false;
2485 if (g_gamecallback->changepassword_requested) {
2486 (new GUIPasswordChange(guienv, guiroot, -1,
2487 &g_menumgr, client))->drop();
2488 g_gamecallback->changepassword_requested = false;
2491 if (g_gamecallback->changevolume_requested) {
2492 (new GUIVolumeChange(guienv, guiroot, -1,
2493 &g_menumgr, client))->drop();
2494 g_gamecallback->changevolume_requested = false;
2497 if (g_gamecallback->keyconfig_requested) {
2498 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2499 &g_menumgr))->drop();
2500 g_gamecallback->keyconfig_requested = false;
2503 if (g_gamecallback->keyconfig_changed) {
2504 keycache.populate(); // update the cache with new settings
2505 g_gamecallback->keyconfig_changed = false;
2512 void Game::processQueues()
2514 texture_src->processQueue();
2515 itemdef_manager->processQueue(gamedef);
2516 shader_src->processQueue();
2520 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2521 const FpsControl &draw_times, f32 dtime)
2523 float profiler_print_interval =
2524 g_settings->getFloat("profiler_print_interval");
2525 bool print_to_log = true;
2527 if (profiler_print_interval == 0) {
2528 print_to_log = false;
2529 profiler_print_interval = 5;
2532 if (profiler_interval.step(dtime, profiler_print_interval)) {
2534 infostream << "Profiler:" << std::endl;
2535 g_profiler->print(infostream);
2538 update_profiler_gui(guitext_profiler, g_fontengine,
2539 runData.profiler_current_page, runData.profiler_max_page,
2540 driver->getScreenSize().Height);
2542 g_profiler->clear();
2545 addProfilerGraphs(stats, draw_times, dtime);
2549 void Game::addProfilerGraphs(const RunStats &stats,
2550 const FpsControl &draw_times, f32 dtime)
2552 g_profiler->graphAdd("mainloop_other",
2553 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2555 if (draw_times.sleep_time != 0)
2556 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2557 g_profiler->graphAdd("mainloop_dtime", dtime);
2559 g_profiler->add("Elapsed time", dtime);
2560 g_profiler->avg("FPS", 1. / dtime);
2564 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2571 /* Time average and jitter calculation
2573 jp = &stats->dtime_jitter;
2574 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2576 jitter = dtime - jp->avg;
2578 if (jitter > jp->max)
2581 jp->counter += dtime;
2583 if (jp->counter > 0.0) {
2585 jp->max_sample = jp->max;
2586 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2590 /* Busytime average and jitter calculation
2592 jp = &stats->busy_time_jitter;
2593 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2595 jitter = draw_times.busy_time - jp->avg;
2597 if (jitter > jp->max)
2599 if (jitter < jp->min)
2602 jp->counter += dtime;
2604 if (jp->counter > 0.0) {
2606 jp->max_sample = jp->max;
2607 jp->min_sample = jp->min;
2615 /****************************************************************************
2617 ****************************************************************************/
2619 void Game::processUserInput(VolatileRunFlags *flags,
2620 GameRunData *runData, f32 dtime)
2622 // Reset input if window not active or some menu is active
2623 if (device->isWindowActive() == false
2624 || noMenuActive() == false
2625 || guienv->hasFocus(gui_chat_console)) {
2627 #ifdef HAVE_TOUCHSCREENGUI
2628 g_touchscreengui->hide();
2631 #ifdef HAVE_TOUCHSCREENGUI
2632 else if (g_touchscreengui) {
2633 /* on touchscreengui step may generate own input events which ain't
2634 * what we want in case we just did clear them */
2635 g_touchscreengui->step(dtime);
2639 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2640 gui_chat_console->closeConsoleAtOnce();
2643 // Input handler step() (used by the random input generator)
2648 if (current_formspec != 0)
2649 current_formspec->getAndroidUIInput();
2653 // Increase timer for double tap of "keymap_jump"
2654 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2655 runData->jump_timer += dtime;
2657 processKeyboardInput(
2659 &runData->statustext_time,
2660 &runData->jump_timer,
2661 &runData->reset_jump_timer,
2662 &runData->profiler_current_page,
2663 runData->profiler_max_page);
2665 processItemSelection(&runData->new_playeritem);
2669 void Game::processKeyboardInput(VolatileRunFlags *flags,
2670 float *statustext_time,
2672 bool *reset_jump_timer,
2673 u32 *profiler_current_page,
2674 u32 profiler_max_page)
2677 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2679 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2681 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_AUTORUN])) {
2682 toggleAutorun(statustext_time);
2683 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2685 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2686 show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
2687 simple_singleplayer_mode);
2688 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2689 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2691 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2692 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2694 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2696 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2697 toggleFreeMove(statustext_time);
2698 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2699 toggleFreeMoveAlt(statustext_time, jump_timer);
2700 *reset_jump_timer = true;
2701 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2702 toggleFast(statustext_time);
2703 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2704 toggleNoClip(statustext_time);
2705 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2706 toggleCinematic(statustext_time);
2707 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2708 client->makeScreenshot(device);
2709 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2710 toggleHud(statustext_time, &flags->show_hud);
2711 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_MINIMAP])) {
2712 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2713 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]));
2714 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2715 toggleChat(statustext_time, &flags->show_chat);
2716 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2717 toggleFog(statustext_time, &flags->force_fog_off);
2718 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2719 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2720 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2721 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2722 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2723 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2724 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2725 increaseViewRange(statustext_time);
2726 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2727 decreaseViewRange(statustext_time);
2728 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2729 toggleFullViewRange(statustext_time);
2730 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2732 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2734 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2736 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2738 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2739 // Print debug stacks
2740 dstream << "-----------------------------------------"
2742 dstream << "Printing debug stacks:" << std::endl;
2743 dstream << "-----------------------------------------"
2745 debug_stacks_print();
2748 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2749 *reset_jump_timer = false;
2755 if (quicktune->hasMessage()) {
2756 std::string msg = quicktune->getMessage();
2757 statustext = utf8_to_wide(msg);
2758 *statustext_time = 0;
2763 void Game::processItemSelection(u16 *new_playeritem)
2765 LocalPlayer *player = client->getEnv().getLocalPlayer();
2767 /* Item selection using mouse wheel
2769 *new_playeritem = client->getPlayerItem();
2771 s32 wheel = input->getMouseWheel();
2772 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2773 player->hud_hotbar_itemcount - 1);
2776 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2778 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2782 /* Item selection using keyboard
2784 for (u16 i = 0; i < 10; i++) {
2785 static const KeyPress *item_keys[10] = {
2786 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2787 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2788 NumberKey + 9, NumberKey + 0,
2791 if (input->wasKeyDown(*item_keys[i])) {
2792 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2793 *new_playeritem = i;
2794 infostream << "Selected item: " << new_playeritem << std::endl;
2802 void Game::dropSelectedItem()
2804 IDropAction *a = new IDropAction();
2806 a->from_inv.setCurrentPlayer();
2807 a->from_list = "main";
2808 a->from_i = client->getPlayerItem();
2809 client->inventoryAction(a);
2813 void Game::openInventory()
2816 * Don't permit to open inventory is CAO or player doesn't exists.
2817 * This prevent showing an empty inventory at player load
2820 LocalPlayer *player = client->getEnv().getLocalPlayer();
2821 if (player == NULL || player->getCAO() == NULL)
2824 infostream << "the_game: " << "Launching inventory" << std::endl;
2826 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2827 TextDest *txt_dst = new TextDestPlayerInventory(client);
2829 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2830 device, fs_src, txt_dst, client);
2832 InventoryLocation inventoryloc;
2833 inventoryloc.setCurrentPlayer();
2834 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2838 void Game::openConsole()
2840 if (!gui_chat_console->isOpenInhibited()) {
2841 // Open up to over half of the screen
2842 gui_chat_console->openConsole(0.6);
2843 guienv->setFocus(gui_chat_console);
2848 void Game::toggleFreeMove(float *statustext_time)
2850 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2852 bool free_move = !g_settings->getBool("free_move");
2853 g_settings->set("free_move", bool_to_cstr(free_move));
2855 *statustext_time = 0;
2856 statustext = msg[free_move];
2857 if (free_move && !client->checkPrivilege("fly"))
2858 statustext += L" (note: no 'fly' privilege)";
2862 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2864 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2865 toggleFreeMove(statustext_time);
2869 void Game::toggleFast(float *statustext_time)
2871 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2872 bool fast_move = !g_settings->getBool("fast_move");
2873 g_settings->set("fast_move", bool_to_cstr(fast_move));
2875 *statustext_time = 0;
2876 statustext = msg[fast_move];
2878 bool has_fast_privs = client->checkPrivilege("fast");
2880 if (fast_move && !has_fast_privs)
2881 statustext += L" (note: no 'fast' privilege)";
2884 m_cache_hold_aux1 = fast_move && has_fast_privs;
2889 void Game::toggleNoClip(float *statustext_time)
2891 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2892 bool noclip = !g_settings->getBool("noclip");
2893 g_settings->set("noclip", bool_to_cstr(noclip));
2895 *statustext_time = 0;
2896 statustext = msg[noclip];
2898 if (noclip && !client->checkPrivilege("noclip"))
2899 statustext += L" (note: no 'noclip' privilege)";
2902 void Game::toggleCinematic(float *statustext_time)
2904 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2905 bool cinematic = !g_settings->getBool("cinematic");
2906 g_settings->set("cinematic", bool_to_cstr(cinematic));
2908 *statustext_time = 0;
2909 statustext = msg[cinematic];
2912 // Add WoW-style autorun by toggling continuous forward.
2913 void Game::toggleAutorun(float *statustext_time)
2915 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2916 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2917 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2919 *statustext_time = 0;
2920 statustext = msg[autorun_enabled ? 1 : 0];
2923 void Game::toggleChat(float *statustext_time, bool *flag)
2925 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2928 *statustext_time = 0;
2929 statustext = msg[*flag];
2933 void Game::toggleHud(float *statustext_time, bool *flag)
2935 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2938 *statustext_time = 0;
2939 statustext = msg[*flag];
2942 void Game::toggleMinimap(float *statustext_time, bool *flag,
2943 bool show_hud, bool shift_pressed)
2945 if (!show_hud || !g_settings->getBool("enable_minimap"))
2948 if (shift_pressed) {
2949 mapper->toggleMinimapShape();
2953 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2955 MinimapMode mode = MINIMAP_MODE_OFF;
2956 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2957 mode = mapper->getMinimapMode();
2958 mode = (MinimapMode)((int)mode + 1);
2963 case MINIMAP_MODE_SURFACEx1:
2964 statustext = L"Minimap in surface mode, Zoom x1";
2966 case MINIMAP_MODE_SURFACEx2:
2967 statustext = L"Minimap in surface mode, Zoom x2";
2969 case MINIMAP_MODE_SURFACEx4:
2970 statustext = L"Minimap in surface mode, Zoom x4";
2972 case MINIMAP_MODE_RADARx1:
2973 statustext = L"Minimap in radar mode, Zoom x1";
2975 case MINIMAP_MODE_RADARx2:
2976 statustext = L"Minimap in radar mode, Zoom x2";
2978 case MINIMAP_MODE_RADARx4:
2979 statustext = L"Minimap in radar mode, Zoom x4";
2982 mode = MINIMAP_MODE_OFF;
2984 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2985 L"Minimap hidden" : L"Minimap disabled by server";
2988 *statustext_time = 0;
2989 mapper->setMinimapMode(mode);
2992 void Game::toggleFog(float *statustext_time, bool *flag)
2994 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2997 *statustext_time = 0;
2998 statustext = msg[*flag];
3002 void Game::toggleDebug(float *statustext_time, bool *show_debug,
3003 bool *show_profiler_graph)
3005 // Initial / 3x toggle: Chat only
3006 // 1x toggle: Debug text with chat
3007 // 2x toggle: Debug text with profiler graph
3010 *show_profiler_graph = false;
3011 statustext = L"Debug info shown";
3012 } else if (*show_profiler_graph) {
3013 *show_debug = false;
3014 *show_profiler_graph = false;
3015 statustext = L"Debug info and profiler graph hidden";
3017 *show_profiler_graph = true;
3018 statustext = L"Profiler graph shown";
3020 *statustext_time = 0;
3024 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3026 static const wchar_t *msg[] = {
3027 L"Camera update enabled",
3028 L"Camera update disabled"
3032 *statustext_time = 0;
3033 statustext = msg[*flag];
3037 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3038 u32 profiler_max_page)
3040 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3042 // FIXME: This updates the profiler with incomplete values
3043 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3044 profiler_max_page, driver->getScreenSize().Height);
3046 if (*profiler_current_page != 0) {
3047 std::wstringstream sstr;
3048 sstr << "Profiler shown (page " << *profiler_current_page
3049 << " of " << profiler_max_page << ")";
3050 statustext = sstr.str();
3052 statustext = L"Profiler hidden";
3054 *statustext_time = 0;
3058 void Game::increaseViewRange(float *statustext_time)
3060 s16 range = g_settings->getS16("viewing_range");
3061 s16 range_new = range + 10;
3062 g_settings->set("viewing_range", itos(range_new));
3063 statustext = utf8_to_wide("Viewing range changed to "
3065 *statustext_time = 0;
3069 void Game::decreaseViewRange(float *statustext_time)
3071 s16 range = g_settings->getS16("viewing_range");
3072 s16 range_new = range - 10;
3077 g_settings->set("viewing_range", itos(range_new));
3078 statustext = utf8_to_wide("Viewing range changed to "
3080 *statustext_time = 0;
3084 void Game::toggleFullViewRange(float *statustext_time)
3086 static const wchar_t *msg[] = {
3087 L"Disabled full viewing range",
3088 L"Enabled full viewing range"
3091 draw_control->range_all = !draw_control->range_all;
3092 infostream << msg[draw_control->range_all] << std::endl;
3093 statustext = msg[draw_control->range_all];
3094 *statustext_time = 0;
3098 void Game::updateCameraDirection(CameraOrientation *cam,
3099 VolatileRunFlags *flags)
3101 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3104 if (!random_input) {
3105 // Mac OSX gets upset if this is set every frame
3106 if (device->getCursorControl()->isVisible())
3107 device->getCursorControl()->setVisible(false);
3111 if (flags->first_loop_after_window_activation)
3112 flags->first_loop_after_window_activation = false;
3114 updateCameraOrientation(cam, *flags);
3116 input->setMousePos((driver->getScreenSize().Width / 2),
3117 (driver->getScreenSize().Height / 2));
3121 // Mac OSX gets upset if this is set every frame
3122 if (device->getCursorControl()->isVisible() == false)
3123 device->getCursorControl()->setVisible(true);
3126 if (!flags->first_loop_after_window_activation)
3127 flags->first_loop_after_window_activation = true;
3133 void Game::updateCameraOrientation(CameraOrientation *cam,
3134 const VolatileRunFlags &flags)
3136 #ifdef HAVE_TOUCHSCREENGUI
3137 if (g_touchscreengui) {
3138 cam->camera_yaw = g_touchscreengui->getYaw();
3139 cam->camera_pitch = g_touchscreengui->getPitch();
3142 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3143 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3145 if (flags.invert_mouse
3146 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3150 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3151 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3153 #ifdef HAVE_TOUCHSCREENGUI
3157 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3161 void Game::updatePlayerControl(const CameraOrientation &cam)
3163 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3165 PlayerControl control(
3166 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
3167 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
3168 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
3169 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
3170 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
3171 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
3172 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
3173 input->getLeftState(),
3174 input->getRightState(),
3180 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
3181 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
3182 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
3183 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
3184 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
3185 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
3186 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
3187 ( (u32)(input->getLeftState() & 0x1) << 7) |
3188 ( (u32)(input->getRightState() & 0x1) << 8
3192 /* For Android, simulate holding down AUX1 (fast move) if the user has
3193 * the fast_move setting toggled on. If there is an aux1 key defined for
3194 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3197 if (m_cache_hold_aux1) {
3198 control.aux1 = control.aux1 ^ true;
3199 keypress_bits ^= ((u32)(1U << 5));
3203 client->setPlayerControl(control);
3204 LocalPlayer *player = client->getEnv().getLocalPlayer();
3205 player->keyPressed = keypress_bits;
3211 inline void Game::step(f32 *dtime)
3213 bool can_be_and_is_paused =
3214 (simple_singleplayer_mode && g_menumgr.pausesGame());
3216 if (can_be_and_is_paused) { // This is for a singleplayer server
3217 *dtime = 0; // No time passes
3219 if (server != NULL) {
3220 //TimeTaker timer("server->step(dtime)");
3221 server->step(*dtime);
3224 //TimeTaker timer("client.step(dtime)");
3225 client->step(*dtime);
3230 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3232 ClientEvent event = client->getClientEvent();
3234 LocalPlayer *player = client->getEnv().getLocalPlayer();
3236 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3238 if (event.type == CE_PLAYER_DAMAGE &&
3239 client->getHP() != 0) {
3240 //u16 damage = event.player_damage.amount;
3241 //infostream<<"Player damage: "<<damage<<std::endl;
3243 *damage_flash += 100.0;
3244 *damage_flash += 8.0 * event.player_damage.amount;
3246 player->hurt_tilt_timer = 1.5;
3247 player->hurt_tilt_strength = event.player_damage.amount / 4;
3248 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3250 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3251 gamedef->event()->put(e);
3252 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3253 cam->camera_yaw = event.player_force_move.yaw;
3254 cam->camera_pitch = event.player_force_move.pitch;
3255 } else if (event.type == CE_DEATHSCREEN) {
3256 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3259 chat_backend->addMessage(L"", L"You died.");
3261 /* Handle visualization */
3263 player->hurt_tilt_timer = 0;
3264 player->hurt_tilt_strength = 0;
3266 } else if (event.type == CE_SHOW_FORMSPEC) {
3267 FormspecFormSource *fs_src =
3268 new FormspecFormSource(*(event.show_formspec.formspec));
3269 TextDestPlayerInventory *txt_dst =
3270 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3272 create_formspec_menu(¤t_formspec, client, gamedef,
3273 texture_src, device, fs_src, txt_dst, client);
3275 delete(event.show_formspec.formspec);
3276 delete(event.show_formspec.formname);
3277 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3278 (event.type == CE_ADD_PARTICLESPAWNER) ||
3279 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3280 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3282 } else if (event.type == CE_HUDADD) {
3283 u32 id = event.hudadd.id;
3285 LocalPlayer *player = client->getEnv().getLocalPlayer();
3286 HudElement *e = player->getHud(id);
3289 delete event.hudadd.pos;
3290 delete event.hudadd.name;
3291 delete event.hudadd.scale;
3292 delete event.hudadd.text;
3293 delete event.hudadd.align;
3294 delete event.hudadd.offset;
3295 delete event.hudadd.world_pos;
3296 delete event.hudadd.size;
3301 e->type = (HudElementType)event.hudadd.type;
3302 e->pos = *event.hudadd.pos;
3303 e->name = *event.hudadd.name;
3304 e->scale = *event.hudadd.scale;
3305 e->text = *event.hudadd.text;
3306 e->number = event.hudadd.number;
3307 e->item = event.hudadd.item;
3308 e->dir = event.hudadd.dir;
3309 e->align = *event.hudadd.align;
3310 e->offset = *event.hudadd.offset;
3311 e->world_pos = *event.hudadd.world_pos;
3312 e->size = *event.hudadd.size;
3314 u32 new_id = player->addHud(e);
3315 //if this isn't true our huds aren't consistent
3316 sanity_check(new_id == id);
3318 delete event.hudadd.pos;
3319 delete event.hudadd.name;
3320 delete event.hudadd.scale;
3321 delete event.hudadd.text;
3322 delete event.hudadd.align;
3323 delete event.hudadd.offset;
3324 delete event.hudadd.world_pos;
3325 delete event.hudadd.size;
3326 } else if (event.type == CE_HUDRM) {
3327 HudElement *e = player->removeHud(event.hudrm.id);
3331 } else if (event.type == CE_HUDCHANGE) {
3332 u32 id = event.hudchange.id;
3333 HudElement *e = player->getHud(id);
3336 delete event.hudchange.v3fdata;
3337 delete event.hudchange.v2fdata;
3338 delete event.hudchange.sdata;
3339 delete event.hudchange.v2s32data;
3343 switch (event.hudchange.stat) {
3345 e->pos = *event.hudchange.v2fdata;
3349 e->name = *event.hudchange.sdata;
3352 case HUD_STAT_SCALE:
3353 e->scale = *event.hudchange.v2fdata;
3357 e->text = *event.hudchange.sdata;
3360 case HUD_STAT_NUMBER:
3361 e->number = event.hudchange.data;
3365 e->item = event.hudchange.data;
3369 e->dir = event.hudchange.data;
3372 case HUD_STAT_ALIGN:
3373 e->align = *event.hudchange.v2fdata;
3376 case HUD_STAT_OFFSET:
3377 e->offset = *event.hudchange.v2fdata;
3380 case HUD_STAT_WORLD_POS:
3381 e->world_pos = *event.hudchange.v3fdata;
3385 e->size = *event.hudchange.v2s32data;
3389 delete event.hudchange.v3fdata;
3390 delete event.hudchange.v2fdata;
3391 delete event.hudchange.sdata;
3392 delete event.hudchange.v2s32data;
3393 } else if (event.type == CE_SET_SKY) {
3394 sky->setVisible(false);
3401 // Handle according to type
3402 if (*event.set_sky.type == "regular") {
3403 sky->setVisible(true);
3404 } else if (*event.set_sky.type == "skybox" &&
3405 event.set_sky.params->size() == 6) {
3406 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3407 skybox = smgr->addSkyBoxSceneNode(
3408 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3409 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3410 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3411 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3412 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3413 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3415 // Handle everything else as plain color
3417 if (*event.set_sky.type != "plain")
3418 infostream << "Unknown sky type: "
3419 << (*event.set_sky.type) << std::endl;
3421 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3424 delete event.set_sky.bgcolor;
3425 delete event.set_sky.type;
3426 delete event.set_sky.params;
3427 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3428 bool enable = event.override_day_night_ratio.do_override;
3429 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3430 client->getEnv().setDayNightRatioOverride(enable, value);
3436 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3437 f32 dtime, float time_from_last_punch)
3439 LocalPlayer *player = client->getEnv().getLocalPlayer();
3442 For interaction purposes, get info about the held item
3444 - Is it a usable item?
3445 - Can it point to liquids?
3447 ItemStack playeritem;
3449 InventoryList *mlist = local_inventory->getList("main");
3451 if (mlist && client->getPlayerItem() < mlist->getSize())
3452 playeritem = mlist->getItem(client->getPlayerItem());
3455 ToolCapabilities playeritem_toolcap =
3456 playeritem.getToolCapabilities(itemdef_manager);
3458 v3s16 old_camera_offset = camera->getOffset();
3460 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3461 GenericCAO *playercao = player->getCAO();
3463 // If playercao not loaded, don't change camera
3464 if (playercao == NULL)
3467 camera->toggleCameraMode();
3469 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3470 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3473 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3474 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3476 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3477 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3479 camera->step(dtime);
3481 v3f camera_position = camera->getPosition();
3482 v3f camera_direction = camera->getDirection();
3483 f32 camera_fov = camera->getFovMax();
3484 v3s16 camera_offset = camera->getOffset();
3486 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3488 if (!flags->disable_camera_update) {
3489 client->getEnv().getClientMap().updateCamera(camera_position,
3490 camera_direction, camera_fov, camera_offset);
3492 if (flags->camera_offset_changed) {
3493 client->updateCameraOffset(camera_offset);
3494 client->getEnv().updateCameraOffset(camera_offset);
3497 clouds->updateCameraOffset(camera_offset);
3503 void Game::updateSound(f32 dtime)
3505 // Update sound listener
3506 v3s16 camera_offset = camera->getOffset();
3507 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3508 v3f(0, 0, 0), // velocity
3509 camera->getDirection(),
3510 camera->getCameraNode()->getUpVector());
3511 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3514 // Update sound maker
3515 soundmaker->step(dtime);
3517 LocalPlayer *player = client->getEnv().getLocalPlayer();
3519 ClientMap &map = client->getEnv().getClientMap();
3520 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3521 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3525 void Game::processPlayerInteraction(GameRunData *runData,
3526 f32 dtime, bool show_hud, bool show_debug)
3528 LocalPlayer *player = client->getEnv().getLocalPlayer();
3530 ItemStack playeritem;
3532 InventoryList *mlist = local_inventory->getList("main");
3534 if (mlist && client->getPlayerItem() < mlist->getSize())
3535 playeritem = mlist->getItem(client->getPlayerItem());
3538 const ItemDefinition &playeritem_def =
3539 playeritem.getDefinition(itemdef_manager);
3541 v3f player_position = player->getPosition();
3542 v3f camera_position = camera->getPosition();
3543 v3f camera_direction = camera->getDirection();
3544 v3s16 camera_offset = camera->getOffset();
3548 Calculate what block is the crosshair pointing to
3551 f32 d = playeritem_def.range; // max. distance
3552 f32 d_hand = itemdef_manager->get("").range;
3554 if (d < 0 && d_hand >= 0)
3559 core::line3d<f32> shootline;
3561 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3563 shootline = core::line3d<f32>(camera_position,
3564 camera_position + camera_direction * BS * (d + 1));
3567 // prevent player pointing anything in front-view
3568 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3569 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3572 #ifdef HAVE_TOUCHSCREENGUI
3574 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3575 shootline = g_touchscreengui->getShootline();
3576 shootline.start += intToFloat(camera_offset, BS);
3577 shootline.end += intToFloat(camera_offset, BS);
3582 PointedThing pointed = getPointedThing(
3584 client, hud, player_position, camera_direction,
3585 camera_position, shootline, d,
3586 playeritem_def.liquids_pointable,
3587 !runData->ldown_for_dig,
3590 runData->selected_object);
3592 if (pointed != runData->pointed_old) {
3593 infostream << "Pointing at " << pointed.dump() << std::endl;
3594 hud->updateSelectionMesh(camera_offset);
3599 - releasing left mouse button
3600 - pointing away from node
3602 if (runData->digging) {
3603 if (input->getLeftReleased()) {
3604 infostream << "Left button released"
3605 << " (stopped digging)" << std::endl;
3606 runData->digging = false;
3607 } else if (pointed != runData->pointed_old) {
3608 if (pointed.type == POINTEDTHING_NODE
3609 && runData->pointed_old.type == POINTEDTHING_NODE
3610 && pointed.node_undersurface
3611 == runData->pointed_old.node_undersurface) {
3612 // Still pointing to the same node, but a different face.
3615 infostream << "Pointing away from node"
3616 << " (stopped digging)" << std::endl;
3617 runData->digging = false;
3618 hud->updateSelectionMesh(camera_offset);
3622 if (!runData->digging) {
3623 client->interact(1, runData->pointed_old);
3624 client->setCrack(-1, v3s16(0, 0, 0));
3625 runData->dig_time = 0.0;
3629 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3630 runData->ldown_for_dig = false;
3633 runData->left_punch = false;
3635 soundmaker->m_player_leftpunch_sound.name = "";
3637 if (input->getRightState())
3638 runData->repeat_rightclick_timer += dtime;
3640 runData->repeat_rightclick_timer = 0;
3642 if (playeritem_def.usable && input->getLeftState()) {
3643 if (input->getLeftClicked())
3644 client->interact(4, pointed);
3645 } else if (pointed.type == POINTEDTHING_NODE) {
3646 ToolCapabilities playeritem_toolcap =
3647 playeritem.getToolCapabilities(itemdef_manager);
3648 handlePointingAtNode(runData, pointed, playeritem_def,
3649 playeritem_toolcap, dtime);
3650 } else if (pointed.type == POINTEDTHING_OBJECT) {
3651 handlePointingAtObject(runData, pointed, playeritem,
3652 player_position, show_debug);
3653 } else if (input->getLeftState()) {
3654 // When button is held down in air, show continuous animation
3655 runData->left_punch = true;
3656 } else if (input->getRightClicked()) {
3657 handlePointingAtNothing(runData, playeritem);
3660 runData->pointed_old = pointed;
3662 if (runData->left_punch || input->getLeftClicked())
3663 camera->setDigging(0); // left click animation
3665 input->resetLeftClicked();
3666 input->resetRightClicked();
3668 input->resetLeftReleased();
3669 input->resetRightReleased();
3673 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3675 infostream << "Right Clicked in Air" << std::endl;
3676 PointedThing fauxPointed;
3677 fauxPointed.type = POINTEDTHING_NOTHING;
3678 client->interact(5, fauxPointed);
3682 void Game::handlePointingAtNode(GameRunData *runData,
3683 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3684 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3686 v3s16 nodepos = pointed.node_undersurface;
3687 v3s16 neighbourpos = pointed.node_abovesurface;
3690 Check information text of node
3693 ClientMap &map = client->getEnv().getClientMap();
3694 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3697 infotext = utf8_to_wide(meta->getString("infotext"));
3699 MapNode n = map.getNodeNoEx(nodepos);
3701 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3702 infotext = L"Unknown node: ";
3703 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3707 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3708 && client->checkPrivilege("interact")) {
3709 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3712 if ((input->getRightClicked() ||
3713 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3714 client->checkPrivilege("interact")) {
3715 runData->repeat_rightclick_timer = 0;
3716 infostream << "Ground right-clicked" << std::endl;
3718 if (meta && meta->getString("formspec") != "" && !random_input
3719 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3720 infostream << "Launching custom inventory view" << std::endl;
3722 InventoryLocation inventoryloc;
3723 inventoryloc.setNodeMeta(nodepos);
3725 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3726 &client->getEnv().getClientMap(), nodepos);
3727 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3729 create_formspec_menu(¤t_formspec, client, gamedef,
3730 texture_src, device, fs_src, txt_dst, client);
3732 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3734 // Report right click to server
3736 camera->setDigging(1); // right click animation (always shown for feedback)
3738 // If the wielded item has node placement prediction,
3740 bool placed = nodePlacementPrediction(*client,
3742 nodepos, neighbourpos);
3746 client->interact(3, pointed);
3748 soundmaker->m_player_rightpunch_sound =
3749 playeritem_def.sound_place;
3751 soundmaker->m_player_rightpunch_sound =
3754 if (playeritem_def.node_placement_prediction == "" ||
3755 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3756 client->interact(3, pointed); // Report to server
3758 soundmaker->m_player_rightpunch_sound =
3759 playeritem_def.sound_place_failed;
3767 void Game::handlePointingAtObject(GameRunData *runData,
3768 const PointedThing &pointed,
3769 const ItemStack &playeritem,
3770 const v3f &player_position,
3773 infotext = utf8_to_wide(runData->selected_object->infoText());
3776 if (infotext != L"") {
3779 infotext += utf8_to_wide(runData->selected_object->debugInfoText());
3782 if (input->getLeftState()) {
3783 bool do_punch = false;
3784 bool do_punch_damage = false;
3786 if (runData->object_hit_delay_timer <= 0.0) {
3788 do_punch_damage = true;
3789 runData->object_hit_delay_timer = object_hit_delay;
3792 if (input->getLeftClicked())
3796 infostream << "Left-clicked object" << std::endl;
3797 runData->left_punch = true;
3800 if (do_punch_damage) {
3801 // Report direct punch
3802 v3f objpos = runData->selected_object->getPosition();
3803 v3f dir = (objpos - player_position).normalize();
3805 bool disable_send = runData->selected_object->directReportPunch(
3806 dir, &playeritem, runData->time_from_last_punch);
3807 runData->time_from_last_punch = 0;
3810 client->interact(0, pointed);
3812 } else if (input->getRightClicked()) {
3813 infostream << "Right-clicked object" << std::endl;
3814 client->interact(3, pointed); // place
3819 void Game::handleDigging(GameRunData *runData,
3820 const PointedThing &pointed, const v3s16 &nodepos,
3821 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3823 if (!runData->digging) {
3824 infostream << "Started digging" << std::endl;
3825 client->interact(0, pointed);
3826 runData->digging = true;
3827 runData->ldown_for_dig = true;
3830 LocalPlayer *player = client->getEnv().getLocalPlayer();
3831 ClientMap &map = client->getEnv().getClientMap();
3832 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3834 // NOTE: Similar piece of code exists on the server side for
3836 // Get digging parameters
3837 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3838 &playeritem_toolcap);
3840 // If can't dig, try hand
3841 if (!params.diggable) {
3842 const ItemDefinition &hand = itemdef_manager->get("");
3843 const ToolCapabilities *tp = hand.tool_capabilities;
3846 params = getDigParams(nodedef_manager->get(n).groups, tp);
3849 if (params.diggable == false) {
3850 // I guess nobody will wait for this long
3851 runData->dig_time_complete = 10000000.0;
3853 runData->dig_time_complete = params.time;
3855 if (m_cache_enable_particles) {
3856 const ContentFeatures &features =
3857 client->getNodeDefManager()->get(n);
3858 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3859 player, nodepos, features.tiles);
3863 if (runData->dig_time_complete >= 0.001) {
3864 runData->dig_index = (float)crack_animation_length
3866 / runData->dig_time_complete;
3868 // This is for torches
3869 runData->dig_index = crack_animation_length;
3872 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3874 if (sound_dig.exists() && params.diggable) {
3875 if (sound_dig.name == "__group") {
3876 if (params.main_group != "") {
3877 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3878 soundmaker->m_player_leftpunch_sound.name =
3879 std::string("default_dig_") +
3883 soundmaker->m_player_leftpunch_sound = sound_dig;
3887 // Don't show cracks if not diggable
3888 if (runData->dig_time_complete >= 100000.0) {
3889 } else if (runData->dig_index < crack_animation_length) {
3890 //TimeTaker timer("client.setTempMod");
3891 //infostream<<"dig_index="<<dig_index<<std::endl;
3892 client->setCrack(runData->dig_index, nodepos);
3894 infostream << "Digging completed" << std::endl;
3895 client->interact(2, pointed);
3896 client->setCrack(-1, v3s16(0, 0, 0));
3897 bool is_valid_position;
3898 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3899 if (is_valid_position)
3900 client->removeNode(nodepos);
3902 if (m_cache_enable_particles) {
3903 const ContentFeatures &features =
3904 client->getNodeDefManager()->get(wasnode);
3905 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3906 player, nodepos, features.tiles);
3909 runData->dig_time = 0;
3910 runData->digging = false;
3912 runData->nodig_delay_timer =
3913 runData->dig_time_complete / (float)crack_animation_length;
3915 // We don't want a corresponding delay to
3916 // very time consuming nodes
3917 if (runData->nodig_delay_timer > 0.3)
3918 runData->nodig_delay_timer = 0.3;
3920 // We want a slight delay to very little
3921 // time consuming nodes
3922 const float mindelay = 0.15;
3924 if (runData->nodig_delay_timer < mindelay)
3925 runData->nodig_delay_timer = mindelay;
3927 // Send event to trigger sound
3928 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3929 gamedef->event()->put(e);
3932 if (runData->dig_time_complete < 100000.0) {
3933 runData->dig_time += dtime;
3935 runData->dig_time = 0;
3936 client->setCrack(-1, nodepos);
3939 camera->setDigging(0); // left click animation
3943 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
3944 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
3945 const CameraOrientation &cam)
3947 LocalPlayer *player = client->getEnv().getLocalPlayer();
3953 if (draw_control->range_all) {
3954 runData->fog_range = 100000 * BS;
3956 runData->fog_range = 0.9 * draw_control->wanted_range * BS;
3960 Calculate general brightness
3962 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3963 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3964 float direct_brightness;
3967 if (g_settings->getBool("free_move")) {
3968 direct_brightness = time_brightness;
3969 sunlight_seen = true;
3971 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3972 float old_brightness = sky->getBrightness();
3973 direct_brightness = client->getEnv().getClientMap()
3974 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3975 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3979 float time_of_day = runData->time_of_day;
3980 float time_of_day_smooth = runData->time_of_day_smooth;
3982 time_of_day = client->getEnv().getTimeOfDayF();
3984 const float maxsm = 0.05;
3985 const float todsm = 0.05;
3987 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3988 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3989 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3990 time_of_day_smooth = time_of_day;
3992 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3993 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3994 + (time_of_day + 1.0) * todsm;
3996 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3997 + time_of_day * todsm;
3999 runData->time_of_day = time_of_day;
4000 runData->time_of_day_smooth = time_of_day_smooth;
4002 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4003 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4004 player->getPitch());
4010 v3f player_position = player->getPosition();
4011 if (sky->getCloudsVisible()) {
4012 clouds->setVisible(true);
4013 clouds->step(dtime);
4014 clouds->update(v2f(player_position.X, player_position.Z),
4015 sky->getCloudColor());
4017 clouds->setVisible(false);
4024 client->getParticleManager()->step(dtime);
4030 if (m_cache_enable_fog && !flags.force_fog_off) {
4033 video::EFT_FOG_LINEAR,
4034 runData->fog_range * 0.4,
4035 runData->fog_range * 1.0,
4043 video::EFT_FOG_LINEAR,
4053 Get chat messages from client
4056 v2u32 screensize = driver->getScreenSize();
4058 updateChat(*client, dtime, flags.show_debug, screensize,
4059 flags.show_chat, runData->profiler_current_page,
4060 *chat_backend, guitext_chat);
4066 if (client->getPlayerItem() != runData->new_playeritem)
4067 client->selectPlayerItem(runData->new_playeritem);
4069 // Update local inventory if it has changed
4070 if (client->getLocalInventoryUpdated()) {
4071 //infostream<<"Updating local inventory"<<std::endl;
4072 client->getLocalInventory(*local_inventory);
4073 runData->update_wielded_item_trigger = true;
4076 if (runData->update_wielded_item_trigger) {
4077 // Update wielded tool
4078 InventoryList *mlist = local_inventory->getList("main");
4080 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4081 ItemStack item = mlist->getItem(client->getPlayerItem());
4082 camera->wield(item);
4084 runData->update_wielded_item_trigger = false;
4088 Update block draw list every 200ms or when camera direction has
4091 runData->update_draw_list_timer += dtime;
4093 v3f camera_direction = camera->getDirection();
4094 if (runData->update_draw_list_timer >= 0.2
4095 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4096 || flags.camera_offset_changed) {
4097 runData->update_draw_list_timer = 0;
4098 client->getEnv().getClientMap().updateDrawList(driver);
4099 runData->update_draw_list_last_cam_dir = camera_direction;
4102 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4105 make sure menu is on top
4106 1. Delete formspec menu reference if menu was removed
4107 2. Else, make sure formspec menu is on top
4109 if (current_formspec) {
4110 if (current_formspec->getReferenceCount() == 1) {
4111 current_formspec->drop();
4112 current_formspec = NULL;
4113 } else if (!noMenuActive()) {
4114 guiroot->bringToFront(current_formspec);
4122 video::SColor skycolor = sky->getSkyColor();
4124 TimeTaker tt_draw("mainloop: draw");
4126 TimeTaker timer("beginScene");
4127 driver->beginScene(true, true, skycolor);
4128 stats->beginscenetime = timer.stop(true);
4131 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4132 guienv, screensize, skycolor, flags.show_hud,
4133 flags.show_minimap);
4138 if (flags.show_profiler_graph)
4139 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4144 if (runData->damage_flash > 0.0) {
4145 video::SColor color(std::min(runData->damage_flash, 180.0f),
4149 driver->draw2DRectangle(color,
4150 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4153 runData->damage_flash -= 100.0 * dtime;
4159 if (player->hurt_tilt_timer > 0.0) {
4160 player->hurt_tilt_timer -= dtime * 5;
4162 if (player->hurt_tilt_timer < 0)
4163 player->hurt_tilt_strength = 0;
4167 Update minimap pos and rotation
4169 if (flags.show_minimap && flags.show_hud) {
4170 mapper->setPos(floatToInt(player->getPosition(), BS));
4171 mapper->setAngle(player->getYaw());
4178 TimeTaker timer("endScene");
4180 stats->endscenetime = timer.stop(true);
4183 stats->drawtime = tt_draw.stop(true);
4184 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4188 inline static const char *yawToDirectionString(int yaw)
4190 // NOTE: TODO: This can be done mathematically without the else/else-if
4193 const char *player_direction;
4195 yaw = wrapDegrees_0_360(yaw);
4197 if (yaw >= 45 && yaw < 135)
4198 player_direction = "West [-X]";
4199 else if (yaw >= 135 && yaw < 225)
4200 player_direction = "South [-Z]";
4201 else if (yaw >= 225 && yaw < 315)
4202 player_direction = "East [+X]";
4204 player_direction = "North [+Z]";
4206 return player_direction;
4210 void Game::updateGui(float *statustext_time, const RunStats &stats,
4211 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4212 const CameraOrientation &cam)
4214 v2u32 screensize = driver->getScreenSize();
4215 LocalPlayer *player = client->getEnv().getLocalPlayer();
4216 v3f player_position = player->getPosition();
4218 if (flags.show_debug) {
4219 static float drawtime_avg = 0;
4220 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4222 u16 fps = 1.0 / stats.dtime_jitter.avg;
4223 //s32 fps = driver->getFPS();
4225 std::ostringstream os(std::ios_base::binary);
4227 << PROJECT_NAME_C " " << g_version_hash
4229 << " (R: range_all=" << draw_control->range_all << ")"
4230 << std::setprecision(0)
4231 << " drawtime = " << drawtime_avg
4232 << std::setprecision(1)
4233 << ", dtime_jitter = "
4234 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4235 << std::setprecision(1)
4236 << ", v_range = " << draw_control->wanted_range
4237 << std::setprecision(3)
4238 << ", RTT = " << client->getRTT();
4239 guitext->setText(utf8_to_wide(os.str()).c_str());
4240 guitext->setVisible(true);
4241 } else if (flags.show_hud || flags.show_chat) {
4242 std::ostringstream os(std::ios_base::binary);
4243 os << PROJECT_NAME_C " " << g_version_hash;
4244 guitext->setText(utf8_to_wide(os.str()).c_str());
4245 guitext->setVisible(true);
4247 guitext->setVisible(false);
4250 if (guitext->isVisible()) {
4251 core::rect<s32> rect(
4253 screensize.X, 5 + g_fontengine->getTextHeight()
4255 guitext->setRelativePosition(rect);
4258 if (flags.show_debug) {
4259 std::ostringstream os(std::ios_base::binary);
4260 os << std::setprecision(1) << std::fixed
4261 << "(" << (player_position.X / BS)
4262 << ", " << (player_position.Y / BS)
4263 << ", " << (player_position.Z / BS)
4264 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4265 << " " << yawToDirectionString(cam.camera_yaw)
4266 << ") (seed = " << ((u64)client->getMapSeed())
4269 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4270 ClientMap &map = client->getEnv().getClientMap();
4271 const INodeDefManager *nodedef = client->getNodeDefManager();
4272 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4273 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4274 const ContentFeatures &features = nodedef->get(n);
4275 os << " (pointing_at = " << nodedef->get(n).name
4276 << " - " << features.tiledef[0].name.c_str()
4281 guitext2->setText(utf8_to_wide(os.str()).c_str());
4282 guitext2->setVisible(true);
4284 core::rect<s32> rect(
4285 5, 5 + g_fontengine->getTextHeight(),
4286 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4288 guitext2->setRelativePosition(rect);
4290 guitext2->setVisible(false);
4293 guitext_info->setText(infotext.c_str());
4294 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4296 float statustext_time_max = 1.5;
4298 if (!statustext.empty()) {
4299 *statustext_time += dtime;
4301 if (*statustext_time >= statustext_time_max) {
4303 *statustext_time = 0;
4307 guitext_status->setText(statustext.c_str());
4308 guitext_status->setVisible(!statustext.empty());
4310 if (!statustext.empty()) {
4311 s32 status_width = guitext_status->getTextWidth();
4312 s32 status_height = guitext_status->getTextHeight();
4313 s32 status_y = screensize.Y - 150;
4314 s32 status_x = (screensize.X - status_width) / 2;
4315 core::rect<s32> rect(
4316 status_x , status_y - status_height,
4317 status_x + status_width, status_y
4319 guitext_status->setRelativePosition(rect);
4322 video::SColor initial_color(255, 0, 0, 0);
4324 if (guienv->getSkin())
4325 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4327 video::SColor final_color = initial_color;
4328 final_color.setAlpha(0);
4329 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4330 initial_color, final_color,
4331 pow(*statustext_time / statustext_time_max, 2.0f));
4332 guitext_status->setOverrideColor(fade_color);
4333 guitext_status->enableOverrideColor(true);
4338 /* Log times and stuff for visualization */
4339 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4341 Profiler::GraphValues values;
4342 g_profiler->graphGet(values);
4348 /****************************************************************************
4350 ****************************************************************************/
4352 /* On some computers framerate doesn't seem to be automatically limited
4354 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4356 // not using getRealTime is necessary for wine
4357 device->getTimer()->tick(); // Maker sure device time is up-to-date
4358 u32 time = device->getTimer()->getTime();
4359 u32 last_time = fps_timings->last_time;
4361 if (time > last_time) // Make sure time hasn't overflowed
4362 fps_timings->busy_time = time - last_time;
4364 fps_timings->busy_time = 0;
4366 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4367 ? g_settings->getFloat("pause_fps_max")
4368 : g_settings->getFloat("fps_max"));
4370 if (fps_timings->busy_time < frametime_min) {
4371 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4372 device->sleep(fps_timings->sleep_time);
4374 fps_timings->sleep_time = 0;
4377 /* Get the new value of the device timer. Note that device->sleep() may
4378 * not sleep for the entire requested time as sleep may be interrupted and
4379 * therefore it is arguably more accurate to get the new time from the
4380 * device rather than calculating it by adding sleep_time to time.
4383 device->getTimer()->tick(); // Update device timer
4384 time = device->getTimer()->getTime();
4386 if (time > last_time) // Make sure last_time hasn't overflowed
4387 *dtime = (time - last_time) / 1000.0;
4391 fps_timings->last_time = time;
4394 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4395 // pass a copy of it to this function
4396 // Note: \p msg must be allocated using new (not malloc())
4397 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4398 int percent, bool draw_clouds)
4400 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4404 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4406 ((Game *)data)->readSettings();
4409 void Game::readSettings()
4411 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4412 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4413 m_cache_enable_particles = g_settings->getBool("enable_particles");
4414 m_cache_enable_fog = g_settings->getBool("enable_fog");
4415 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4416 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4418 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4421 /****************************************************************************/
4422 /****************************************************************************
4424 ****************************************************************************/
4425 /****************************************************************************/
4427 void Game::extendedResourceCleanup()
4429 // Extended resource accounting
4430 infostream << "Irrlicht resources after cleanup:" << std::endl;
4431 infostream << "\tRemaining meshes : "
4432 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4433 infostream << "\tRemaining textures : "
4434 << driver->getTextureCount() << std::endl;
4436 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4437 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4438 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4442 clearTextureNameCache();
4443 infostream << "\tRemaining materials: "
4444 << driver-> getMaterialRendererCount()
4445 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4449 /****************************************************************************/
4450 /****************************************************************************
4451 extern function for launching the game
4452 ****************************************************************************/
4453 /****************************************************************************/
4455 void the_game(bool *kill,
4457 InputHandler *input,
4458 IrrlichtDevice *device,
4460 const std::string &map_dir,
4461 const std::string &playername,
4462 const std::string &password,
4463 const std::string &address, // If empty local server is created
4466 std::string &error_message,
4467 ChatBackend &chat_backend,
4468 bool *reconnect_requested,
4469 const SubgameSpec &gamespec, // Used for local game
4470 bool simple_singleplayer_mode)
4474 /* Make a copy of the server address because if a local singleplayer server
4475 * is created then this is updated and we don't want to change the value
4476 * passed to us by the calling function
4478 std::string server_address = address;
4482 if (game.startup(kill, random_input, input, device, map_dir,
4483 playername, password, &server_address, port, error_message,
4484 reconnect_requested, &chat_backend, gamespec,
4485 simple_singleplayer_mode)) {
4490 } catch (SerializationError &e) {
4491 error_message = std::string("A serialization error occurred:\n")
4492 + e.what() + "\n\nThe server is probably "
4493 " running a different version of " PROJECT_NAME_C ".";
4494 errorstream << error_message << std::endl;
4495 } catch (ServerError &e) {
4496 error_message = e.what();
4497 errorstream << "ServerError: " << error_message << std::endl;
4498 } catch (ModError &e) {
4499 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4500 errorstream << "ModError: " << error_message << std::endl;