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 "client/keys.h"
27 #include "client/joystick_controller.h"
28 #include "clientmap.h"
31 #include "content_cao.h"
32 #include "drawscene.h"
33 #include "event_manager.h"
34 #include "fontengine.h"
39 #include "guiChatConsole.h"
40 #include "guiFormSpecMenu.h"
41 #include "guiKeyChangeMenu.h"
42 #include "guiPasswordChange.h"
43 #include "guiVolumeChange.h"
45 #include "mainmenumanager.h"
47 #include "nodedef.h" // Needed for determining pointing to nodes
48 #include "nodemetadata.h"
49 #include "particles.h"
51 #include "quicktune_shortcutter.h"
54 #include "shader.h" // For ShaderSource
58 #include "util/directiontables.h"
59 #include "util/pointedthing.h"
60 #include "irrlicht_changes/static_text.h"
63 #include "mapblock_mesh.h"
68 #include "sound_openal.h"
71 #ifdef HAVE_TOUCHSCREENGUI
72 #include "touchscreengui.h"
75 extern Settings *g_settings;
76 extern Profiler *g_profiler;
82 struct TextDestNodeMetadata : public TextDest {
83 TextDestNodeMetadata(v3s16 p, Client *client)
88 // This is deprecated I guess? -celeron55
89 void gotText(std::wstring text)
91 std::string ntext = wide_to_utf8(text);
92 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
93 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
95 fields["text"] = ntext;
96 m_client->sendNodemetaFields(m_p, "", fields);
98 void gotText(const StringMap &fields)
100 m_client->sendNodemetaFields(m_p, "", fields);
107 struct TextDestPlayerInventory : public TextDest {
108 TextDestPlayerInventory(Client *client)
113 TextDestPlayerInventory(Client *client, std::string formname)
116 m_formname = formname;
118 void gotText(const StringMap &fields)
120 m_client->sendInventoryFields(m_formname, fields);
126 struct LocalFormspecHandler : public TextDest {
127 LocalFormspecHandler();
128 LocalFormspecHandler(std::string formname) :
131 m_formname = formname;
134 LocalFormspecHandler(std::string formname, Client *client) :
137 m_formname = formname;
140 void gotText(std::wstring message)
142 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
145 void gotText(const StringMap &fields)
147 if (m_formname == "MT_PAUSE_MENU") {
148 if (fields.find("btn_sound") != fields.end()) {
149 g_gamecallback->changeVolume();
153 if (fields.find("btn_key_config") != fields.end()) {
154 g_gamecallback->keyConfig();
158 if (fields.find("btn_exit_menu") != fields.end()) {
159 g_gamecallback->disconnect();
163 if (fields.find("btn_exit_os") != fields.end()) {
164 g_gamecallback->exitToOS();
168 if (fields.find("btn_change_password") != fields.end()) {
169 g_gamecallback->changePassword();
173 if (fields.find("quit") != fields.end()) {
177 if (fields.find("btn_continue") != fields.end()) {
182 if (m_formname == "MT_DEATH_SCREEN") {
183 assert(m_client != 0);
185 if ((fields.find("btn_respawn") != fields.end())) {
186 m_client->sendRespawn();
190 if (fields.find("quit") != fields.end()) {
191 m_client->sendRespawn();
196 // don't show error message for unhandled cursor keys
197 if ((fields.find("key_up") != fields.end()) ||
198 (fields.find("key_down") != fields.end()) ||
199 (fields.find("key_left") != fields.end()) ||
200 (fields.find("key_right") != fields.end())) {
204 errorstream << "LocalFormspecHandler::gotText unhandled >"
205 << m_formname << "< event" << std::endl;
208 StringMap::const_iterator it;
209 for (it = fields.begin(); it != fields.end(); ++it) {
210 errorstream << "\t" << i << ": " << it->first
211 << "=" << it->second << std::endl;
219 /* Form update callback */
221 class NodeMetadataFormSource: public IFormSource
224 NodeMetadataFormSource(ClientMap *map, v3s16 p):
229 std::string getForm()
231 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
236 return meta->getString("formspec");
238 std::string resolveText(std::string str)
240 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
245 return meta->resolveString(str);
252 class PlayerInventoryFormSource: public IFormSource
255 PlayerInventoryFormSource(Client *client):
259 std::string getForm()
261 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
262 return player->inventory_formspec;
269 Check if a node is pointable
271 inline bool isPointableNode(const MapNode &n,
272 Client *client, bool liquids_pointable)
274 const ContentFeatures &features = client->getNodeDefManager()->get(n);
275 return features.pointable ||
276 (liquids_pointable && features.isLiquid());
279 static inline void getNeighborConnectingFace(v3s16 p, INodeDefManager *nodedef,
280 ClientMap *map, MapNode n, u8 bitmask, u8 *neighbors)
282 MapNode n2 = map->getNodeNoEx(p);
283 if (nodedef->nodeboxConnects(n, n2, bitmask))
284 *neighbors |= bitmask;
287 static inline u8 getNeighbors(v3s16 p, INodeDefManager *nodedef, ClientMap *map, MapNode n)
290 const ContentFeatures &f = nodedef->get(n);
291 // locate possible neighboring nodes to connect to
292 if (f.drawtype == NDT_NODEBOX && f.node_box.type == NODEBOX_CONNECTED) {
296 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
300 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
304 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
308 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
312 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
316 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
323 Find what the player is pointing at
325 PointedThing getPointedThing(Client *client, Hud *hud, const v3f &player_position,
326 const v3f &camera_direction, const v3f &camera_position,
327 core::line3d<f32> shootline, f32 d, bool liquids_pointable,
328 bool look_for_object, const v3s16 &camera_offset,
329 ClientActiveObject *&selected_object)
333 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
334 selectionboxes->clear();
335 static const bool show_entity_selectionbox = g_settings->getBool("show_entity_selectionbox");
337 selected_object = NULL;
339 INodeDefManager *nodedef = client->getNodeDefManager();
340 ClientMap &map = client->getEnv().getClientMap();
342 f32 min_distance = BS * 1001;
344 // First try to find a pointed at active object
345 if (look_for_object) {
346 selected_object = client->getSelectedActiveObject(d * BS,
347 camera_position, shootline);
349 if (selected_object != NULL) {
350 if (show_entity_selectionbox &&
351 selected_object->doShowSelectionBox()) {
352 aabb3f *selection_box = selected_object->getSelectionBox();
353 // Box should exist because object was
354 // returned in the first place
355 assert(selection_box);
357 v3f pos = selected_object->getPosition();
358 selectionboxes->push_back(aabb3f(
359 selection_box->MinEdge, selection_box->MaxEdge));
360 hud->setSelectionPos(pos, camera_offset);
363 min_distance = (selected_object->getPosition() - camera_position).getLength();
365 result.type = POINTEDTHING_OBJECT;
366 result.object_id = selected_object->getId();
370 // That didn't work, try to find a pointed at node
372 v3s16 pos_i = floatToInt(player_position, BS);
374 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
378 s16 ystart = pos_i.Y - (camera_direction.Y < 0 ? a : 1);
379 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
380 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
381 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
382 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
383 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
385 // Prevent signed number overflow
395 v3s16 pointed_pos(0, 0, 0);
397 for (s16 y = ystart; y <= yend; y++) {
398 for (s16 z = zstart; z <= zend; z++) {
399 for (s16 x = xstart; x <= xend; x++) {
401 bool is_valid_position;
404 n = map.getNodeNoEx(p, &is_valid_position);
405 if (!is_valid_position) {
408 if (!isPointableNode(n, client, liquids_pointable)) {
412 std::vector<aabb3f> boxes;
413 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(p, nodedef, &map, n));
416 v3f npf = intToFloat(np, BS);
417 for (std::vector<aabb3f>::const_iterator
419 i != boxes.end(); ++i) {
424 v3f centerpoint = box.getCenter();
425 f32 distance = (centerpoint - camera_position).getLength();
426 if (distance >= min_distance) {
429 if (!box.intersectsWithLine(shootline)) {
432 result.type = POINTEDTHING_NODE;
433 min_distance = distance;
440 if (result.type == POINTEDTHING_NODE) {
442 MapNode n = map.getNodeNoEx(pointed_pos);
443 v3f npf = intToFloat(pointed_pos, BS);
444 std::vector<aabb3f> boxes;
445 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(pointed_pos, nodedef, &map, n));
446 f32 face_min_distance = 1000 * BS;
447 for (std::vector<aabb3f>::const_iterator
449 i != boxes.end(); ++i) {
453 for (u16 j = 0; j < 6; j++) {
454 v3s16 facedir = g_6dirs[j];
455 aabb3f facebox = box;
457 facebox.MinEdge.X = facebox.MaxEdge.X - d;
458 } else if (facedir.X < 0) {
459 facebox.MaxEdge.X = facebox.MinEdge.X + d;
460 } else if (facedir.Y > 0) {
461 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
462 } else if (facedir.Y < 0) {
463 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
464 } else if (facedir.Z > 0) {
465 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
466 } else if (facedir.Z < 0) {
467 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
469 v3f centerpoint = facebox.getCenter();
470 f32 distance = (centerpoint - camera_position).getLength();
471 if (distance >= face_min_distance)
473 if (!facebox.intersectsWithLine(shootline))
475 result.node_abovesurface = pointed_pos + facedir;
476 face_min_distance = distance;
479 selectionboxes->clear();
480 for (std::vector<aabb3f>::const_iterator
482 i != boxes.end(); ++i) {
484 box.MinEdge += v3f(-d, -d, -d);
485 box.MaxEdge += v3f(d, d, d);
486 selectionboxes->push_back(box);
488 hud->setSelectionPos(intToFloat(pointed_pos, BS), camera_offset);
489 result.node_undersurface = pointed_pos;
492 // Update selection mesh light level and vertex colors
493 if (selectionboxes->size() > 0) {
494 v3f pf = hud->getSelectionPos();
495 v3s16 p = floatToInt(pf, BS);
497 // Get selection mesh light level
498 MapNode n = map.getNodeNoEx(p);
499 u16 node_light = getInteriorLight(n, -1, nodedef);
500 u16 light_level = node_light;
502 for (u8 i = 0; i < 6; i++) {
503 n = map.getNodeNoEx(p + g_6dirs[i]);
504 node_light = getInteriorLight(n, -1, nodedef);
505 if (node_light > light_level)
506 light_level = node_light;
509 video::SColor c = MapBlock_LightColor(255, light_level, 0);
511 u8 night = c.getGreen();
512 u32 daynight_ratio = client->getEnv().getDayNightRatio();
513 finalColorBlend(c, day, night, daynight_ratio);
515 // Modify final color a bit with time
516 u32 timer = porting::getTimeMs() % 5000;
517 float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
518 float sin_r = 0.08 * sin(timerf);
519 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
520 float sin_b = 0.08 * sin(timerf + irr::core::PI);
521 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
522 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
523 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
525 // Set mesh final color
526 hud->setSelectionMeshColor(c);
531 /* Profiler display */
533 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
534 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
536 if (show_profiler == 0) {
537 guitext_profiler->setVisible(false);
540 std::ostringstream os(std::ios_base::binary);
541 g_profiler->printPage(os, show_profiler, show_profiler_max);
542 std::wstring text = utf8_to_wide(os.str());
543 setStaticText(guitext_profiler, text.c_str());
544 guitext_profiler->setVisible(true);
546 s32 w = fe->getTextWidth(text.c_str());
551 unsigned text_height = fe->getTextHeight();
553 core::position2di upper_left, lower_right;
556 upper_left.Y = (text_height + 5) * 2;
557 lower_right.X = 12 + w;
558 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
560 if (lower_right.Y > screen_height * 2 / 3)
561 lower_right.Y = screen_height * 2 / 3;
563 core::rect<s32> rect(upper_left, lower_right);
565 guitext_profiler->setRelativePosition(rect);
566 guitext_profiler->setVisible(true);
574 Profiler::GraphValues values;
580 Meta(float initial = 0,
581 video::SColor color = video::SColor(255, 255, 255, 255)):
587 std::deque<Piece> m_log;
595 void put(const Profiler::GraphValues &values)
598 piece.values = values;
599 m_log.push_back(piece);
601 while (m_log.size() > m_log_max_size)
602 m_log.erase(m_log.begin());
605 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
606 gui::IGUIFont *font) const
608 // Do *not* use UNORDERED_MAP here as the order needs
609 // to be the same for each call to prevent flickering
610 std::map<std::string, Meta> m_meta;
612 for (std::deque<Piece>::const_iterator k = m_log.begin();
613 k != m_log.end(); ++k) {
614 const Piece &piece = *k;
616 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
617 i != piece.values.end(); ++i) {
618 const std::string &id = i->first;
619 const float &value = i->second;
620 std::map<std::string, Meta>::iterator j = m_meta.find(id);
622 if (j == m_meta.end()) {
623 m_meta[id] = Meta(value);
627 if (value < j->second.min)
628 j->second.min = value;
630 if (value > j->second.max)
631 j->second.max = value;
636 static const video::SColor usable_colors[] = {
637 video::SColor(255, 255, 100, 100),
638 video::SColor(255, 90, 225, 90),
639 video::SColor(255, 100, 100, 255),
640 video::SColor(255, 255, 150, 50),
641 video::SColor(255, 220, 220, 100)
643 static const u32 usable_colors_count =
644 sizeof(usable_colors) / sizeof(*usable_colors);
645 u32 next_color_i = 0;
647 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
648 i != m_meta.end(); ++i) {
649 Meta &meta = i->second;
650 video::SColor color(255, 200, 200, 200);
652 if (next_color_i < usable_colors_count)
653 color = usable_colors[next_color_i++];
659 s32 textx = x_left + m_log_max_size + 15;
660 s32 textx2 = textx + 200 - 15;
663 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
664 i != m_meta.end(); ++i) {
665 const std::string &id = i->first;
666 const Meta &meta = i->second;
668 s32 y = y_bottom - meta_i * 50;
669 float show_min = meta.min;
670 float show_max = meta.max;
672 if (show_min >= -0.0001 && show_max >= -0.0001) {
673 if (show_min <= show_max * 0.5)
679 snprintf(buf, 10, "%.3g", show_max);
680 font->draw(utf8_to_wide(buf).c_str(),
681 core::rect<s32>(textx, y - graphh,
682 textx2, y - graphh + texth),
684 snprintf(buf, 10, "%.3g", show_min);
685 font->draw(utf8_to_wide(buf).c_str(),
686 core::rect<s32>(textx, y - texth,
689 font->draw(utf8_to_wide(id).c_str(),
690 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
691 textx2, y - graphh / 2 + texth / 2),
694 s32 graph1h = graphh;
695 bool relativegraph = (show_min != 0 && show_min != show_max);
696 float lastscaledvalue = 0.0;
697 bool lastscaledvalue_exists = false;
699 for (std::deque<Piece>::const_iterator j = m_log.begin();
700 j != m_log.end(); ++j) {
701 const Piece &piece = *j;
703 bool value_exists = false;
704 Profiler::GraphValues::const_iterator k =
705 piece.values.find(id);
707 if (k != piece.values.end()) {
714 lastscaledvalue_exists = false;
718 float scaledvalue = 1.0;
720 if (show_max != show_min)
721 scaledvalue = (value - show_min) / (show_max - show_min);
723 if (scaledvalue == 1.0 && value == 0) {
725 lastscaledvalue_exists = false;
730 if (lastscaledvalue_exists) {
731 s32 ivalue1 = lastscaledvalue * graph1h;
732 s32 ivalue2 = scaledvalue * graph1h;
733 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
734 v2s32(x, graph1y - ivalue2), meta.color);
737 lastscaledvalue = scaledvalue;
738 lastscaledvalue_exists = true;
740 s32 ivalue = scaledvalue * graph1h;
741 driver->draw2DLine(v2s32(x, graph1y),
742 v2s32(x, graph1y - ivalue), meta.color);
753 class NodeDugEvent: public MtEvent
759 NodeDugEvent(v3s16 p, MapNode n):
763 const char *getType() const
771 ISoundManager *m_sound;
772 INodeDefManager *m_ndef;
774 float m_player_step_timer;
776 SimpleSoundSpec m_player_step_sound;
777 SimpleSoundSpec m_player_leftpunch_sound;
778 SimpleSoundSpec m_player_rightpunch_sound;
780 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
783 m_player_step_timer(0)
787 void playPlayerStep()
789 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
790 m_player_step_timer = 0.03;
791 m_sound->playSound(m_player_step_sound, false);
795 static void viewBobbingStep(MtEvent *e, void *data)
797 SoundMaker *sm = (SoundMaker *)data;
798 sm->playPlayerStep();
801 static void playerRegainGround(MtEvent *e, void *data)
803 SoundMaker *sm = (SoundMaker *)data;
804 sm->playPlayerStep();
807 static void playerJump(MtEvent *e, void *data)
809 //SoundMaker *sm = (SoundMaker*)data;
812 static void cameraPunchLeft(MtEvent *e, void *data)
814 SoundMaker *sm = (SoundMaker *)data;
815 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
818 static void cameraPunchRight(MtEvent *e, void *data)
820 SoundMaker *sm = (SoundMaker *)data;
821 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
824 static void nodeDug(MtEvent *e, void *data)
826 SoundMaker *sm = (SoundMaker *)data;
827 NodeDugEvent *nde = (NodeDugEvent *)e;
828 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
831 static void playerDamage(MtEvent *e, void *data)
833 SoundMaker *sm = (SoundMaker *)data;
834 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
837 static void playerFallingDamage(MtEvent *e, void *data)
839 SoundMaker *sm = (SoundMaker *)data;
840 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
843 void registerReceiver(MtEventManager *mgr)
845 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
846 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
847 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
848 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
849 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
850 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
851 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
852 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
855 void step(float dtime)
857 m_player_step_timer -= dtime;
861 // Locally stored sounds don't need to be preloaded because of this
862 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
864 std::set<std::string> m_fetched;
866 void fetchSounds(const std::string &name,
867 std::set<std::string> &dst_paths,
868 std::set<std::string> &dst_datas)
870 if (m_fetched.count(name))
873 m_fetched.insert(name);
874 std::string base = porting::path_share + DIR_DELIM + "sounds";
875 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
876 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
877 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
878 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
879 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
880 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
881 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
882 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
883 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
884 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
885 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
889 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
892 bool *m_force_fog_off;
898 void onSettingsChange(const std::string &name)
900 if (name == "enable_fog")
901 m_fogEnabled = g_settings->getBool("enable_fog");
904 static void SettingsCallback(const std::string &name, void *userdata)
906 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
909 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
910 f32 *fog_range, Client *client) :
912 m_force_fog_off(force_fog_off),
913 m_fog_range(fog_range),
916 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
917 m_fogEnabled = g_settings->getBool("enable_fog");
920 ~GameGlobalShaderConstantSetter()
922 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
925 virtual void onSetConstants(video::IMaterialRendererServices *services,
932 video::SColor bgcolor = m_sky->getBgColor();
933 video::SColorf bgcolorf(bgcolor);
934 float bgcolorfa[4] = {
940 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
943 float fog_distance = 10000 * BS;
945 if (m_fogEnabled && !*m_force_fog_off)
946 fog_distance = *m_fog_range;
948 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
951 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
952 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
953 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
955 u32 animation_timer = porting::getTimeMs() % 100000;
956 float animation_timer_f = (float)animation_timer / 100000.0;
957 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
958 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
960 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
961 v3f eye_position = player->getEyePosition();
962 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
963 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
965 v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
966 services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
968 // Uniform sampler layers
969 // before 1.8 there isn't a "integer interface", only float
970 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
974 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
975 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
976 services->setPixelShaderConstant("textureFlags" , (irr::f32 *)&layer2, 1);
981 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
982 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
983 services->setPixelShaderConstant("textureFlags" , (irr::s32 *)&layer2, 1);
988 bool nodePlacementPrediction(Client &client,
989 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
991 std::string prediction = playeritem_def.node_placement_prediction;
992 INodeDefManager *nodedef = client.ndef();
993 ClientMap &map = client.getEnv().getClientMap();
995 bool is_valid_position;
997 node = map.getNodeNoEx(nodepos, &is_valid_position);
998 if (!is_valid_position)
1001 if (prediction != "" && !nodedef->get(node).rightclickable) {
1002 verbosestream << "Node placement prediction for "
1003 << playeritem_def.name << " is "
1004 << prediction << std::endl;
1005 v3s16 p = neighbourpos;
1007 // Place inside node itself if buildable_to
1008 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
1009 if (is_valid_position)
1011 if (nodedef->get(n_under).buildable_to)
1014 node = map.getNodeNoEx(p, &is_valid_position);
1015 if (is_valid_position &&!nodedef->get(node).buildable_to)
1020 // Find id of predicted node
1022 bool found = nodedef->getId(prediction, id);
1025 errorstream << "Node placement prediction failed for "
1026 << playeritem_def.name << " (places "
1028 << ") - Name not known" << std::endl;
1032 // Predict param2 for facedir and wallmounted nodes
1035 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
1036 v3s16 dir = nodepos - neighbourpos;
1038 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
1039 param2 = dir.Y < 0 ? 1 : 0;
1040 } else if (abs(dir.X) > abs(dir.Z)) {
1041 param2 = dir.X < 0 ? 3 : 2;
1043 param2 = dir.Z < 0 ? 5 : 4;
1047 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
1048 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
1050 if (abs(dir.X) > abs(dir.Z)) {
1051 param2 = dir.X < 0 ? 3 : 1;
1053 param2 = dir.Z < 0 ? 2 : 0;
1057 assert(param2 <= 5);
1059 //Check attachment if node is in group attached_node
1060 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
1061 static v3s16 wallmounted_dirs[8] = {
1071 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
1072 pp = p + wallmounted_dirs[param2];
1074 pp = p + v3s16(0, -1, 0);
1076 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
1080 // Add node to client map
1081 MapNode n(id, 0, param2);
1084 LocalPlayer *player = client.getEnv().getLocalPlayer();
1086 // Dont place node when player would be inside new node
1087 // NOTE: This is to be eventually implemented by a mod as client-side Lua
1088 if (!nodedef->get(n).walkable ||
1089 g_settings->getBool("enable_build_where_you_stand") ||
1090 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1091 (nodedef->get(n).walkable &&
1092 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1093 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1095 // This triggers the required mesh update too
1096 client.addNode(p, n);
1099 } catch (InvalidPositionException &e) {
1100 errorstream << "Node placement prediction failed for "
1101 << playeritem_def.name << " (places "
1103 << ") - Position not loaded" << std::endl;
1110 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1111 InventoryManager *invmgr, IGameDef *gamedef,
1112 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1113 JoystickController *joystick,
1114 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1117 if (*cur_formspec == 0) {
1118 *cur_formspec = new GUIFormSpecMenu(device, joystick,
1119 guiroot, -1, &g_menumgr, invmgr, gamedef, tsrc,
1120 fs_src, txt_dest, client);
1121 (*cur_formspec)->doPause = false;
1124 Caution: do not call (*cur_formspec)->drop() here --
1125 the reference might outlive the menu, so we will
1126 periodically check if *cur_formspec is the only
1127 remaining reference (i.e. the menu was removed)
1128 and delete it in that case.
1132 (*cur_formspec)->setFormSource(fs_src);
1133 (*cur_formspec)->setTextDest(txt_dest);
1138 #define SIZE_TAG "size[11,5.5]"
1140 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1143 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1144 InventoryManager *invmgr, IGameDef *gamedef,
1145 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1146 JoystickController *joystick, Client *client)
1148 std::string formspec =
1149 std::string(FORMSPEC_VERSION_STRING) +
1151 "bgcolor[#320000b4;true]"
1152 "label[4.85,1.35;" + gettext("You died.") + "]"
1153 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1157 /* Note: FormspecFormSource and LocalFormspecHandler
1158 * are deleted by guiFormSpecMenu */
1159 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1160 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1162 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,
1163 joystick, fs_src, txt_dst, NULL);
1166 /******************************************************************************/
1167 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1168 InventoryManager *invmgr, IGameDef *gamedef,
1169 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1170 JoystickController *joystick, bool singleplayermode)
1173 std::string control_text = strgettext("Default Controls:\n"
1174 "No menu visible:\n"
1175 "- single tap: button activate\n"
1176 "- double tap: place/use\n"
1177 "- slide finger: look around\n"
1178 "Menu/Inventory visible:\n"
1179 "- double tap (outside):\n"
1181 "- touch stack, touch slot:\n"
1183 "- touch&drag, tap 2nd finger\n"
1184 " --> place single item to slot\n"
1187 std::string control_text = strgettext("Default Controls:\n"
1189 "- Space: jump/climb\n"
1190 "- Shift: sneak/go down\n"
1193 "- Mouse: turn/look\n"
1194 "- Mouse left: dig/punch\n"
1195 "- Mouse right: place/use\n"
1196 "- Mouse wheel: select item\n"
1201 float ypos = singleplayermode ? 0.5 : 0.1;
1202 std::ostringstream os;
1204 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1205 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1206 << strgettext("Continue") << "]";
1208 if (!singleplayermode) {
1209 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1210 << strgettext("Change Password") << "]";
1214 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1215 << strgettext("Sound Volume") << "]";
1216 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1217 << strgettext("Change Keys") << "]";
1219 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1220 << strgettext("Exit to Menu") << "]";
1221 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1222 << strgettext("Exit to OS") << "]"
1223 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1224 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1225 << g_build_info << "\n"
1226 << "path_user = " << wrap_rows(porting::path_user, 20)
1230 /* Note: FormspecFormSource and LocalFormspecHandler *
1231 * are deleted by guiFormSpecMenu */
1232 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1233 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1235 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,
1236 joystick, fs_src, txt_dst, NULL);
1237 std::string con("btn_continue");
1238 (*cur_formspec)->setFocus(con);
1239 (*cur_formspec)->doPause = true;
1242 /******************************************************************************/
1243 static void updateChat(Client &client, f32 dtime, bool show_debug,
1244 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1245 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1247 // Add chat log output for errors to be shown in chat
1248 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1250 // Get new messages from error log buffer
1251 while (!chat_log_error_buf.empty()) {
1252 std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
1253 if (!g_settings->getBool("disable_escape_sequences")) {
1254 error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
1256 chat_backend.addMessage(L"", error_message);
1259 // Get new messages from client
1260 std::wstring message;
1262 while (client.getChatMessage(message)) {
1263 chat_backend.addUnparsedMessage(message);
1266 // Remove old messages
1267 chat_backend.step(dtime);
1269 // Display all messages in a static text element
1270 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1271 EnrichedString recent_chat = chat_backend.getRecentChat();
1272 unsigned int line_height = g_fontengine->getLineHeight();
1274 setStaticText(guitext_chat, recent_chat);
1276 // Update gui element size and position
1280 chat_y += 2 * line_height;
1282 // first pass to calculate height of text to be set
1283 s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
1284 porting::getWindowSize().X - 20);
1285 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1286 guitext_chat->setRelativePosition(rect);
1288 //now use real height of text and adjust rect according to this size
1289 rect = core::rect<s32>(10, chat_y, width,
1290 chat_y + guitext_chat->getTextHeight());
1293 guitext_chat->setRelativePosition(rect);
1294 // Don't show chat if disabled or empty or profiler is enabled
1295 guitext_chat->setVisible(
1296 show_chat && recent_chat_count != 0 && !show_profiler);
1300 /****************************************************************************
1301 Fast key cache for main game loop
1302 ****************************************************************************/
1304 /* This is faster than using getKeySetting with the tradeoff that functions
1305 * using it must make sure that it's initialised before using it and there is
1306 * no error handling (for example bounds checking). This is really intended for
1307 * use only in the main running loop of the client (the_game()) where the faster
1308 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1309 * (e.g. formspecs) should continue using getKeySetting().
1317 populate_nonchanging();
1322 // Keys that are not settings dependent
1323 void populate_nonchanging();
1325 KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
1326 InputHandler *handler;
1329 void KeyCache::populate_nonchanging()
1331 key[KeyType::ESC] = EscapeKey;
1334 void KeyCache::populate()
1336 key[KeyType::FORWARD] = getKeySetting("keymap_forward");
1337 key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
1338 key[KeyType::LEFT] = getKeySetting("keymap_left");
1339 key[KeyType::RIGHT] = getKeySetting("keymap_right");
1340 key[KeyType::JUMP] = getKeySetting("keymap_jump");
1341 key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
1342 key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
1344 key[KeyType::AUTORUN] = getKeySetting("keymap_autorun");
1346 key[KeyType::DROP] = getKeySetting("keymap_drop");
1347 key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
1348 key[KeyType::CHAT] = getKeySetting("keymap_chat");
1349 key[KeyType::CMD] = getKeySetting("keymap_cmd");
1350 key[KeyType::CONSOLE] = getKeySetting("keymap_console");
1351 key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
1352 key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
1353 key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
1354 key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
1355 key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
1356 key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
1357 key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1358 key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1359 key[KeyType::TOGGLE_FORCE_FOG_OFF]
1360 = getKeySetting("keymap_toggle_force_fog_off");
1361 key[KeyType::TOGGLE_UPDATE_CAMERA]
1362 = getKeySetting("keymap_toggle_update_camera");
1363 key[KeyType::TOGGLE_DEBUG]
1364 = getKeySetting("keymap_toggle_debug");
1365 key[KeyType::TOGGLE_PROFILER]
1366 = getKeySetting("keymap_toggle_profiler");
1367 key[KeyType::CAMERA_MODE]
1368 = getKeySetting("keymap_camera_mode");
1369 key[KeyType::INCREASE_VIEWING_RANGE]
1370 = getKeySetting("keymap_increase_viewing_range_min");
1371 key[KeyType::DECREASE_VIEWING_RANGE]
1372 = getKeySetting("keymap_decrease_viewing_range_min");
1373 key[KeyType::RANGESELECT]
1374 = getKeySetting("keymap_rangeselect");
1375 key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
1377 key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1378 key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1379 key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1380 key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1382 key[KeyType::DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1385 // First clear all keys, then re-add the ones we listen for
1386 handler->dontListenForKeys();
1387 for (size_t i = 0; i < KeyType::INTERNAL_ENUM_COUNT; i++) {
1388 handler->listenForKey(key[i]);
1390 handler->listenForKey(EscapeKey);
1391 handler->listenForKey(CancelKey);
1392 for (size_t i = 0; i < 10; i++) {
1393 handler->listenForKey(NumberKey[i]);
1399 /****************************************************************************
1401 ****************************************************************************/
1403 const float object_hit_delay = 0.2;
1406 u32 last_time, busy_time, sleep_time;
1410 /* The reason the following structs are not anonymous structs within the
1411 * class is that they are not used by the majority of member functions and
1412 * many functions that do require objects of thse types do not modify them
1413 * (so they can be passed as a const qualified parameter)
1415 struct CameraOrientation {
1416 f32 camera_yaw; // "right/left"
1417 f32 camera_pitch; // "up/down"
1420 struct GameRunData {
1423 PointedThing pointed_old;
1427 bool update_wielded_item_trigger;
1428 bool reset_jump_timer;
1429 float nodig_delay_timer;
1431 float dig_time_complete;
1432 float repeat_rightclick_timer;
1433 float object_hit_delay_timer;
1434 float time_from_last_punch;
1435 ClientActiveObject *selected_object;
1439 float update_draw_list_timer;
1440 float statustext_time;
1444 v3f update_draw_list_last_cam_dir;
1446 u32 profiler_current_page;
1447 u32 profiler_max_page; // Number of pages
1450 float time_of_day_smooth;
1454 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1462 Jitter dtime_jitter, busy_time_jitter;
1465 /* Flags that can, or may, change during main game loop
1467 struct VolatileRunFlags {
1474 bool show_profiler_graph;
1475 bool disable_camera_update;
1476 bool first_loop_after_window_activation;
1477 bool camera_offset_changed;
1481 /****************************************************************************
1483 ****************************************************************************/
1485 /* This is not intended to be a public class. If a public class becomes
1486 * desirable then it may be better to create another 'wrapper' class that
1487 * hides most of the stuff in this class (nothing in this class is required
1488 * by any other file) but exposes the public methods/data only.
1495 bool startup(bool *kill,
1497 InputHandler *input,
1498 IrrlichtDevice *device,
1499 const std::string &map_dir,
1500 const std::string &playername,
1501 const std::string &password,
1502 // If address is "", local server is used and address is updated
1503 std::string *address,
1505 std::string &error_message,
1507 ChatBackend *chat_backend,
1508 const SubgameSpec &gamespec, // Used for local game
1509 bool simple_singleplayer_mode);
1516 void extendedResourceCleanup();
1518 // Basic initialisation
1519 bool init(const std::string &map_dir, std::string *address,
1521 const SubgameSpec &gamespec);
1523 bool createSingleplayerServer(const std::string map_dir,
1524 const SubgameSpec &gamespec, u16 port, std::string *address);
1527 bool createClient(const std::string &playername,
1528 const std::string &password, std::string *address, u16 port);
1531 // Client connection
1532 bool connectToServer(const std::string &playername,
1533 const std::string &password, std::string *address, u16 port,
1534 bool *connect_ok, bool *aborted);
1535 bool getServerContent(bool *aborted);
1539 void updateInteractTimers(GameRunData *runData, f32 dtime);
1540 bool checkConnection();
1541 bool handleCallbacks();
1542 void processQueues();
1543 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1544 const FpsControl &draw_times, f32 dtime);
1545 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1547 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1550 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1552 void processKeyInput(VolatileRunFlags *flags,
1553 float *statustext_time,
1555 bool *reset_jump_timer,
1556 u32 *profiler_current_page,
1557 u32 profiler_max_page);
1558 void processItemSelection(u16 *new_playeritem);
1560 void dropSelectedItem();
1561 void openInventory();
1562 void openConsole(float height, const wchar_t *line=NULL);
1563 void toggleFreeMove(float *statustext_time);
1564 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1565 void toggleFast(float *statustext_time);
1566 void toggleNoClip(float *statustext_time);
1567 void toggleCinematic(float *statustext_time);
1568 void toggleAutorun(float *statustext_time);
1570 void toggleChat(float *statustext_time, bool *flag);
1571 void toggleHud(float *statustext_time, bool *flag);
1572 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1573 bool shift_pressed);
1574 void toggleFog(float *statustext_time, bool *flag);
1575 void toggleDebug(float *statustext_time, bool *show_debug,
1576 bool *show_profiler_graph);
1577 void toggleUpdateCamera(float *statustext_time, bool *flag);
1578 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1579 u32 profiler_max_page);
1581 void increaseViewRange(float *statustext_time);
1582 void decreaseViewRange(float *statustext_time);
1583 void toggleFullViewRange(float *statustext_time);
1585 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags,
1587 void updateCameraOrientation(CameraOrientation *cam,
1588 const VolatileRunFlags &flags, float dtime);
1589 void updatePlayerControl(const CameraOrientation &cam);
1590 void step(f32 *dtime);
1591 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1592 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1593 float time_from_last_punch);
1594 void updateSound(f32 dtime);
1595 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1597 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1598 void handlePointingAtNode(GameRunData *runData,
1599 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1600 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1601 void handlePointingAtObject(GameRunData *runData,
1602 const PointedThing &pointed, const ItemStack &playeritem,
1603 const v3f &player_position, bool show_debug);
1604 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1605 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1607 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1608 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1609 void updateGui(float *statustext_time, const RunStats &stats,
1610 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1611 const CameraOrientation &cam);
1612 void updateProfilerGraphs(ProfilerGraph *graph);
1615 void limitFps(FpsControl *fps_timings, f32 *dtime);
1617 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1618 bool draw_clouds = true);
1620 static void settingChangedCallback(const std::string &setting_name, void *data);
1621 void readSettings();
1623 inline bool getLeftClicked()
1625 return input->getLeftClicked() ||
1626 input->joystick.getWasKeyDown(KeyType::MOUSE_L);
1628 inline bool getRightClicked()
1630 return input->getRightClicked() ||
1631 input->joystick.getWasKeyDown(KeyType::MOUSE_R);
1633 inline bool isLeftPressed()
1635 return input->getLeftState() ||
1636 input->joystick.isKeyDown(KeyType::MOUSE_L);
1638 inline bool isRightPressed()
1640 return input->getRightState() ||
1641 input->joystick.isKeyDown(KeyType::MOUSE_R);
1643 inline bool getLeftReleased()
1645 return input->getLeftReleased() ||
1646 input->joystick.wasKeyReleased(KeyType::MOUSE_L);
1649 inline bool isKeyDown(GameKeyType k)
1651 return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
1653 inline bool wasKeyDown(GameKeyType k)
1655 return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
1659 void handleAndroidChatInput();
1663 InputHandler *input;
1668 IWritableTextureSource *texture_src;
1669 IWritableShaderSource *shader_src;
1671 // When created, these will be filled with data received from the server
1672 IWritableItemDefManager *itemdef_manager;
1673 IWritableNodeDefManager *nodedef_manager;
1675 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1676 ISoundManager *sound;
1677 bool sound_is_dummy;
1678 SoundMaker *soundmaker;
1680 ChatBackend *chat_backend;
1682 GUIFormSpecMenu *current_formspec;
1684 EventManager *eventmgr;
1685 QuicktuneShortcutter *quicktune;
1687 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1688 MapDrawControl *draw_control;
1690 Clouds *clouds; // Free using ->Drop()
1691 Sky *sky; // Free using ->Drop()
1692 Inventory *local_inventory;
1697 This class does take ownership/responsibily for cleaning up etc of any of
1698 these items (e.g. device)
1700 IrrlichtDevice *device;
1701 video::IVideoDriver *driver;
1702 scene::ISceneManager *smgr;
1704 std::string *error_message;
1705 bool *reconnect_requested;
1706 IGameDef *gamedef; // Convenience (same as *client)
1707 scene::ISceneNode *skybox;
1710 bool simple_singleplayer_mode;
1713 /* Pre-calculated values
1715 int crack_animation_length;
1719 gui::IGUIStaticText *guitext; // First line of debug text
1720 gui::IGUIStaticText *guitext2; // Second line of debug text
1721 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1722 gui::IGUIStaticText *guitext_status;
1723 gui::IGUIStaticText *guitext_chat; // Chat text
1724 gui::IGUIStaticText *guitext_profiler; // Profiler text
1726 std::wstring infotext;
1727 std::wstring statustext;
1731 IntervalLimiter profiler_interval;
1734 * TODO: Local caching of settings is not optimal and should at some stage
1735 * be updated to use a global settings object for getting thse values
1736 * (as opposed to the this local caching). This can be addressed in
1739 bool m_cache_doubletap_jump;
1740 bool m_cache_enable_clouds;
1741 bool m_cache_enable_joysticks;
1742 bool m_cache_enable_particles;
1743 bool m_cache_enable_fog;
1744 bool m_cache_enable_noclip;
1745 bool m_cache_enable_free_move;
1746 f32 m_cache_mouse_sensitivity;
1747 f32 m_cache_joystick_frustum_sensitivity;
1748 f32 m_repeat_right_click_time;
1751 bool m_cache_hold_aux1;
1752 bool m_android_chat_open;
1761 itemdef_manager(NULL),
1762 nodedef_manager(NULL),
1764 sound_is_dummy(false),
1767 current_formspec(NULL),
1770 gui_chat_console(NULL),
1775 local_inventory(NULL),
1779 g_settings->registerChangedCallback("doubletap_jump",
1780 &settingChangedCallback, this);
1781 g_settings->registerChangedCallback("enable_clouds",
1782 &settingChangedCallback, this);
1783 g_settings->registerChangedCallback("doubletap_joysticks",
1784 &settingChangedCallback, this);
1785 g_settings->registerChangedCallback("enable_particles",
1786 &settingChangedCallback, this);
1787 g_settings->registerChangedCallback("enable_fog",
1788 &settingChangedCallback, this);
1789 g_settings->registerChangedCallback("mouse_sensitivity",
1790 &settingChangedCallback, this);
1791 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1792 &settingChangedCallback, this);
1793 g_settings->registerChangedCallback("repeat_rightclick_time",
1794 &settingChangedCallback, this);
1795 g_settings->registerChangedCallback("noclip",
1796 &settingChangedCallback, this);
1797 g_settings->registerChangedCallback("free_move",
1798 &settingChangedCallback, this);
1803 m_cache_hold_aux1 = false; // This is initialised properly later
1810 /****************************************************************************
1812 ****************************************************************************/
1818 if (!sound_is_dummy)
1821 delete server; // deleted first to stop all server threads
1824 delete local_inventory;
1830 delete nodedef_manager;
1831 delete itemdef_manager;
1832 delete draw_control;
1834 extendedResourceCleanup();
1836 g_settings->deregisterChangedCallback("doubletap_jump",
1837 &settingChangedCallback, this);
1838 g_settings->deregisterChangedCallback("enable_clouds",
1839 &settingChangedCallback, this);
1840 g_settings->deregisterChangedCallback("enable_particles",
1841 &settingChangedCallback, this);
1842 g_settings->deregisterChangedCallback("enable_fog",
1843 &settingChangedCallback, this);
1844 g_settings->deregisterChangedCallback("mouse_sensitivity",
1845 &settingChangedCallback, this);
1846 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1847 &settingChangedCallback, this);
1848 g_settings->deregisterChangedCallback("noclip",
1849 &settingChangedCallback, this);
1850 g_settings->deregisterChangedCallback("free_move",
1851 &settingChangedCallback, this);
1854 bool Game::startup(bool *kill,
1856 InputHandler *input,
1857 IrrlichtDevice *device,
1858 const std::string &map_dir,
1859 const std::string &playername,
1860 const std::string &password,
1861 std::string *address, // can change if simple_singleplayer_mode
1863 std::string &error_message,
1865 ChatBackend *chat_backend,
1866 const SubgameSpec &gamespec,
1867 bool simple_singleplayer_mode)
1870 this->device = device;
1872 this->error_message = &error_message;
1873 this->reconnect_requested = reconnect;
1874 this->random_input = random_input;
1875 this->input = input;
1876 this->chat_backend = chat_backend;
1877 this->simple_singleplayer_mode = simple_singleplayer_mode;
1879 keycache.handler = input;
1880 keycache.populate();
1882 driver = device->getVideoDriver();
1883 smgr = device->getSceneManager();
1885 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1887 if (!init(map_dir, address, port, gamespec))
1890 if (!createClient(playername, password, address, port))
1899 ProfilerGraph graph;
1900 RunStats stats = { 0 };
1901 CameraOrientation cam_view_target = { 0 };
1902 CameraOrientation cam_view = { 0 };
1903 GameRunData runData = { 0 };
1904 FpsControl draw_times = { 0 };
1905 VolatileRunFlags flags = { 0 };
1906 f32 dtime; // in seconds
1908 runData.time_from_last_punch = 10.0;
1909 runData.profiler_max_page = 3;
1910 runData.update_wielded_item_trigger = true;
1912 flags.show_chat = true;
1913 flags.show_hud = true;
1914 flags.show_minimap = g_settings->getBool("enable_minimap");
1915 flags.show_debug = g_settings->getBool("show_debug");
1916 flags.invert_mouse = g_settings->getBool("invert_mouse");
1917 flags.first_loop_after_window_activation = true;
1919 /* Clear the profiler */
1920 Profiler::GraphValues dummyvalues;
1921 g_profiler->graphGet(dummyvalues);
1923 draw_times.last_time = device->getTimer()->getTime();
1925 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1927 &flags.force_fog_off,
1931 set_light_table(g_settings->getFloat("display_gamma"));
1934 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1935 && client->checkPrivilege("fast");
1938 while (device->run()
1939 && !(*kill || g_gamecallback->shutdown_requested
1940 || (server && server->getShutdownRequested()))) {
1942 /* Must be called immediately after a device->run() call because it
1943 * uses device->getTimer()->getTime()
1945 limitFps(&draw_times, &dtime);
1947 updateStats(&stats, draw_times, dtime);
1948 updateInteractTimers(&runData, dtime);
1950 if (!checkConnection())
1952 if (!handleCallbacks())
1958 hud->resizeHotbar();
1960 updateProfilers(runData, stats, draw_times, dtime);
1961 processUserInput(&flags, &runData, dtime);
1962 // Update camera before player movement to avoid camera lag of one frame
1963 updateCameraDirection(&cam_view_target, &flags, dtime);
1964 float cam_smoothing = 0;
1965 if (g_settings->getBool("cinematic"))
1966 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1968 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1969 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1970 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1971 cam_view.camera_yaw) * cam_smoothing;
1972 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1973 cam_view.camera_pitch) * cam_smoothing;
1974 updatePlayerControl(cam_view);
1976 processClientEvents(&cam_view_target, &runData.damage_flash);
1977 updateCamera(&flags, draw_times.busy_time, dtime,
1978 runData.time_from_last_punch);
1980 processPlayerInteraction(&runData, dtime, flags.show_hud,
1982 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1983 updateProfilerGraphs(&graph);
1985 // Update if minimap has been disabled by the server
1986 flags.show_minimap &= !client->isMinimapDisabledByServer();
1991 void Game::shutdown()
1993 if (g_settings->get("3d_mode") == "pageflip") {
1994 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1997 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
2002 if (gui_chat_console)
2003 gui_chat_console->drop();
2009 while (g_menumgr.menuCount() > 0) {
2010 g_menumgr.m_stack.front()->setVisible(false);
2011 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
2014 if (current_formspec) {
2015 current_formspec->drop();
2016 current_formspec = NULL;
2019 chat_backend->addMessage(L"", L"# Disconnected.");
2020 chat_backend->addMessage(L"", L"");
2024 while (!client->isShutdown()) {
2025 assert(texture_src != NULL);
2026 assert(shader_src != NULL);
2027 texture_src->processQueue();
2028 shader_src->processQueue();
2035 /****************************************************************************/
2036 /****************************************************************************
2038 ****************************************************************************/
2039 /****************************************************************************/
2042 const std::string &map_dir,
2043 std::string *address,
2045 const SubgameSpec &gamespec)
2047 showOverlayMessage(wgettext("Loading..."), 0, 0);
2049 texture_src = createTextureSource(device);
2050 shader_src = createShaderSource(device);
2052 itemdef_manager = createItemDefManager();
2053 nodedef_manager = createNodeDefManager();
2055 eventmgr = new EventManager();
2056 quicktune = new QuicktuneShortcutter();
2058 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
2059 && eventmgr && quicktune))
2065 // Create a server if not connecting to an existing one
2066 if (*address == "") {
2067 if (!createSingleplayerServer(map_dir, gamespec, port, address))
2074 bool Game::initSound()
2077 if (g_settings->getBool("enable_sound")) {
2078 infostream << "Attempting to use OpenAL audio" << std::endl;
2079 sound = createOpenALSoundManager(&soundfetcher);
2081 infostream << "Failed to initialize OpenAL audio" << std::endl;
2083 infostream << "Sound disabled." << std::endl;
2087 infostream << "Using dummy audio." << std::endl;
2088 sound = &dummySoundManager;
2089 sound_is_dummy = true;
2092 soundmaker = new SoundMaker(sound, nodedef_manager);
2096 soundmaker->registerReceiver(eventmgr);
2101 bool Game::createSingleplayerServer(const std::string map_dir,
2102 const SubgameSpec &gamespec, u16 port, std::string *address)
2104 showOverlayMessage(wgettext("Creating server..."), 0, 5);
2106 std::string bind_str = g_settings->get("bind_address");
2107 Address bind_addr(0, 0, 0, 0, port);
2109 if (g_settings->getBool("ipv6_server")) {
2110 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2114 bind_addr.Resolve(bind_str.c_str());
2115 } catch (ResolveError &e) {
2116 infostream << "Resolving bind address \"" << bind_str
2117 << "\" failed: " << e.what()
2118 << " -- Listening on all addresses." << std::endl;
2121 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2122 *error_message = "Unable to listen on " +
2123 bind_addr.serializeString() +
2124 " because IPv6 is disabled";
2125 errorstream << *error_message << std::endl;
2129 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2130 bind_addr.isIPv6());
2132 server->start(bind_addr);
2137 bool Game::createClient(const std::string &playername,
2138 const std::string &password, std::string *address, u16 port)
2140 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2142 draw_control = new MapDrawControl;
2146 bool could_connect, connect_aborted;
2148 if (!connectToServer(playername, password, address, port,
2149 &could_connect, &connect_aborted))
2152 if (!could_connect) {
2153 if (error_message->empty() && !connect_aborted) {
2154 // Should not happen if error messages are set properly
2155 *error_message = "Connection failed for unknown reason";
2156 errorstream << *error_message << std::endl;
2161 if (!getServerContent(&connect_aborted)) {
2162 if (error_message->empty() && !connect_aborted) {
2163 // Should not happen if error messages are set properly
2164 *error_message = "Connection failed for unknown reason";
2165 errorstream << *error_message << std::endl;
2170 // Update cached textures, meshes and materials
2171 client->afterContentReceived(device);
2175 camera = new Camera(smgr, *draw_control, gamedef);
2176 if (!camera || !camera->successfullyCreated(*error_message))
2178 client->setCamera(camera);
2182 if (m_cache_enable_clouds) {
2183 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2185 *error_message = "Memory allocation error (clouds)";
2186 errorstream << *error_message << std::endl;
2193 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2194 skybox = NULL; // This is used/set later on in the main run loop
2196 local_inventory = new Inventory(itemdef_manager);
2198 if (!(sky && local_inventory)) {
2199 *error_message = "Memory allocation error (sky or local inventory)";
2200 errorstream << *error_message << std::endl;
2204 /* Pre-calculated values
2206 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2208 v2u32 size = t->getOriginalSize();
2209 crack_animation_length = size.Y / size.X;
2211 crack_animation_length = 5;
2217 /* Set window caption
2219 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2221 str += utf8_to_wide(g_version_hash);
2223 str += driver->getName();
2225 device->setWindowCaption(str.c_str());
2227 LocalPlayer *player = client->getEnv().getLocalPlayer();
2228 player->hurt_tilt_timer = 0;
2229 player->hurt_tilt_strength = 0;
2231 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2234 *error_message = "Memory error: could not create HUD";
2235 errorstream << *error_message << std::endl;
2239 mapper = client->getMapper();
2240 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2245 bool Game::initGui()
2247 // First line of debug text
2248 guitext = addStaticText(guienv,
2249 utf8_to_wide(PROJECT_NAME_C).c_str(),
2250 core::rect<s32>(0, 0, 0, 0),
2251 false, false, guiroot);
2253 // Second line of debug text
2254 guitext2 = addStaticText(guienv,
2256 core::rect<s32>(0, 0, 0, 0),
2257 false, false, guiroot);
2259 // At the middle of the screen
2260 // Object infos are shown in this
2261 guitext_info = addStaticText(guienv,
2263 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2264 false, true, guiroot);
2266 // Status text (displays info when showing and hiding GUI stuff, etc.)
2267 guitext_status = addStaticText(guienv,
2269 core::rect<s32>(0, 0, 0, 0),
2270 false, false, guiroot);
2271 guitext_status->setVisible(false);
2274 guitext_chat = addStaticText(
2277 core::rect<s32>(0, 0, 0, 0),
2278 //false, false); // Disable word wrap as of now
2279 false, true, guiroot);
2281 // Remove stale "recent" chat messages from previous connections
2282 chat_backend->clearRecentChat();
2284 // Chat backend and console
2285 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2286 -1, chat_backend, client, &g_menumgr);
2287 if (!gui_chat_console) {
2288 *error_message = "Could not allocate memory for chat console";
2289 errorstream << *error_message << std::endl;
2293 // Profiler text (size is updated when text is updated)
2294 guitext_profiler = addStaticText(guienv,
2296 core::rect<s32>(0, 0, 0, 0),
2297 false, false, guiroot);
2298 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2299 guitext_profiler->setVisible(false);
2300 guitext_profiler->setWordWrap(true);
2302 #ifdef HAVE_TOUCHSCREENGUI
2304 if (g_touchscreengui)
2305 g_touchscreengui->init(texture_src);
2312 bool Game::connectToServer(const std::string &playername,
2313 const std::string &password, std::string *address, u16 port,
2314 bool *connect_ok, bool *aborted)
2316 *connect_ok = false; // Let's not be overly optimistic
2318 bool local_server_mode = false;
2320 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2322 Address connect_address(0, 0, 0, 0, port);
2325 connect_address.Resolve(address->c_str());
2327 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2328 //connect_address.Resolve("localhost");
2329 if (connect_address.isIPv6()) {
2330 IPv6AddressBytes addr_bytes;
2331 addr_bytes.bytes[15] = 1;
2332 connect_address.setAddress(&addr_bytes);
2334 connect_address.setAddress(127, 0, 0, 1);
2336 local_server_mode = true;
2338 } catch (ResolveError &e) {
2339 *error_message = std::string("Couldn't resolve address: ") + e.what();
2340 errorstream << *error_message << std::endl;
2344 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2345 *error_message = "Unable to connect to " +
2346 connect_address.serializeString() +
2347 " because IPv6 is disabled";
2348 errorstream << *error_message << std::endl;
2352 client = new Client(device,
2353 playername.c_str(), password,
2354 *draw_control, texture_src, shader_src,
2355 itemdef_manager, nodedef_manager, sound, eventmgr,
2356 connect_address.isIPv6());
2361 gamedef = client; // Client acts as our GameDef
2363 infostream << "Connecting to server at ";
2364 connect_address.print(&infostream);
2365 infostream << std::endl;
2367 client->connect(connect_address, *address,
2368 simple_singleplayer_mode || local_server_mode);
2371 Wait for server to accept connection
2377 FpsControl fps_control = { 0 };
2379 f32 wait_time = 0; // in seconds
2381 fps_control.last_time = device->getTimer()->getTime();
2383 while (device->run()) {
2385 limitFps(&fps_control, &dtime);
2387 // Update client and server
2388 client->step(dtime);
2391 server->step(dtime);
2394 if (client->getState() == LC_Init) {
2400 if (client->accessDenied()) {
2401 *error_message = "Access denied. Reason: "
2402 + client->accessDeniedReason();
2403 *reconnect_requested = client->reconnectRequested();
2404 errorstream << *error_message << std::endl;
2408 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2410 infostream << "Connect aborted [Escape]" << std::endl;
2415 // Only time out if we aren't waiting for the server we started
2416 if ((*address != "") && (wait_time > 10)) {
2417 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2418 // If no pre v25 init was sent, and no answer was received,
2419 // but the low level connection could be established
2420 // (meaning that we have a peer id), then we probably wanted
2421 // to connect to a legacy server. In this case, tell the user
2422 // to enable the option to be able to connect.
2423 if (!sent_old_init &&
2424 (client->getProtoVersion() == 0) &&
2425 client->connectedToServer()) {
2426 *error_message = "Connection failure: init packet not "
2427 "recognized by server.\n"
2428 "Most likely the server uses an old protocol version (<v25).\n"
2429 "Please ask the server owner to update to 0.4.13 or later.\n"
2430 "To still connect to the server in the meantime,\n"
2431 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2432 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2433 "entry in the advanced settings menu.";
2435 *error_message = "Connection timed out.";
2437 errorstream << *error_message << std::endl;
2442 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2444 } catch (con::PeerNotFoundException &e) {
2445 // TODO: Should something be done here? At least an info/error
2453 bool Game::getServerContent(bool *aborted)
2457 FpsControl fps_control = { 0 };
2458 f32 dtime; // in seconds
2460 fps_control.last_time = device->getTimer()->getTime();
2462 while (device->run()) {
2464 limitFps(&fps_control, &dtime);
2466 // Update client and server
2467 client->step(dtime);
2470 server->step(dtime);
2473 if (client->mediaReceived() && client->itemdefReceived() &&
2474 client->nodedefReceived()) {
2479 if (!checkConnection())
2482 if (client->getState() < LC_Init) {
2483 *error_message = "Client disconnected";
2484 errorstream << *error_message << std::endl;
2488 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2490 infostream << "Connect aborted [Escape]" << std::endl;
2497 if (!client->itemdefReceived()) {
2498 const wchar_t *text = wgettext("Item definitions...");
2500 draw_load_screen(text, device, guienv, dtime, progress);
2502 } else if (!client->nodedefReceived()) {
2503 const wchar_t *text = wgettext("Node definitions...");
2505 draw_load_screen(text, device, guienv, dtime, progress);
2508 std::stringstream message;
2509 message.precision(3);
2510 message << gettext("Media...");
2512 if ((USE_CURL == 0) ||
2513 (!g_settings->getBool("enable_remote_media_server"))) {
2514 float cur = client->getCurRate();
2515 std::string cur_unit = gettext("KiB/s");
2519 cur_unit = gettext("MiB/s");
2522 message << " (" << cur << ' ' << cur_unit << ")";
2525 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2526 draw_load_screen(utf8_to_wide(message.str()), device,
2527 guienv, dtime, progress);
2535 /****************************************************************************/
2536 /****************************************************************************
2538 ****************************************************************************/
2539 /****************************************************************************/
2541 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2543 if (runData->nodig_delay_timer >= 0)
2544 runData->nodig_delay_timer -= dtime;
2546 if (runData->object_hit_delay_timer >= 0)
2547 runData->object_hit_delay_timer -= dtime;
2549 runData->time_from_last_punch += dtime;
2553 /* returns false if game should exit, otherwise true
2555 inline bool Game::checkConnection()
2557 if (client->accessDenied()) {
2558 *error_message = "Access denied. Reason: "
2559 + client->accessDeniedReason();
2560 *reconnect_requested = client->reconnectRequested();
2561 errorstream << *error_message << std::endl;
2569 /* returns false if game should exit, otherwise true
2571 inline bool Game::handleCallbacks()
2573 if (g_gamecallback->disconnect_requested) {
2574 g_gamecallback->disconnect_requested = false;
2578 if (g_gamecallback->changepassword_requested) {
2579 (new GUIPasswordChange(guienv, guiroot, -1,
2580 &g_menumgr, client))->drop();
2581 g_gamecallback->changepassword_requested = false;
2584 if (g_gamecallback->changevolume_requested) {
2585 (new GUIVolumeChange(guienv, guiroot, -1,
2586 &g_menumgr))->drop();
2587 g_gamecallback->changevolume_requested = false;
2590 if (g_gamecallback->keyconfig_requested) {
2591 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2592 &g_menumgr))->drop();
2593 g_gamecallback->keyconfig_requested = false;
2596 if (g_gamecallback->keyconfig_changed) {
2597 keycache.populate(); // update the cache with new settings
2598 g_gamecallback->keyconfig_changed = false;
2605 void Game::processQueues()
2607 texture_src->processQueue();
2608 itemdef_manager->processQueue(gamedef);
2609 shader_src->processQueue();
2613 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2614 const FpsControl &draw_times, f32 dtime)
2616 float profiler_print_interval =
2617 g_settings->getFloat("profiler_print_interval");
2618 bool print_to_log = true;
2620 if (profiler_print_interval == 0) {
2621 print_to_log = false;
2622 profiler_print_interval = 5;
2625 if (profiler_interval.step(dtime, profiler_print_interval)) {
2627 infostream << "Profiler:" << std::endl;
2628 g_profiler->print(infostream);
2631 update_profiler_gui(guitext_profiler, g_fontengine,
2632 runData.profiler_current_page, runData.profiler_max_page,
2633 driver->getScreenSize().Height);
2635 g_profiler->clear();
2638 addProfilerGraphs(stats, draw_times, dtime);
2642 void Game::addProfilerGraphs(const RunStats &stats,
2643 const FpsControl &draw_times, f32 dtime)
2645 g_profiler->graphAdd("mainloop_other",
2646 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2648 if (draw_times.sleep_time != 0)
2649 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2650 g_profiler->graphAdd("mainloop_dtime", dtime);
2652 g_profiler->add("Elapsed time", dtime);
2653 g_profiler->avg("FPS", 1. / dtime);
2657 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2664 /* Time average and jitter calculation
2666 jp = &stats->dtime_jitter;
2667 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2669 jitter = dtime - jp->avg;
2671 if (jitter > jp->max)
2674 jp->counter += dtime;
2676 if (jp->counter > 0.0) {
2678 jp->max_sample = jp->max;
2679 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2683 /* Busytime average and jitter calculation
2685 jp = &stats->busy_time_jitter;
2686 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2688 jitter = draw_times.busy_time - jp->avg;
2690 if (jitter > jp->max)
2692 if (jitter < jp->min)
2695 jp->counter += dtime;
2697 if (jp->counter > 0.0) {
2699 jp->max_sample = jp->max;
2700 jp->min_sample = jp->min;
2708 /****************************************************************************
2710 ****************************************************************************/
2712 void Game::processUserInput(VolatileRunFlags *flags,
2713 GameRunData *runData, f32 dtime)
2715 // Reset input if window not active or some menu is active
2716 if (device->isWindowActive() == false
2717 || noMenuActive() == false
2718 || guienv->hasFocus(gui_chat_console)) {
2720 #ifdef HAVE_TOUCHSCREENGUI
2721 g_touchscreengui->hide();
2724 #ifdef HAVE_TOUCHSCREENGUI
2725 else if (g_touchscreengui) {
2726 /* on touchscreengui step may generate own input events which ain't
2727 * what we want in case we just did clear them */
2728 g_touchscreengui->step(dtime);
2732 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2733 gui_chat_console->closeConsoleAtOnce();
2736 // Input handler step() (used by the random input generator)
2740 if (current_formspec != NULL)
2741 current_formspec->getAndroidUIInput();
2743 handleAndroidChatInput();
2746 // Increase timer for double tap of "keymap_jump"
2747 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2748 runData->jump_timer += dtime;
2752 &runData->statustext_time,
2753 &runData->jump_timer,
2754 &runData->reset_jump_timer,
2755 &runData->profiler_current_page,
2756 runData->profiler_max_page);
2758 processItemSelection(&runData->new_playeritem);
2762 void Game::processKeyInput(VolatileRunFlags *flags,
2763 float *statustext_time,
2765 bool *reset_jump_timer,
2766 u32 *profiler_current_page,
2767 u32 profiler_max_page)
2770 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2772 if (wasKeyDown(KeyType::DROP)) {
2774 } else if (wasKeyDown(KeyType::AUTORUN)) {
2775 toggleAutorun(statustext_time);
2776 } else if (wasKeyDown(KeyType::INVENTORY)) {
2778 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2779 if (!gui_chat_console->isOpenInhibited()) {
2780 show_pause_menu(¤t_formspec, client, gamedef,
2781 texture_src, device, &input->joystick,
2782 simple_singleplayer_mode);
2784 } else if (wasKeyDown(KeyType::CHAT)) {
2785 openConsole(0.2, L"");
2786 } else if (wasKeyDown(KeyType::CMD)) {
2787 openConsole(0.2, L"/");
2788 } else if (wasKeyDown(KeyType::CONSOLE)) {
2790 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2791 toggleFreeMove(statustext_time);
2792 } else if (wasKeyDown(KeyType::JUMP)) {
2793 toggleFreeMoveAlt(statustext_time, jump_timer);
2794 *reset_jump_timer = true;
2795 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2796 toggleFast(statustext_time);
2797 } else if (wasKeyDown(KeyType::NOCLIP)) {
2798 toggleNoClip(statustext_time);
2799 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2800 toggleCinematic(statustext_time);
2801 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2802 client->makeScreenshot(device);
2803 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2804 toggleHud(statustext_time, &flags->show_hud);
2805 } else if (wasKeyDown(KeyType::MINIMAP)) {
2806 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2807 isKeyDown(KeyType::SNEAK));
2808 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2809 toggleChat(statustext_time, &flags->show_chat);
2810 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2811 toggleFog(statustext_time, &flags->force_fog_off);
2812 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2813 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2814 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2815 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2816 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2817 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2818 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2819 increaseViewRange(statustext_time);
2820 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2821 decreaseViewRange(statustext_time);
2822 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2823 toggleFullViewRange(statustext_time);
2824 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2826 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2828 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2830 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2832 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2833 // Print debug stacks
2834 dstream << "-----------------------------------------"
2836 dstream << "Printing debug stacks:" << std::endl;
2837 dstream << "-----------------------------------------"
2839 debug_stacks_print();
2842 if (!isKeyDown(KeyType::JUMP) && *reset_jump_timer) {
2843 *reset_jump_timer = false;
2849 if (quicktune->hasMessage()) {
2850 std::string msg = quicktune->getMessage();
2851 statustext = utf8_to_wide(msg);
2852 *statustext_time = 0;
2856 void Game::processItemSelection(u16 *new_playeritem)
2858 LocalPlayer *player = client->getEnv().getLocalPlayer();
2860 /* Item selection using mouse wheel
2862 *new_playeritem = client->getPlayerItem();
2864 s32 wheel = input->getMouseWheel();
2865 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2866 player->hud_hotbar_itemcount - 1);
2870 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN)) {
2874 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP)) {
2879 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2881 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2884 /* Item selection using keyboard
2886 for (u16 i = 0; i < 10; i++) {
2887 static const KeyPress *item_keys[10] = {
2888 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2889 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2890 NumberKey + 9, NumberKey + 0,
2893 if (input->wasKeyDown(*item_keys[i])) {
2894 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2895 *new_playeritem = i;
2896 infostream << "Selected item: " << new_playeritem << std::endl;
2904 void Game::dropSelectedItem()
2906 IDropAction *a = new IDropAction();
2908 a->from_inv.setCurrentPlayer();
2909 a->from_list = "main";
2910 a->from_i = client->getPlayerItem();
2911 client->inventoryAction(a);
2915 void Game::openInventory()
2918 * Don't permit to open inventory is CAO or player doesn't exists.
2919 * This prevent showing an empty inventory at player load
2922 LocalPlayer *player = client->getEnv().getLocalPlayer();
2923 if (player == NULL || player->getCAO() == NULL)
2926 infostream << "the_game: " << "Launching inventory" << std::endl;
2928 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2929 TextDest *txt_dst = new TextDestPlayerInventory(client);
2931 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2932 device, &input->joystick, fs_src, txt_dst, client);
2934 InventoryLocation inventoryloc;
2935 inventoryloc.setCurrentPlayer();
2936 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2940 void Game::openConsole(float height, const wchar_t *line)
2943 porting::showInputDialog(gettext("ok"), "", "", 2);
2944 m_android_chat_open = true;
2946 if (gui_chat_console->isOpenInhibited())
2948 gui_chat_console->openConsole(height);
2950 gui_chat_console->setCloseOnEnter(true);
2951 gui_chat_console->replaceAndAddToHistory(line);
2957 void Game::handleAndroidChatInput()
2959 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2960 std::string text = porting::getInputDialogValue();
2961 client->typeChatMessage(utf8_to_wide(text));
2967 void Game::toggleFreeMove(float *statustext_time)
2969 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2971 bool free_move = !g_settings->getBool("free_move");
2972 g_settings->set("free_move", bool_to_cstr(free_move));
2974 *statustext_time = 0;
2975 statustext = msg[free_move];
2976 if (free_move && !client->checkPrivilege("fly"))
2977 statustext += L" (note: no 'fly' privilege)";
2981 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2983 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2984 toggleFreeMove(statustext_time);
2988 void Game::toggleFast(float *statustext_time)
2990 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2991 bool fast_move = !g_settings->getBool("fast_move");
2992 g_settings->set("fast_move", bool_to_cstr(fast_move));
2994 *statustext_time = 0;
2995 statustext = msg[fast_move];
2997 bool has_fast_privs = client->checkPrivilege("fast");
2999 if (fast_move && !has_fast_privs)
3000 statustext += L" (note: no 'fast' privilege)";
3003 m_cache_hold_aux1 = fast_move && has_fast_privs;
3008 void Game::toggleNoClip(float *statustext_time)
3010 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
3011 bool noclip = !g_settings->getBool("noclip");
3012 g_settings->set("noclip", bool_to_cstr(noclip));
3014 *statustext_time = 0;
3015 statustext = msg[noclip];
3017 if (noclip && !client->checkPrivilege("noclip"))
3018 statustext += L" (note: no 'noclip' privilege)";
3021 void Game::toggleCinematic(float *statustext_time)
3023 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
3024 bool cinematic = !g_settings->getBool("cinematic");
3025 g_settings->set("cinematic", bool_to_cstr(cinematic));
3027 *statustext_time = 0;
3028 statustext = msg[cinematic];
3031 // Add WoW-style autorun by toggling continuous forward.
3032 void Game::toggleAutorun(float *statustext_time)
3034 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
3035 bool autorun_enabled = !g_settings->getBool("continuous_forward");
3036 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
3038 *statustext_time = 0;
3039 statustext = msg[autorun_enabled ? 1 : 0];
3042 void Game::toggleChat(float *statustext_time, bool *flag)
3044 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
3047 *statustext_time = 0;
3048 statustext = msg[*flag];
3052 void Game::toggleHud(float *statustext_time, bool *flag)
3054 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
3057 *statustext_time = 0;
3058 statustext = msg[*flag];
3061 void Game::toggleMinimap(float *statustext_time, bool *flag,
3062 bool show_hud, bool shift_pressed)
3064 if (!show_hud || !g_settings->getBool("enable_minimap"))
3067 if (shift_pressed) {
3068 mapper->toggleMinimapShape();
3072 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
3074 MinimapMode mode = MINIMAP_MODE_OFF;
3075 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
3076 mode = mapper->getMinimapMode();
3077 mode = (MinimapMode)((int)mode + 1);
3082 case MINIMAP_MODE_SURFACEx1:
3083 statustext = L"Minimap in surface mode, Zoom x1";
3085 case MINIMAP_MODE_SURFACEx2:
3086 statustext = L"Minimap in surface mode, Zoom x2";
3088 case MINIMAP_MODE_SURFACEx4:
3089 statustext = L"Minimap in surface mode, Zoom x4";
3091 case MINIMAP_MODE_RADARx1:
3092 statustext = L"Minimap in radar mode, Zoom x1";
3094 case MINIMAP_MODE_RADARx2:
3095 statustext = L"Minimap in radar mode, Zoom x2";
3097 case MINIMAP_MODE_RADARx4:
3098 statustext = L"Minimap in radar mode, Zoom x4";
3101 mode = MINIMAP_MODE_OFF;
3103 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
3104 L"Minimap hidden" : L"Minimap disabled by server";
3107 *statustext_time = 0;
3108 mapper->setMinimapMode(mode);
3111 void Game::toggleFog(float *statustext_time, bool *flag)
3113 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
3116 *statustext_time = 0;
3117 statustext = msg[*flag];
3121 void Game::toggleDebug(float *statustext_time, bool *show_debug,
3122 bool *show_profiler_graph)
3124 // Initial / 3x toggle: Chat only
3125 // 1x toggle: Debug text with chat
3126 // 2x toggle: Debug text with profiler graph
3129 *show_profiler_graph = false;
3130 statustext = L"Debug info shown";
3131 } else if (*show_profiler_graph) {
3132 *show_debug = false;
3133 *show_profiler_graph = false;
3134 statustext = L"Debug info and profiler graph hidden";
3136 *show_profiler_graph = true;
3137 statustext = L"Profiler graph shown";
3139 *statustext_time = 0;
3143 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3145 static const wchar_t *msg[] = {
3146 L"Camera update enabled",
3147 L"Camera update disabled"
3151 *statustext_time = 0;
3152 statustext = msg[*flag];
3156 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3157 u32 profiler_max_page)
3159 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3161 // FIXME: This updates the profiler with incomplete values
3162 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3163 profiler_max_page, driver->getScreenSize().Height);
3165 if (*profiler_current_page != 0) {
3166 std::wstringstream sstr;
3167 sstr << "Profiler shown (page " << *profiler_current_page
3168 << " of " << profiler_max_page << ")";
3169 statustext = sstr.str();
3171 statustext = L"Profiler hidden";
3173 *statustext_time = 0;
3177 void Game::increaseViewRange(float *statustext_time)
3179 s16 range = g_settings->getS16("viewing_range");
3180 s16 range_new = range + 10;
3181 g_settings->set("viewing_range", itos(range_new));
3182 statustext = utf8_to_wide("Viewing range changed to "
3184 *statustext_time = 0;
3188 void Game::decreaseViewRange(float *statustext_time)
3190 s16 range = g_settings->getS16("viewing_range");
3191 s16 range_new = range - 10;
3196 g_settings->set("viewing_range", itos(range_new));
3197 statustext = utf8_to_wide("Viewing range changed to "
3199 *statustext_time = 0;
3203 void Game::toggleFullViewRange(float *statustext_time)
3205 static const wchar_t *msg[] = {
3206 L"Disabled full viewing range",
3207 L"Enabled full viewing range"
3210 draw_control->range_all = !draw_control->range_all;
3211 infostream << msg[draw_control->range_all] << std::endl;
3212 statustext = msg[draw_control->range_all];
3213 *statustext_time = 0;
3217 void Game::updateCameraDirection(CameraOrientation *cam,
3218 VolatileRunFlags *flags, float dtime)
3220 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3223 if (!random_input) {
3224 // Mac OSX gets upset if this is set every frame
3225 if (device->getCursorControl()->isVisible())
3226 device->getCursorControl()->setVisible(false);
3230 if (flags->first_loop_after_window_activation)
3231 flags->first_loop_after_window_activation = false;
3233 updateCameraOrientation(cam, *flags, dtime);
3235 input->setMousePos((driver->getScreenSize().Width / 2),
3236 (driver->getScreenSize().Height / 2));
3240 // Mac OSX gets upset if this is set every frame
3241 if (device->getCursorControl()->isVisible() == false)
3242 device->getCursorControl()->setVisible(true);
3245 if (!flags->first_loop_after_window_activation)
3246 flags->first_loop_after_window_activation = true;
3251 void Game::updateCameraOrientation(CameraOrientation *cam,
3252 const VolatileRunFlags &flags, float dtime)
3254 #ifdef HAVE_TOUCHSCREENGUI
3255 if (g_touchscreengui) {
3256 cam->camera_yaw = g_touchscreengui->getYaw();
3257 cam->camera_pitch = g_touchscreengui->getPitch();
3261 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3262 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3264 if (flags.invert_mouse
3265 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3269 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3270 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3272 #ifdef HAVE_TOUCHSCREENGUI
3276 if (m_cache_enable_joysticks) {
3277 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3278 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) *
3280 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) *
3284 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3288 void Game::updatePlayerControl(const CameraOrientation &cam)
3290 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3292 // DO NOT use the isKeyDown method for the forward, backward, left, right
3293 // buttons, as the code that uses the controls needs to be able to
3294 // distinguish between the two in order to know when to use joysticks.
3296 PlayerControl control(
3297 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3298 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3299 input->isKeyDown(keycache.key[KeyType::LEFT]),
3300 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3301 isKeyDown(KeyType::JUMP),
3302 isKeyDown(KeyType::SPECIAL1),
3303 isKeyDown(KeyType::SNEAK),
3304 isKeyDown(KeyType::ZOOM),
3309 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3310 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3314 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3315 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3316 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3317 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3318 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3319 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3320 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3321 ( (u32)(isLeftPressed() & 0x1) << 7) |
3322 ( (u32)(isRightPressed() & 0x1) << 8
3326 /* For Android, simulate holding down AUX1 (fast move) if the user has
3327 * the fast_move setting toggled on. If there is an aux1 key defined for
3328 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3331 if (m_cache_hold_aux1) {
3332 control.aux1 = control.aux1 ^ true;
3333 keypress_bits ^= ((u32)(1U << 5));
3337 client->setPlayerControl(control);
3338 LocalPlayer *player = client->getEnv().getLocalPlayer();
3339 player->keyPressed = keypress_bits;
3345 inline void Game::step(f32 *dtime)
3347 bool can_be_and_is_paused =
3348 (simple_singleplayer_mode && g_menumgr.pausesGame());
3350 if (can_be_and_is_paused) { // This is for a singleplayer server
3351 *dtime = 0; // No time passes
3353 if (server != NULL) {
3354 //TimeTaker timer("server->step(dtime)");
3355 server->step(*dtime);
3358 //TimeTaker timer("client.step(dtime)");
3359 client->step(*dtime);
3364 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3366 ClientEvent event = client->getClientEvent();
3368 LocalPlayer *player = client->getEnv().getLocalPlayer();
3370 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3372 if (event.type == CE_PLAYER_DAMAGE &&
3373 client->getHP() != 0) {
3374 //u16 damage = event.player_damage.amount;
3375 //infostream<<"Player damage: "<<damage<<std::endl;
3377 *damage_flash += 95.0 + 3.2 * event.player_damage.amount;
3378 *damage_flash = MYMIN(*damage_flash, 127.0);
3380 player->hurt_tilt_timer = 1.5;
3381 player->hurt_tilt_strength =
3382 rangelim(event.player_damage.amount / 4, 1.0, 4.0);
3384 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3385 gamedef->event()->put(e);
3386 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3387 cam->camera_yaw = event.player_force_move.yaw;
3388 cam->camera_pitch = event.player_force_move.pitch;
3389 } else if (event.type == CE_DEATHSCREEN) {
3390 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3391 device, &input->joystick, client);
3393 chat_backend->addMessage(L"", L"You died.");
3395 /* Handle visualization */
3397 player->hurt_tilt_timer = 0;
3398 player->hurt_tilt_strength = 0;
3400 } else if (event.type == CE_SHOW_FORMSPEC) {
3401 FormspecFormSource *fs_src =
3402 new FormspecFormSource(*(event.show_formspec.formspec));
3403 TextDestPlayerInventory *txt_dst =
3404 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3406 create_formspec_menu(¤t_formspec, client, gamedef,
3407 texture_src, device, &input->joystick,
3408 fs_src, txt_dst, client);
3410 delete(event.show_formspec.formspec);
3411 delete(event.show_formspec.formname);
3412 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3413 (event.type == CE_ADD_PARTICLESPAWNER) ||
3414 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3415 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3417 } else if (event.type == CE_HUDADD) {
3418 u32 id = event.hudadd.id;
3420 LocalPlayer *player = client->getEnv().getLocalPlayer();
3421 HudElement *e = player->getHud(id);
3424 delete event.hudadd.pos;
3425 delete event.hudadd.name;
3426 delete event.hudadd.scale;
3427 delete event.hudadd.text;
3428 delete event.hudadd.align;
3429 delete event.hudadd.offset;
3430 delete event.hudadd.world_pos;
3431 delete event.hudadd.size;
3436 e->type = (HudElementType)event.hudadd.type;
3437 e->pos = *event.hudadd.pos;
3438 e->name = *event.hudadd.name;
3439 e->scale = *event.hudadd.scale;
3440 e->text = *event.hudadd.text;
3441 e->number = event.hudadd.number;
3442 e->item = event.hudadd.item;
3443 e->dir = event.hudadd.dir;
3444 e->align = *event.hudadd.align;
3445 e->offset = *event.hudadd.offset;
3446 e->world_pos = *event.hudadd.world_pos;
3447 e->size = *event.hudadd.size;
3449 u32 new_id = player->addHud(e);
3450 //if this isn't true our huds aren't consistent
3451 sanity_check(new_id == id);
3453 delete event.hudadd.pos;
3454 delete event.hudadd.name;
3455 delete event.hudadd.scale;
3456 delete event.hudadd.text;
3457 delete event.hudadd.align;
3458 delete event.hudadd.offset;
3459 delete event.hudadd.world_pos;
3460 delete event.hudadd.size;
3461 } else if (event.type == CE_HUDRM) {
3462 HudElement *e = player->removeHud(event.hudrm.id);
3466 } else if (event.type == CE_HUDCHANGE) {
3467 u32 id = event.hudchange.id;
3468 HudElement *e = player->getHud(id);
3471 delete event.hudchange.v3fdata;
3472 delete event.hudchange.v2fdata;
3473 delete event.hudchange.sdata;
3474 delete event.hudchange.v2s32data;
3478 switch (event.hudchange.stat) {
3480 e->pos = *event.hudchange.v2fdata;
3484 e->name = *event.hudchange.sdata;
3487 case HUD_STAT_SCALE:
3488 e->scale = *event.hudchange.v2fdata;
3492 e->text = *event.hudchange.sdata;
3495 case HUD_STAT_NUMBER:
3496 e->number = event.hudchange.data;
3500 e->item = event.hudchange.data;
3504 e->dir = event.hudchange.data;
3507 case HUD_STAT_ALIGN:
3508 e->align = *event.hudchange.v2fdata;
3511 case HUD_STAT_OFFSET:
3512 e->offset = *event.hudchange.v2fdata;
3515 case HUD_STAT_WORLD_POS:
3516 e->world_pos = *event.hudchange.v3fdata;
3520 e->size = *event.hudchange.v2s32data;
3524 delete event.hudchange.v3fdata;
3525 delete event.hudchange.v2fdata;
3526 delete event.hudchange.sdata;
3527 delete event.hudchange.v2s32data;
3528 } else if (event.type == CE_SET_SKY) {
3529 sky->setVisible(false);
3536 // Handle according to type
3537 if (*event.set_sky.type == "regular") {
3538 sky->setVisible(true);
3539 } else if (*event.set_sky.type == "skybox" &&
3540 event.set_sky.params->size() == 6) {
3541 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3542 skybox = smgr->addSkyBoxSceneNode(
3543 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3544 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3545 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3546 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3547 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3548 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3550 // Handle everything else as plain color
3552 if (*event.set_sky.type != "plain")
3553 infostream << "Unknown sky type: "
3554 << (*event.set_sky.type) << std::endl;
3556 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3559 delete event.set_sky.bgcolor;
3560 delete event.set_sky.type;
3561 delete event.set_sky.params;
3562 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3563 bool enable = event.override_day_night_ratio.do_override;
3564 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3565 client->getEnv().setDayNightRatioOverride(enable, value);
3571 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3572 f32 dtime, float time_from_last_punch)
3574 LocalPlayer *player = client->getEnv().getLocalPlayer();
3577 For interaction purposes, get info about the held item
3579 - Is it a usable item?
3580 - Can it point to liquids?
3582 ItemStack playeritem;
3584 InventoryList *mlist = local_inventory->getList("main");
3586 if (mlist && client->getPlayerItem() < mlist->getSize())
3587 playeritem = mlist->getItem(client->getPlayerItem());
3590 ToolCapabilities playeritem_toolcap =
3591 playeritem.getToolCapabilities(itemdef_manager);
3593 v3s16 old_camera_offset = camera->getOffset();
3595 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3596 GenericCAO *playercao = player->getCAO();
3598 // If playercao not loaded, don't change camera
3599 if (playercao == NULL)
3602 camera->toggleCameraMode();
3604 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3605 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3608 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3609 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3611 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3612 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3614 camera->step(dtime);
3616 v3f camera_position = camera->getPosition();
3617 v3f camera_direction = camera->getDirection();
3618 f32 camera_fov = camera->getFovMax();
3619 v3s16 camera_offset = camera->getOffset();
3621 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3623 if (!flags->disable_camera_update) {
3624 client->getEnv().getClientMap().updateCamera(camera_position,
3625 camera_direction, camera_fov, camera_offset);
3627 if (flags->camera_offset_changed) {
3628 client->updateCameraOffset(camera_offset);
3629 client->getEnv().updateCameraOffset(camera_offset);
3632 clouds->updateCameraOffset(camera_offset);
3638 void Game::updateSound(f32 dtime)
3640 // Update sound listener
3641 v3s16 camera_offset = camera->getOffset();
3642 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3643 v3f(0, 0, 0), // velocity
3644 camera->getDirection(),
3645 camera->getCameraNode()->getUpVector());
3646 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3649 // Update sound maker
3650 soundmaker->step(dtime);
3652 LocalPlayer *player = client->getEnv().getLocalPlayer();
3654 ClientMap &map = client->getEnv().getClientMap();
3655 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3656 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3660 void Game::processPlayerInteraction(GameRunData *runData,
3661 f32 dtime, bool show_hud, bool show_debug)
3663 LocalPlayer *player = client->getEnv().getLocalPlayer();
3665 ItemStack playeritem;
3667 InventoryList *mlist = local_inventory->getList("main");
3669 if (mlist && client->getPlayerItem() < mlist->getSize())
3670 playeritem = mlist->getItem(client->getPlayerItem());
3673 const ItemDefinition &playeritem_def =
3674 playeritem.getDefinition(itemdef_manager);
3676 v3f player_position = player->getPosition();
3677 v3f camera_position = camera->getPosition();
3678 v3f camera_direction = camera->getDirection();
3679 v3s16 camera_offset = camera->getOffset();
3683 Calculate what block is the crosshair pointing to
3686 f32 d = playeritem_def.range; // max. distance
3687 f32 d_hand = itemdef_manager->get("").range;
3689 if (d < 0 && d_hand >= 0)
3694 core::line3d<f32> shootline;
3696 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3698 shootline = core::line3d<f32>(camera_position,
3699 camera_position + camera_direction * BS * (d + 1));
3702 // prevent player pointing anything in front-view
3703 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3704 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3707 #ifdef HAVE_TOUCHSCREENGUI
3709 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3710 shootline = g_touchscreengui->getShootline();
3711 shootline.start += intToFloat(camera_offset, BS);
3712 shootline.end += intToFloat(camera_offset, BS);
3717 PointedThing pointed = getPointedThing(
3719 client, hud, player_position, camera_direction,
3720 camera_position, shootline, d,
3721 playeritem_def.liquids_pointable,
3722 !runData->ldown_for_dig,
3725 runData->selected_object);
3727 if (pointed != runData->pointed_old) {
3728 infostream << "Pointing at " << pointed.dump() << std::endl;
3729 hud->updateSelectionMesh(camera_offset);
3734 - releasing left mouse button
3735 - pointing away from node
3737 if (runData->digging) {
3738 if (getLeftReleased()) {
3739 infostream << "Left button released"
3740 << " (stopped digging)" << std::endl;
3741 runData->digging = false;
3742 } else if (pointed != runData->pointed_old) {
3743 if (pointed.type == POINTEDTHING_NODE
3744 && runData->pointed_old.type == POINTEDTHING_NODE
3745 && pointed.node_undersurface
3746 == runData->pointed_old.node_undersurface) {
3747 // Still pointing to the same node, but a different face.
3750 infostream << "Pointing away from node"
3751 << " (stopped digging)" << std::endl;
3752 runData->digging = false;
3753 hud->updateSelectionMesh(camera_offset);
3757 if (!runData->digging) {
3758 client->interact(1, runData->pointed_old);
3759 client->setCrack(-1, v3s16(0, 0, 0));
3760 runData->dig_time = 0.0;
3764 if (!runData->digging && runData->ldown_for_dig && !isLeftPressed()) {
3765 runData->ldown_for_dig = false;
3768 runData->left_punch = false;
3770 soundmaker->m_player_leftpunch_sound.name = "";
3772 if (isRightPressed())
3773 runData->repeat_rightclick_timer += dtime;
3775 runData->repeat_rightclick_timer = 0;
3777 if (playeritem_def.usable && isLeftPressed()) {
3778 if (getLeftClicked())
3779 client->interact(4, pointed);
3780 } else if (pointed.type == POINTEDTHING_NODE) {
3781 ToolCapabilities playeritem_toolcap =
3782 playeritem.getToolCapabilities(itemdef_manager);
3783 handlePointingAtNode(runData, pointed, playeritem_def,
3784 playeritem_toolcap, dtime);
3785 } else if (pointed.type == POINTEDTHING_OBJECT) {
3786 handlePointingAtObject(runData, pointed, playeritem,
3787 player_position, show_debug);
3788 } else if (isLeftPressed()) {
3789 // When button is held down in air, show continuous animation
3790 runData->left_punch = true;
3791 } else if (getRightClicked()) {
3792 handlePointingAtNothing(runData, playeritem);
3795 runData->pointed_old = pointed;
3797 if (runData->left_punch || getLeftClicked())
3798 camera->setDigging(0); // left click animation
3800 input->resetLeftClicked();
3801 input->resetRightClicked();
3803 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3804 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3806 input->resetLeftReleased();
3807 input->resetRightReleased();
3809 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3810 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3814 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3816 infostream << "Right Clicked in Air" << std::endl;
3817 PointedThing fauxPointed;
3818 fauxPointed.type = POINTEDTHING_NOTHING;
3819 client->interact(5, fauxPointed);
3823 void Game::handlePointingAtNode(GameRunData *runData,
3824 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3825 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3827 v3s16 nodepos = pointed.node_undersurface;
3828 v3s16 neighbourpos = pointed.node_abovesurface;
3831 Check information text of node
3834 ClientMap &map = client->getEnv().getClientMap();
3835 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3838 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3840 MapNode n = map.getNodeNoEx(nodepos);
3842 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3843 infotext = L"Unknown node: ";
3844 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3848 if (runData->nodig_delay_timer <= 0.0 && isLeftPressed()
3849 && client->checkPrivilege("interact")) {
3850 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3853 if ((getRightClicked() ||
3854 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3855 client->checkPrivilege("interact")) {
3856 runData->repeat_rightclick_timer = 0;
3857 infostream << "Ground right-clicked" << std::endl;
3859 if (meta && meta->getString("formspec") != "" && !random_input
3860 && !isKeyDown(KeyType::SNEAK)) {
3861 infostream << "Launching custom inventory view" << std::endl;
3863 InventoryLocation inventoryloc;
3864 inventoryloc.setNodeMeta(nodepos);
3866 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3867 &client->getEnv().getClientMap(), nodepos);
3868 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3870 create_formspec_menu(¤t_formspec, client, gamedef,
3871 texture_src, device, &input->joystick, fs_src, txt_dst, client);
3873 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3875 // Report right click to server
3877 camera->setDigging(1); // right click animation (always shown for feedback)
3879 // If the wielded item has node placement prediction,
3881 bool placed = nodePlacementPrediction(*client,
3883 nodepos, neighbourpos);
3887 client->interact(3, pointed);
3889 soundmaker->m_player_rightpunch_sound =
3890 playeritem_def.sound_place;
3892 soundmaker->m_player_rightpunch_sound =
3895 if (playeritem_def.node_placement_prediction == "" ||
3896 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3897 client->interact(3, pointed); // Report to server
3899 soundmaker->m_player_rightpunch_sound =
3900 playeritem_def.sound_place_failed;
3908 void Game::handlePointingAtObject(GameRunData *runData,
3909 const PointedThing &pointed,
3910 const ItemStack &playeritem,
3911 const v3f &player_position,
3914 infotext = unescape_enriched(
3915 utf8_to_wide(runData->selected_object->infoText()));
3918 if (infotext != L"") {
3921 infotext += unescape_enriched(utf8_to_wide(
3922 runData->selected_object->debugInfoText()));
3925 if (isLeftPressed()) {
3926 bool do_punch = false;
3927 bool do_punch_damage = false;
3929 if (runData->object_hit_delay_timer <= 0.0) {
3931 do_punch_damage = true;
3932 runData->object_hit_delay_timer = object_hit_delay;
3935 if (getLeftClicked())
3939 infostream << "Left-clicked object" << std::endl;
3940 runData->left_punch = true;
3943 if (do_punch_damage) {
3944 // Report direct punch
3945 v3f objpos = runData->selected_object->getPosition();
3946 v3f dir = (objpos - player_position).normalize();
3948 bool disable_send = runData->selected_object->directReportPunch(
3949 dir, &playeritem, runData->time_from_last_punch);
3950 runData->time_from_last_punch = 0;
3953 client->interact(0, pointed);
3955 } else if (getRightClicked()) {
3956 infostream << "Right-clicked object" << std::endl;
3957 client->interact(3, pointed); // place
3962 void Game::handleDigging(GameRunData *runData,
3963 const PointedThing &pointed, const v3s16 &nodepos,
3964 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3966 if (!runData->digging) {
3967 infostream << "Started digging" << std::endl;
3968 client->interact(0, pointed);
3969 runData->digging = true;
3970 runData->ldown_for_dig = true;
3973 LocalPlayer *player = client->getEnv().getLocalPlayer();
3974 ClientMap &map = client->getEnv().getClientMap();
3975 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3977 // NOTE: Similar piece of code exists on the server side for
3979 // Get digging parameters
3980 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3981 &playeritem_toolcap);
3983 // If can't dig, try hand
3984 if (!params.diggable) {
3985 const ItemDefinition &hand = itemdef_manager->get("");
3986 const ToolCapabilities *tp = hand.tool_capabilities;
3989 params = getDigParams(nodedef_manager->get(n).groups, tp);
3992 if (params.diggable == false) {
3993 // I guess nobody will wait for this long
3994 runData->dig_time_complete = 10000000.0;
3996 runData->dig_time_complete = params.time;
3998 if (m_cache_enable_particles) {
3999 const ContentFeatures &features =
4000 client->getNodeDefManager()->get(n);
4001 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
4002 player, nodepos, features.tiles);
4006 if (runData->dig_time_complete >= 0.001) {
4007 runData->dig_index = (float)crack_animation_length
4009 / runData->dig_time_complete;
4011 // This is for torches
4012 runData->dig_index = crack_animation_length;
4015 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
4017 if (sound_dig.exists() && params.diggable) {
4018 if (sound_dig.name == "__group") {
4019 if (params.main_group != "") {
4020 soundmaker->m_player_leftpunch_sound.gain = 0.5;
4021 soundmaker->m_player_leftpunch_sound.name =
4022 std::string("default_dig_") +
4026 soundmaker->m_player_leftpunch_sound = sound_dig;
4030 // Don't show cracks if not diggable
4031 if (runData->dig_time_complete >= 100000.0) {
4032 } else if (runData->dig_index < crack_animation_length) {
4033 //TimeTaker timer("client.setTempMod");
4034 //infostream<<"dig_index="<<dig_index<<std::endl;
4035 client->setCrack(runData->dig_index, nodepos);
4037 infostream << "Digging completed" << std::endl;
4038 client->interact(2, pointed);
4039 client->setCrack(-1, v3s16(0, 0, 0));
4040 bool is_valid_position;
4041 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4042 if (is_valid_position)
4043 client->removeNode(nodepos);
4045 if (m_cache_enable_particles) {
4046 const ContentFeatures &features =
4047 client->getNodeDefManager()->get(wasnode);
4048 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
4049 player, nodepos, features.tiles);
4052 runData->dig_time = 0;
4053 runData->digging = false;
4055 runData->nodig_delay_timer =
4056 runData->dig_time_complete / (float)crack_animation_length;
4058 // We don't want a corresponding delay to
4059 // very time consuming nodes
4060 if (runData->nodig_delay_timer > 0.3)
4061 runData->nodig_delay_timer = 0.3;
4063 // We want a slight delay to very little
4064 // time consuming nodes
4065 const float mindelay = 0.15;
4067 if (runData->nodig_delay_timer < mindelay)
4068 runData->nodig_delay_timer = mindelay;
4070 // Send event to trigger sound
4071 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4072 gamedef->event()->put(e);
4075 if (runData->dig_time_complete < 100000.0) {
4076 runData->dig_time += dtime;
4078 runData->dig_time = 0;
4079 client->setCrack(-1, nodepos);
4082 camera->setDigging(0); // left click animation
4086 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
4087 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
4088 const CameraOrientation &cam)
4090 LocalPlayer *player = client->getEnv().getLocalPlayer();
4096 if (draw_control->range_all) {
4097 runData->fog_range = 100000 * BS;
4099 runData->fog_range = 0.9 * draw_control->wanted_range * BS;
4103 Calculate general brightness
4105 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4106 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4107 float direct_brightness;
4110 if (m_cache_enable_noclip && m_cache_enable_free_move) {
4111 direct_brightness = time_brightness;
4112 sunlight_seen = true;
4114 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4115 float old_brightness = sky->getBrightness();
4116 direct_brightness = client->getEnv().getClientMap()
4117 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
4118 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4122 float time_of_day = runData->time_of_day;
4123 float time_of_day_smooth = runData->time_of_day_smooth;
4125 time_of_day = client->getEnv().getTimeOfDayF();
4127 const float maxsm = 0.05;
4128 const float todsm = 0.05;
4130 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4131 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4132 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4133 time_of_day_smooth = time_of_day;
4135 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4136 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4137 + (time_of_day + 1.0) * todsm;
4139 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4140 + time_of_day * todsm;
4142 runData->time_of_day = time_of_day;
4143 runData->time_of_day_smooth = time_of_day_smooth;
4145 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4146 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4147 player->getPitch());
4153 v3f player_position = player->getPosition();
4154 if (sky->getCloudsVisible()) {
4155 clouds->setVisible(true);
4156 clouds->step(dtime);
4157 clouds->update(v2f(player_position.X, player_position.Z),
4158 sky->getCloudColor());
4160 clouds->setVisible(false);
4167 client->getParticleManager()->step(dtime);
4173 if (m_cache_enable_fog && !flags.force_fog_off) {
4176 video::EFT_FOG_LINEAR,
4177 runData->fog_range * 0.4,
4178 runData->fog_range * 1.0,
4186 video::EFT_FOG_LINEAR,
4196 Get chat messages from client
4199 v2u32 screensize = driver->getScreenSize();
4201 updateChat(*client, dtime, flags.show_debug, screensize,
4202 flags.show_chat, runData->profiler_current_page,
4203 *chat_backend, guitext_chat);
4209 if (client->getPlayerItem() != runData->new_playeritem)
4210 client->selectPlayerItem(runData->new_playeritem);
4212 // Update local inventory if it has changed
4213 if (client->getLocalInventoryUpdated()) {
4214 //infostream<<"Updating local inventory"<<std::endl;
4215 client->getLocalInventory(*local_inventory);
4216 runData->update_wielded_item_trigger = true;
4219 if (runData->update_wielded_item_trigger) {
4220 // Update wielded tool
4221 InventoryList *mlist = local_inventory->getList("main");
4223 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4224 ItemStack item = mlist->getItem(client->getPlayerItem());
4225 camera->wield(item);
4227 runData->update_wielded_item_trigger = false;
4231 Update block draw list every 200ms or when camera direction has
4234 runData->update_draw_list_timer += dtime;
4236 v3f camera_direction = camera->getDirection();
4237 if (runData->update_draw_list_timer >= 0.2
4238 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4239 || flags.camera_offset_changed) {
4240 runData->update_draw_list_timer = 0;
4241 client->getEnv().getClientMap().updateDrawList(driver);
4242 runData->update_draw_list_last_cam_dir = camera_direction;
4245 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4248 make sure menu is on top
4249 1. Delete formspec menu reference if menu was removed
4250 2. Else, make sure formspec menu is on top
4252 if (current_formspec) {
4253 if (current_formspec->getReferenceCount() == 1) {
4254 current_formspec->drop();
4255 current_formspec = NULL;
4256 } else if (!noMenuActive()) {
4257 guiroot->bringToFront(current_formspec);
4265 video::SColor skycolor = sky->getSkyColor();
4267 TimeTaker tt_draw("mainloop: draw");
4269 TimeTaker timer("beginScene");
4270 driver->beginScene(true, true, skycolor);
4271 stats->beginscenetime = timer.stop(true);
4274 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4275 guienv, screensize, skycolor, flags.show_hud,
4276 flags.show_minimap);
4281 if (flags.show_profiler_graph)
4282 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4287 if (runData->damage_flash > 0.0) {
4288 video::SColor color(runData->damage_flash, 180, 0, 0);
4289 driver->draw2DRectangle(color,
4290 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4293 runData->damage_flash -= 100.0 * dtime;
4299 if (player->hurt_tilt_timer > 0.0) {
4300 player->hurt_tilt_timer -= dtime * 5;
4302 if (player->hurt_tilt_timer < 0)
4303 player->hurt_tilt_strength = 0;
4307 Update minimap pos and rotation
4309 if (flags.show_minimap && flags.show_hud) {
4310 mapper->setPos(floatToInt(player->getPosition(), BS));
4311 mapper->setAngle(player->getYaw());
4318 TimeTaker timer("endScene");
4320 stats->endscenetime = timer.stop(true);
4323 stats->drawtime = tt_draw.stop(true);
4324 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4328 inline static const char *yawToDirectionString(int yaw)
4330 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4332 yaw = wrapDegrees_0_360(yaw);
4333 yaw = (yaw + 45) % 360 / 90;
4335 return direction[yaw];
4339 void Game::updateGui(float *statustext_time, const RunStats &stats,
4340 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4341 const CameraOrientation &cam)
4343 v2u32 screensize = driver->getScreenSize();
4344 LocalPlayer *player = client->getEnv().getLocalPlayer();
4345 v3f player_position = player->getPosition();
4347 if (flags.show_debug) {
4348 static float drawtime_avg = 0;
4349 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4351 u16 fps = 1.0 / stats.dtime_jitter.avg;
4352 //s32 fps = driver->getFPS();
4354 std::ostringstream os(std::ios_base::binary);
4356 << PROJECT_NAME_C " " << g_version_hash
4358 << " (R: range_all=" << draw_control->range_all << ")"
4359 << std::setprecision(0)
4360 << " drawtime = " << drawtime_avg
4361 << std::setprecision(1)
4362 << ", dtime_jitter = "
4363 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4364 << std::setprecision(1)
4365 << ", v_range = " << draw_control->wanted_range
4366 << std::setprecision(3)
4367 << ", RTT = " << client->getRTT();
4368 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4369 guitext->setVisible(true);
4371 guitext->setVisible(false);
4374 if (guitext->isVisible()) {
4375 core::rect<s32> rect(
4377 screensize.X, 5 + g_fontengine->getTextHeight()
4379 guitext->setRelativePosition(rect);
4382 if (flags.show_debug) {
4383 std::ostringstream os(std::ios_base::binary);
4384 os << std::setprecision(1) << std::fixed
4385 << "(" << (player_position.X / BS)
4386 << ", " << (player_position.Y / BS)
4387 << ", " << (player_position.Z / BS)
4388 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4389 << " " << yawToDirectionString(cam.camera_yaw)
4390 << ") (seed = " << ((u64)client->getMapSeed())
4393 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4394 ClientMap &map = client->getEnv().getClientMap();
4395 const INodeDefManager *nodedef = client->getNodeDefManager();
4396 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4397 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4398 const ContentFeatures &features = nodedef->get(n);
4399 os << " (pointing_at = " << nodedef->get(n).name
4400 << " - " << features.tiledef[0].name.c_str()
4405 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4406 guitext2->setVisible(true);
4408 core::rect<s32> rect(
4409 5, 5 + g_fontengine->getTextHeight(),
4410 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4412 guitext2->setRelativePosition(rect);
4414 guitext2->setVisible(false);
4417 setStaticText(guitext_info, infotext.c_str());
4418 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4420 float statustext_time_max = 1.5;
4422 if (!statustext.empty()) {
4423 *statustext_time += dtime;
4425 if (*statustext_time >= statustext_time_max) {
4427 *statustext_time = 0;
4431 setStaticText(guitext_status, statustext.c_str());
4432 guitext_status->setVisible(!statustext.empty());
4434 if (!statustext.empty()) {
4435 s32 status_width = guitext_status->getTextWidth();
4436 s32 status_height = guitext_status->getTextHeight();
4437 s32 status_y = screensize.Y - 150;
4438 s32 status_x = (screensize.X - status_width) / 2;
4439 core::rect<s32> rect(
4440 status_x , status_y - status_height,
4441 status_x + status_width, status_y
4443 guitext_status->setRelativePosition(rect);
4446 video::SColor initial_color(255, 0, 0, 0);
4448 if (guienv->getSkin())
4449 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4451 video::SColor final_color = initial_color;
4452 final_color.setAlpha(0);
4453 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4454 initial_color, final_color,
4455 pow(*statustext_time / statustext_time_max, 2.0f));
4456 guitext_status->setOverrideColor(fade_color);
4457 guitext_status->enableOverrideColor(true);
4462 /* Log times and stuff for visualization */
4463 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4465 Profiler::GraphValues values;
4466 g_profiler->graphGet(values);
4472 /****************************************************************************
4474 ****************************************************************************/
4476 /* On some computers framerate doesn't seem to be automatically limited
4478 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4480 // not using getRealTime is necessary for wine
4481 device->getTimer()->tick(); // Maker sure device time is up-to-date
4482 u32 time = device->getTimer()->getTime();
4483 u32 last_time = fps_timings->last_time;
4485 if (time > last_time) // Make sure time hasn't overflowed
4486 fps_timings->busy_time = time - last_time;
4488 fps_timings->busy_time = 0;
4490 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4491 ? g_settings->getFloat("pause_fps_max")
4492 : g_settings->getFloat("fps_max"));
4494 if (fps_timings->busy_time < frametime_min) {
4495 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4496 device->sleep(fps_timings->sleep_time);
4498 fps_timings->sleep_time = 0;
4501 /* Get the new value of the device timer. Note that device->sleep() may
4502 * not sleep for the entire requested time as sleep may be interrupted and
4503 * therefore it is arguably more accurate to get the new time from the
4504 * device rather than calculating it by adding sleep_time to time.
4507 device->getTimer()->tick(); // Update device timer
4508 time = device->getTimer()->getTime();
4510 if (time > last_time) // Make sure last_time hasn't overflowed
4511 *dtime = (time - last_time) / 1000.0;
4515 fps_timings->last_time = time;
4518 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4519 // pass a copy of it to this function
4520 // Note: \p msg must be allocated using new (not malloc())
4521 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4522 int percent, bool draw_clouds)
4524 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4528 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4530 ((Game *)data)->readSettings();
4533 void Game::readSettings()
4535 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4536 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4537 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4538 m_cache_enable_particles = g_settings->getBool("enable_particles");
4539 m_cache_enable_fog = g_settings->getBool("enable_fog");
4540 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4541 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4542 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4544 m_cache_enable_noclip = g_settings->getBool("noclip");
4545 m_cache_enable_free_move = g_settings->getBool("free_move");
4547 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4550 /****************************************************************************/
4551 /****************************************************************************
4553 ****************************************************************************/
4554 /****************************************************************************/
4556 void Game::extendedResourceCleanup()
4558 // Extended resource accounting
4559 infostream << "Irrlicht resources after cleanup:" << std::endl;
4560 infostream << "\tRemaining meshes : "
4561 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4562 infostream << "\tRemaining textures : "
4563 << driver->getTextureCount() << std::endl;
4565 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4566 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4567 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4571 clearTextureNameCache();
4572 infostream << "\tRemaining materials: "
4573 << driver-> getMaterialRendererCount()
4574 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4578 /****************************************************************************/
4579 /****************************************************************************
4580 extern function for launching the game
4581 ****************************************************************************/
4582 /****************************************************************************/
4584 void the_game(bool *kill,
4586 InputHandler *input,
4587 IrrlichtDevice *device,
4589 const std::string &map_dir,
4590 const std::string &playername,
4591 const std::string &password,
4592 const std::string &address, // If empty local server is created
4595 std::string &error_message,
4596 ChatBackend &chat_backend,
4597 bool *reconnect_requested,
4598 const SubgameSpec &gamespec, // Used for local game
4599 bool simple_singleplayer_mode)
4603 /* Make a copy of the server address because if a local singleplayer server
4604 * is created then this is updated and we don't want to change the value
4605 * passed to us by the calling function
4607 std::string server_address = address;
4611 if (game.startup(kill, random_input, input, device, map_dir,
4612 playername, password, &server_address, port, error_message,
4613 reconnect_requested, &chat_backend, gamespec,
4614 simple_singleplayer_mode)) {
4619 } catch (SerializationError &e) {
4620 error_message = std::string("A serialization error occurred:\n")
4621 + e.what() + "\n\nThe server is probably "
4622 " running a different version of " PROJECT_NAME_C ".";
4623 errorstream << error_message << std::endl;
4624 } catch (ServerError &e) {
4625 error_message = e.what();
4626 errorstream << "ServerError: " << error_message << std::endl;
4627 } catch (ModError &e) {
4628 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4629 errorstream << "ModError: " << error_message << std::endl;