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 + "testsounds";
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 f32 m_cache_mouse_sensitivity;
1745 f32 m_cache_joystick_frustum_sensitivity;
1746 f32 m_repeat_right_click_time;
1749 bool m_cache_hold_aux1;
1750 bool m_android_chat_open;
1759 itemdef_manager(NULL),
1760 nodedef_manager(NULL),
1762 sound_is_dummy(false),
1765 current_formspec(NULL),
1768 gui_chat_console(NULL),
1773 local_inventory(NULL),
1777 g_settings->registerChangedCallback("doubletap_jump",
1778 &settingChangedCallback, this);
1779 g_settings->registerChangedCallback("enable_clouds",
1780 &settingChangedCallback, this);
1781 g_settings->registerChangedCallback("doubletap_joysticks",
1782 &settingChangedCallback, this);
1783 g_settings->registerChangedCallback("enable_particles",
1784 &settingChangedCallback, this);
1785 g_settings->registerChangedCallback("enable_fog",
1786 &settingChangedCallback, this);
1787 g_settings->registerChangedCallback("mouse_sensitivity",
1788 &settingChangedCallback, this);
1789 g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1790 &settingChangedCallback, this);
1791 g_settings->registerChangedCallback("repeat_rightclick_time",
1792 &settingChangedCallback, this);
1797 m_cache_hold_aux1 = false; // This is initialised properly later
1804 /****************************************************************************
1806 ****************************************************************************/
1812 if (!sound_is_dummy)
1815 delete server; // deleted first to stop all server threads
1818 delete local_inventory;
1824 delete nodedef_manager;
1825 delete itemdef_manager;
1826 delete draw_control;
1828 extendedResourceCleanup();
1830 g_settings->deregisterChangedCallback("doubletap_jump",
1831 &settingChangedCallback, this);
1832 g_settings->deregisterChangedCallback("enable_clouds",
1833 &settingChangedCallback, this);
1834 g_settings->deregisterChangedCallback("enable_particles",
1835 &settingChangedCallback, this);
1836 g_settings->deregisterChangedCallback("enable_fog",
1837 &settingChangedCallback, this);
1838 g_settings->deregisterChangedCallback("mouse_sensitivity",
1839 &settingChangedCallback, this);
1840 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1841 &settingChangedCallback, this);
1844 bool Game::startup(bool *kill,
1846 InputHandler *input,
1847 IrrlichtDevice *device,
1848 const std::string &map_dir,
1849 const std::string &playername,
1850 const std::string &password,
1851 std::string *address, // can change if simple_singleplayer_mode
1853 std::string &error_message,
1855 ChatBackend *chat_backend,
1856 const SubgameSpec &gamespec,
1857 bool simple_singleplayer_mode)
1860 this->device = device;
1862 this->error_message = &error_message;
1863 this->reconnect_requested = reconnect;
1864 this->random_input = random_input;
1865 this->input = input;
1866 this->chat_backend = chat_backend;
1867 this->simple_singleplayer_mode = simple_singleplayer_mode;
1869 keycache.handler = input;
1870 keycache.populate();
1872 driver = device->getVideoDriver();
1873 smgr = device->getSceneManager();
1875 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1877 if (!init(map_dir, address, port, gamespec))
1880 if (!createClient(playername, password, address, port))
1889 ProfilerGraph graph;
1890 RunStats stats = { 0 };
1891 CameraOrientation cam_view_target = { 0 };
1892 CameraOrientation cam_view = { 0 };
1893 GameRunData runData = { 0 };
1894 FpsControl draw_times = { 0 };
1895 VolatileRunFlags flags = { 0 };
1896 f32 dtime; // in seconds
1898 runData.time_from_last_punch = 10.0;
1899 runData.profiler_max_page = 3;
1900 runData.update_wielded_item_trigger = true;
1902 flags.show_chat = true;
1903 flags.show_hud = true;
1904 flags.show_minimap = g_settings->getBool("enable_minimap");
1905 flags.show_debug = g_settings->getBool("show_debug");
1906 flags.invert_mouse = g_settings->getBool("invert_mouse");
1907 flags.first_loop_after_window_activation = true;
1909 /* Clear the profiler */
1910 Profiler::GraphValues dummyvalues;
1911 g_profiler->graphGet(dummyvalues);
1913 draw_times.last_time = device->getTimer()->getTime();
1915 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1917 &flags.force_fog_off,
1921 set_light_table(g_settings->getFloat("display_gamma"));
1924 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1925 && client->checkPrivilege("fast");
1928 while (device->run()
1929 && !(*kill || g_gamecallback->shutdown_requested
1930 || (server && server->getShutdownRequested()))) {
1932 /* Must be called immediately after a device->run() call because it
1933 * uses device->getTimer()->getTime()
1935 limitFps(&draw_times, &dtime);
1937 updateStats(&stats, draw_times, dtime);
1938 updateInteractTimers(&runData, dtime);
1940 if (!checkConnection())
1942 if (!handleCallbacks())
1948 hud->resizeHotbar();
1950 updateProfilers(runData, stats, draw_times, dtime);
1951 processUserInput(&flags, &runData, dtime);
1952 // Update camera before player movement to avoid camera lag of one frame
1953 updateCameraDirection(&cam_view_target, &flags, dtime);
1954 float cam_smoothing = 0;
1955 if (g_settings->getBool("cinematic"))
1956 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1958 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1959 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1960 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1961 cam_view.camera_yaw) * cam_smoothing;
1962 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1963 cam_view.camera_pitch) * cam_smoothing;
1964 updatePlayerControl(cam_view);
1966 processClientEvents(&cam_view_target, &runData.damage_flash);
1967 updateCamera(&flags, draw_times.busy_time, dtime,
1968 runData.time_from_last_punch);
1970 processPlayerInteraction(&runData, dtime, flags.show_hud,
1972 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1973 updateProfilerGraphs(&graph);
1975 // Update if minimap has been disabled by the server
1976 flags.show_minimap &= !client->isMinimapDisabledByServer();
1981 void Game::shutdown()
1983 if (g_settings->get("3d_mode") == "pageflip") {
1984 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1987 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1992 if (gui_chat_console)
1993 gui_chat_console->drop();
1999 while (g_menumgr.menuCount() > 0) {
2000 g_menumgr.m_stack.front()->setVisible(false);
2001 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
2004 if (current_formspec) {
2005 current_formspec->drop();
2006 current_formspec = NULL;
2009 chat_backend->addMessage(L"", L"# Disconnected.");
2010 chat_backend->addMessage(L"", L"");
2014 while (!client->isShutdown()) {
2015 assert(texture_src != NULL);
2016 assert(shader_src != NULL);
2017 texture_src->processQueue();
2018 shader_src->processQueue();
2025 /****************************************************************************/
2026 /****************************************************************************
2028 ****************************************************************************/
2029 /****************************************************************************/
2032 const std::string &map_dir,
2033 std::string *address,
2035 const SubgameSpec &gamespec)
2037 showOverlayMessage(wgettext("Loading..."), 0, 0);
2039 texture_src = createTextureSource(device);
2040 shader_src = createShaderSource(device);
2042 itemdef_manager = createItemDefManager();
2043 nodedef_manager = createNodeDefManager();
2045 eventmgr = new EventManager();
2046 quicktune = new QuicktuneShortcutter();
2048 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
2049 && eventmgr && quicktune))
2055 // Create a server if not connecting to an existing one
2056 if (*address == "") {
2057 if (!createSingleplayerServer(map_dir, gamespec, port, address))
2064 bool Game::initSound()
2067 if (g_settings->getBool("enable_sound")) {
2068 infostream << "Attempting to use OpenAL audio" << std::endl;
2069 sound = createOpenALSoundManager(&soundfetcher);
2071 infostream << "Failed to initialize OpenAL audio" << std::endl;
2073 infostream << "Sound disabled." << std::endl;
2077 infostream << "Using dummy audio." << std::endl;
2078 sound = &dummySoundManager;
2079 sound_is_dummy = true;
2082 soundmaker = new SoundMaker(sound, nodedef_manager);
2086 soundmaker->registerReceiver(eventmgr);
2091 bool Game::createSingleplayerServer(const std::string map_dir,
2092 const SubgameSpec &gamespec, u16 port, std::string *address)
2094 showOverlayMessage(wgettext("Creating server..."), 0, 5);
2096 std::string bind_str = g_settings->get("bind_address");
2097 Address bind_addr(0, 0, 0, 0, port);
2099 if (g_settings->getBool("ipv6_server")) {
2100 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2104 bind_addr.Resolve(bind_str.c_str());
2105 } catch (ResolveError &e) {
2106 infostream << "Resolving bind address \"" << bind_str
2107 << "\" failed: " << e.what()
2108 << " -- Listening on all addresses." << std::endl;
2111 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2112 *error_message = "Unable to listen on " +
2113 bind_addr.serializeString() +
2114 " because IPv6 is disabled";
2115 errorstream << *error_message << std::endl;
2119 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2120 bind_addr.isIPv6());
2122 server->start(bind_addr);
2127 bool Game::createClient(const std::string &playername,
2128 const std::string &password, std::string *address, u16 port)
2130 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2132 draw_control = new MapDrawControl;
2136 bool could_connect, connect_aborted;
2138 if (!connectToServer(playername, password, address, port,
2139 &could_connect, &connect_aborted))
2142 if (!could_connect) {
2143 if (error_message->empty() && !connect_aborted) {
2144 // Should not happen if error messages are set properly
2145 *error_message = "Connection failed for unknown reason";
2146 errorstream << *error_message << std::endl;
2151 if (!getServerContent(&connect_aborted)) {
2152 if (error_message->empty() && !connect_aborted) {
2153 // Should not happen if error messages are set properly
2154 *error_message = "Connection failed for unknown reason";
2155 errorstream << *error_message << std::endl;
2160 // Update cached textures, meshes and materials
2161 client->afterContentReceived(device);
2165 camera = new Camera(smgr, *draw_control, gamedef);
2166 if (!camera || !camera->successfullyCreated(*error_message))
2168 client->setCamera(camera);
2172 if (m_cache_enable_clouds) {
2173 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2175 *error_message = "Memory allocation error (clouds)";
2176 errorstream << *error_message << std::endl;
2183 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2184 skybox = NULL; // This is used/set later on in the main run loop
2186 local_inventory = new Inventory(itemdef_manager);
2188 if (!(sky && local_inventory)) {
2189 *error_message = "Memory allocation error (sky or local inventory)";
2190 errorstream << *error_message << std::endl;
2194 /* Pre-calculated values
2196 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2198 v2u32 size = t->getOriginalSize();
2199 crack_animation_length = size.Y / size.X;
2201 crack_animation_length = 5;
2207 /* Set window caption
2209 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2211 str += utf8_to_wide(g_version_hash);
2213 str += driver->getName();
2215 device->setWindowCaption(str.c_str());
2217 LocalPlayer *player = client->getEnv().getLocalPlayer();
2218 player->hurt_tilt_timer = 0;
2219 player->hurt_tilt_strength = 0;
2221 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2224 *error_message = "Memory error: could not create HUD";
2225 errorstream << *error_message << std::endl;
2229 mapper = client->getMapper();
2230 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2235 bool Game::initGui()
2237 // First line of debug text
2238 guitext = addStaticText(guienv,
2239 utf8_to_wide(PROJECT_NAME_C).c_str(),
2240 core::rect<s32>(0, 0, 0, 0),
2241 false, false, guiroot);
2243 // Second line of debug text
2244 guitext2 = addStaticText(guienv,
2246 core::rect<s32>(0, 0, 0, 0),
2247 false, false, guiroot);
2249 // At the middle of the screen
2250 // Object infos are shown in this
2251 guitext_info = addStaticText(guienv,
2253 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2254 false, true, guiroot);
2256 // Status text (displays info when showing and hiding GUI stuff, etc.)
2257 guitext_status = addStaticText(guienv,
2259 core::rect<s32>(0, 0, 0, 0),
2260 false, false, guiroot);
2261 guitext_status->setVisible(false);
2264 guitext_chat = addStaticText(
2267 core::rect<s32>(0, 0, 0, 0),
2268 //false, false); // Disable word wrap as of now
2269 false, true, guiroot);
2271 // Remove stale "recent" chat messages from previous connections
2272 chat_backend->clearRecentChat();
2274 // Chat backend and console
2275 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2276 -1, chat_backend, client, &g_menumgr);
2277 if (!gui_chat_console) {
2278 *error_message = "Could not allocate memory for chat console";
2279 errorstream << *error_message << std::endl;
2283 // Profiler text (size is updated when text is updated)
2284 guitext_profiler = addStaticText(guienv,
2286 core::rect<s32>(0, 0, 0, 0),
2287 false, false, guiroot);
2288 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2289 guitext_profiler->setVisible(false);
2290 guitext_profiler->setWordWrap(true);
2292 #ifdef HAVE_TOUCHSCREENGUI
2294 if (g_touchscreengui)
2295 g_touchscreengui->init(texture_src);
2302 bool Game::connectToServer(const std::string &playername,
2303 const std::string &password, std::string *address, u16 port,
2304 bool *connect_ok, bool *aborted)
2306 *connect_ok = false; // Let's not be overly optimistic
2308 bool local_server_mode = false;
2310 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2312 Address connect_address(0, 0, 0, 0, port);
2315 connect_address.Resolve(address->c_str());
2317 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2318 //connect_address.Resolve("localhost");
2319 if (connect_address.isIPv6()) {
2320 IPv6AddressBytes addr_bytes;
2321 addr_bytes.bytes[15] = 1;
2322 connect_address.setAddress(&addr_bytes);
2324 connect_address.setAddress(127, 0, 0, 1);
2326 local_server_mode = true;
2328 } catch (ResolveError &e) {
2329 *error_message = std::string("Couldn't resolve address: ") + e.what();
2330 errorstream << *error_message << std::endl;
2334 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2335 *error_message = "Unable to connect to " +
2336 connect_address.serializeString() +
2337 " because IPv6 is disabled";
2338 errorstream << *error_message << std::endl;
2342 client = new Client(device,
2343 playername.c_str(), password,
2344 *draw_control, texture_src, shader_src,
2345 itemdef_manager, nodedef_manager, sound, eventmgr,
2346 connect_address.isIPv6());
2351 gamedef = client; // Client acts as our GameDef
2353 infostream << "Connecting to server at ";
2354 connect_address.print(&infostream);
2355 infostream << std::endl;
2357 client->connect(connect_address, *address,
2358 simple_singleplayer_mode || local_server_mode);
2361 Wait for server to accept connection
2367 FpsControl fps_control = { 0 };
2369 f32 wait_time = 0; // in seconds
2371 fps_control.last_time = device->getTimer()->getTime();
2373 while (device->run()) {
2375 limitFps(&fps_control, &dtime);
2377 // Update client and server
2378 client->step(dtime);
2381 server->step(dtime);
2384 if (client->getState() == LC_Init) {
2390 if (client->accessDenied()) {
2391 *error_message = "Access denied. Reason: "
2392 + client->accessDeniedReason();
2393 *reconnect_requested = client->reconnectRequested();
2394 errorstream << *error_message << std::endl;
2398 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2400 infostream << "Connect aborted [Escape]" << std::endl;
2405 // Only time out if we aren't waiting for the server we started
2406 if ((*address != "") && (wait_time > 10)) {
2407 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2408 // If no pre v25 init was sent, and no answer was received,
2409 // but the low level connection could be established
2410 // (meaning that we have a peer id), then we probably wanted
2411 // to connect to a legacy server. In this case, tell the user
2412 // to enable the option to be able to connect.
2413 if (!sent_old_init &&
2414 (client->getProtoVersion() == 0) &&
2415 client->connectedToServer()) {
2416 *error_message = "Connection failure: init packet not "
2417 "recognized by server.\n"
2418 "Most likely the server uses an old protocol version (<v25).\n"
2419 "Please ask the server owner to update to 0.4.13 or later.\n"
2420 "To still connect to the server in the meantime,\n"
2421 "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2422 "or by enabling the 'Client -> Network -> Support older Servers'\n"
2423 "entry in the advanced settings menu.";
2425 *error_message = "Connection timed out.";
2427 errorstream << *error_message << std::endl;
2432 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2434 } catch (con::PeerNotFoundException &e) {
2435 // TODO: Should something be done here? At least an info/error
2443 bool Game::getServerContent(bool *aborted)
2447 FpsControl fps_control = { 0 };
2448 f32 dtime; // in seconds
2450 fps_control.last_time = device->getTimer()->getTime();
2452 while (device->run()) {
2454 limitFps(&fps_control, &dtime);
2456 // Update client and server
2457 client->step(dtime);
2460 server->step(dtime);
2463 if (client->mediaReceived() && client->itemdefReceived() &&
2464 client->nodedefReceived()) {
2469 if (!checkConnection())
2472 if (client->getState() < LC_Init) {
2473 *error_message = "Client disconnected";
2474 errorstream << *error_message << std::endl;
2478 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2480 infostream << "Connect aborted [Escape]" << std::endl;
2487 if (!client->itemdefReceived()) {
2488 const wchar_t *text = wgettext("Item definitions...");
2490 draw_load_screen(text, device, guienv, dtime, progress);
2492 } else if (!client->nodedefReceived()) {
2493 const wchar_t *text = wgettext("Node definitions...");
2495 draw_load_screen(text, device, guienv, dtime, progress);
2498 std::stringstream message;
2499 message.precision(3);
2500 message << gettext("Media...");
2502 if ((USE_CURL == 0) ||
2503 (!g_settings->getBool("enable_remote_media_server"))) {
2504 float cur = client->getCurRate();
2505 std::string cur_unit = gettext("KiB/s");
2509 cur_unit = gettext("MiB/s");
2512 message << " (" << cur << ' ' << cur_unit << ")";
2515 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2516 draw_load_screen(utf8_to_wide(message.str()), device,
2517 guienv, dtime, progress);
2525 /****************************************************************************/
2526 /****************************************************************************
2528 ****************************************************************************/
2529 /****************************************************************************/
2531 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2533 if (runData->nodig_delay_timer >= 0)
2534 runData->nodig_delay_timer -= dtime;
2536 if (runData->object_hit_delay_timer >= 0)
2537 runData->object_hit_delay_timer -= dtime;
2539 runData->time_from_last_punch += dtime;
2543 /* returns false if game should exit, otherwise true
2545 inline bool Game::checkConnection()
2547 if (client->accessDenied()) {
2548 *error_message = "Access denied. Reason: "
2549 + client->accessDeniedReason();
2550 *reconnect_requested = client->reconnectRequested();
2551 errorstream << *error_message << std::endl;
2559 /* returns false if game should exit, otherwise true
2561 inline bool Game::handleCallbacks()
2563 if (g_gamecallback->disconnect_requested) {
2564 g_gamecallback->disconnect_requested = false;
2568 if (g_gamecallback->changepassword_requested) {
2569 (new GUIPasswordChange(guienv, guiroot, -1,
2570 &g_menumgr, client))->drop();
2571 g_gamecallback->changepassword_requested = false;
2574 if (g_gamecallback->changevolume_requested) {
2575 (new GUIVolumeChange(guienv, guiroot, -1,
2576 &g_menumgr))->drop();
2577 g_gamecallback->changevolume_requested = false;
2580 if (g_gamecallback->keyconfig_requested) {
2581 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2582 &g_menumgr))->drop();
2583 g_gamecallback->keyconfig_requested = false;
2586 if (g_gamecallback->keyconfig_changed) {
2587 keycache.populate(); // update the cache with new settings
2588 g_gamecallback->keyconfig_changed = false;
2595 void Game::processQueues()
2597 texture_src->processQueue();
2598 itemdef_manager->processQueue(gamedef);
2599 shader_src->processQueue();
2603 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2604 const FpsControl &draw_times, f32 dtime)
2606 float profiler_print_interval =
2607 g_settings->getFloat("profiler_print_interval");
2608 bool print_to_log = true;
2610 if (profiler_print_interval == 0) {
2611 print_to_log = false;
2612 profiler_print_interval = 5;
2615 if (profiler_interval.step(dtime, profiler_print_interval)) {
2617 infostream << "Profiler:" << std::endl;
2618 g_profiler->print(infostream);
2621 update_profiler_gui(guitext_profiler, g_fontengine,
2622 runData.profiler_current_page, runData.profiler_max_page,
2623 driver->getScreenSize().Height);
2625 g_profiler->clear();
2628 addProfilerGraphs(stats, draw_times, dtime);
2632 void Game::addProfilerGraphs(const RunStats &stats,
2633 const FpsControl &draw_times, f32 dtime)
2635 g_profiler->graphAdd("mainloop_other",
2636 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2638 if (draw_times.sleep_time != 0)
2639 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2640 g_profiler->graphAdd("mainloop_dtime", dtime);
2642 g_profiler->add("Elapsed time", dtime);
2643 g_profiler->avg("FPS", 1. / dtime);
2647 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2654 /* Time average and jitter calculation
2656 jp = &stats->dtime_jitter;
2657 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2659 jitter = dtime - jp->avg;
2661 if (jitter > jp->max)
2664 jp->counter += dtime;
2666 if (jp->counter > 0.0) {
2668 jp->max_sample = jp->max;
2669 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2673 /* Busytime average and jitter calculation
2675 jp = &stats->busy_time_jitter;
2676 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2678 jitter = draw_times.busy_time - jp->avg;
2680 if (jitter > jp->max)
2682 if (jitter < jp->min)
2685 jp->counter += dtime;
2687 if (jp->counter > 0.0) {
2689 jp->max_sample = jp->max;
2690 jp->min_sample = jp->min;
2698 /****************************************************************************
2700 ****************************************************************************/
2702 void Game::processUserInput(VolatileRunFlags *flags,
2703 GameRunData *runData, f32 dtime)
2705 // Reset input if window not active or some menu is active
2706 if (device->isWindowActive() == false
2707 || noMenuActive() == false
2708 || guienv->hasFocus(gui_chat_console)) {
2710 #ifdef HAVE_TOUCHSCREENGUI
2711 g_touchscreengui->hide();
2714 #ifdef HAVE_TOUCHSCREENGUI
2715 else if (g_touchscreengui) {
2716 /* on touchscreengui step may generate own input events which ain't
2717 * what we want in case we just did clear them */
2718 g_touchscreengui->step(dtime);
2722 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2723 gui_chat_console->closeConsoleAtOnce();
2726 // Input handler step() (used by the random input generator)
2730 if (current_formspec != NULL)
2731 current_formspec->getAndroidUIInput();
2733 handleAndroidChatInput();
2736 // Increase timer for double tap of "keymap_jump"
2737 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2738 runData->jump_timer += dtime;
2742 &runData->statustext_time,
2743 &runData->jump_timer,
2744 &runData->reset_jump_timer,
2745 &runData->profiler_current_page,
2746 runData->profiler_max_page);
2748 processItemSelection(&runData->new_playeritem);
2752 void Game::processKeyInput(VolatileRunFlags *flags,
2753 float *statustext_time,
2755 bool *reset_jump_timer,
2756 u32 *profiler_current_page,
2757 u32 profiler_max_page)
2760 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2762 if (wasKeyDown(KeyType::DROP)) {
2764 } else if (wasKeyDown(KeyType::AUTORUN)) {
2765 toggleAutorun(statustext_time);
2766 } else if (wasKeyDown(KeyType::INVENTORY)) {
2768 } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2769 if (!gui_chat_console->isOpenInhibited()) {
2770 show_pause_menu(¤t_formspec, client, gamedef,
2771 texture_src, device, &input->joystick,
2772 simple_singleplayer_mode);
2774 } else if (wasKeyDown(KeyType::CHAT)) {
2775 openConsole(0.2, L"");
2776 } else if (wasKeyDown(KeyType::CMD)) {
2777 openConsole(0.2, L"/");
2778 } else if (wasKeyDown(KeyType::CONSOLE)) {
2780 } else if (wasKeyDown(KeyType::FREEMOVE)) {
2781 toggleFreeMove(statustext_time);
2782 } else if (wasKeyDown(KeyType::JUMP)) {
2783 toggleFreeMoveAlt(statustext_time, jump_timer);
2784 *reset_jump_timer = true;
2785 } else if (wasKeyDown(KeyType::FASTMOVE)) {
2786 toggleFast(statustext_time);
2787 } else if (wasKeyDown(KeyType::NOCLIP)) {
2788 toggleNoClip(statustext_time);
2789 } else if (wasKeyDown(KeyType::CINEMATIC)) {
2790 toggleCinematic(statustext_time);
2791 } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2792 client->makeScreenshot(device);
2793 } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2794 toggleHud(statustext_time, &flags->show_hud);
2795 } else if (wasKeyDown(KeyType::MINIMAP)) {
2796 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2797 isKeyDown(KeyType::SNEAK));
2798 } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2799 toggleChat(statustext_time, &flags->show_chat);
2800 } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2801 toggleFog(statustext_time, &flags->force_fog_off);
2802 } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2803 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2804 } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2805 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2806 } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2807 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2808 } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2809 increaseViewRange(statustext_time);
2810 } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2811 decreaseViewRange(statustext_time);
2812 } else if (wasKeyDown(KeyType::RANGESELECT)) {
2813 toggleFullViewRange(statustext_time);
2814 } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2816 } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2818 } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2820 } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2822 } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2823 // Print debug stacks
2824 dstream << "-----------------------------------------"
2826 dstream << "Printing debug stacks:" << std::endl;
2827 dstream << "-----------------------------------------"
2829 debug_stacks_print();
2832 if (!isKeyDown(KeyType::JUMP) && *reset_jump_timer) {
2833 *reset_jump_timer = false;
2839 if (quicktune->hasMessage()) {
2840 std::string msg = quicktune->getMessage();
2841 statustext = utf8_to_wide(msg);
2842 *statustext_time = 0;
2846 void Game::processItemSelection(u16 *new_playeritem)
2848 LocalPlayer *player = client->getEnv().getLocalPlayer();
2850 /* Item selection using mouse wheel
2852 *new_playeritem = client->getPlayerItem();
2854 s32 wheel = input->getMouseWheel();
2855 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2856 player->hud_hotbar_itemcount - 1);
2860 if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN)) {
2864 if (input->joystick.wasKeyDown(KeyType::SCROLL_UP)) {
2869 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2871 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2874 /* Item selection using keyboard
2876 for (u16 i = 0; i < 10; i++) {
2877 static const KeyPress *item_keys[10] = {
2878 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2879 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2880 NumberKey + 9, NumberKey + 0,
2883 if (input->wasKeyDown(*item_keys[i])) {
2884 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2885 *new_playeritem = i;
2886 infostream << "Selected item: " << new_playeritem << std::endl;
2894 void Game::dropSelectedItem()
2896 IDropAction *a = new IDropAction();
2898 a->from_inv.setCurrentPlayer();
2899 a->from_list = "main";
2900 a->from_i = client->getPlayerItem();
2901 client->inventoryAction(a);
2905 void Game::openInventory()
2908 * Don't permit to open inventory is CAO or player doesn't exists.
2909 * This prevent showing an empty inventory at player load
2912 LocalPlayer *player = client->getEnv().getLocalPlayer();
2913 if (player == NULL || player->getCAO() == NULL)
2916 infostream << "the_game: " << "Launching inventory" << std::endl;
2918 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2919 TextDest *txt_dst = new TextDestPlayerInventory(client);
2921 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2922 device, &input->joystick, fs_src, txt_dst, client);
2924 InventoryLocation inventoryloc;
2925 inventoryloc.setCurrentPlayer();
2926 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2930 void Game::openConsole(float height, const wchar_t *line)
2933 porting::showInputDialog(gettext("ok"), "", "", 2);
2934 m_android_chat_open = true;
2936 if (gui_chat_console->isOpenInhibited())
2938 gui_chat_console->openConsole(height);
2940 gui_chat_console->setCloseOnEnter(true);
2941 gui_chat_console->replaceAndAddToHistory(line);
2947 void Game::handleAndroidChatInput()
2949 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2950 std::string text = porting::getInputDialogValue();
2951 client->typeChatMessage(utf8_to_wide(text));
2957 void Game::toggleFreeMove(float *statustext_time)
2959 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2961 bool free_move = !g_settings->getBool("free_move");
2962 g_settings->set("free_move", bool_to_cstr(free_move));
2964 *statustext_time = 0;
2965 statustext = msg[free_move];
2966 if (free_move && !client->checkPrivilege("fly"))
2967 statustext += L" (note: no 'fly' privilege)";
2971 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2973 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2974 toggleFreeMove(statustext_time);
2978 void Game::toggleFast(float *statustext_time)
2980 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2981 bool fast_move = !g_settings->getBool("fast_move");
2982 g_settings->set("fast_move", bool_to_cstr(fast_move));
2984 *statustext_time = 0;
2985 statustext = msg[fast_move];
2987 bool has_fast_privs = client->checkPrivilege("fast");
2989 if (fast_move && !has_fast_privs)
2990 statustext += L" (note: no 'fast' privilege)";
2993 m_cache_hold_aux1 = fast_move && has_fast_privs;
2998 void Game::toggleNoClip(float *statustext_time)
3000 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
3001 bool noclip = !g_settings->getBool("noclip");
3002 g_settings->set("noclip", bool_to_cstr(noclip));
3004 *statustext_time = 0;
3005 statustext = msg[noclip];
3007 if (noclip && !client->checkPrivilege("noclip"))
3008 statustext += L" (note: no 'noclip' privilege)";
3011 void Game::toggleCinematic(float *statustext_time)
3013 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
3014 bool cinematic = !g_settings->getBool("cinematic");
3015 g_settings->set("cinematic", bool_to_cstr(cinematic));
3017 *statustext_time = 0;
3018 statustext = msg[cinematic];
3021 // Add WoW-style autorun by toggling continuous forward.
3022 void Game::toggleAutorun(float *statustext_time)
3024 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
3025 bool autorun_enabled = !g_settings->getBool("continuous_forward");
3026 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
3028 *statustext_time = 0;
3029 statustext = msg[autorun_enabled ? 1 : 0];
3032 void Game::toggleChat(float *statustext_time, bool *flag)
3034 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
3037 *statustext_time = 0;
3038 statustext = msg[*flag];
3042 void Game::toggleHud(float *statustext_time, bool *flag)
3044 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
3047 *statustext_time = 0;
3048 statustext = msg[*flag];
3051 void Game::toggleMinimap(float *statustext_time, bool *flag,
3052 bool show_hud, bool shift_pressed)
3054 if (!show_hud || !g_settings->getBool("enable_minimap"))
3057 if (shift_pressed) {
3058 mapper->toggleMinimapShape();
3062 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
3064 MinimapMode mode = MINIMAP_MODE_OFF;
3065 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
3066 mode = mapper->getMinimapMode();
3067 mode = (MinimapMode)((int)mode + 1);
3072 case MINIMAP_MODE_SURFACEx1:
3073 statustext = L"Minimap in surface mode, Zoom x1";
3075 case MINIMAP_MODE_SURFACEx2:
3076 statustext = L"Minimap in surface mode, Zoom x2";
3078 case MINIMAP_MODE_SURFACEx4:
3079 statustext = L"Minimap in surface mode, Zoom x4";
3081 case MINIMAP_MODE_RADARx1:
3082 statustext = L"Minimap in radar mode, Zoom x1";
3084 case MINIMAP_MODE_RADARx2:
3085 statustext = L"Minimap in radar mode, Zoom x2";
3087 case MINIMAP_MODE_RADARx4:
3088 statustext = L"Minimap in radar mode, Zoom x4";
3091 mode = MINIMAP_MODE_OFF;
3093 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
3094 L"Minimap hidden" : L"Minimap disabled by server";
3097 *statustext_time = 0;
3098 mapper->setMinimapMode(mode);
3101 void Game::toggleFog(float *statustext_time, bool *flag)
3103 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
3106 *statustext_time = 0;
3107 statustext = msg[*flag];
3111 void Game::toggleDebug(float *statustext_time, bool *show_debug,
3112 bool *show_profiler_graph)
3114 // Initial / 3x toggle: Chat only
3115 // 1x toggle: Debug text with chat
3116 // 2x toggle: Debug text with profiler graph
3119 *show_profiler_graph = false;
3120 statustext = L"Debug info shown";
3121 } else if (*show_profiler_graph) {
3122 *show_debug = false;
3123 *show_profiler_graph = false;
3124 statustext = L"Debug info and profiler graph hidden";
3126 *show_profiler_graph = true;
3127 statustext = L"Profiler graph shown";
3129 *statustext_time = 0;
3133 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3135 static const wchar_t *msg[] = {
3136 L"Camera update enabled",
3137 L"Camera update disabled"
3141 *statustext_time = 0;
3142 statustext = msg[*flag];
3146 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3147 u32 profiler_max_page)
3149 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3151 // FIXME: This updates the profiler with incomplete values
3152 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3153 profiler_max_page, driver->getScreenSize().Height);
3155 if (*profiler_current_page != 0) {
3156 std::wstringstream sstr;
3157 sstr << "Profiler shown (page " << *profiler_current_page
3158 << " of " << profiler_max_page << ")";
3159 statustext = sstr.str();
3161 statustext = L"Profiler hidden";
3163 *statustext_time = 0;
3167 void Game::increaseViewRange(float *statustext_time)
3169 s16 range = g_settings->getS16("viewing_range");
3170 s16 range_new = range + 10;
3171 g_settings->set("viewing_range", itos(range_new));
3172 statustext = utf8_to_wide("Viewing range changed to "
3174 *statustext_time = 0;
3178 void Game::decreaseViewRange(float *statustext_time)
3180 s16 range = g_settings->getS16("viewing_range");
3181 s16 range_new = range - 10;
3186 g_settings->set("viewing_range", itos(range_new));
3187 statustext = utf8_to_wide("Viewing range changed to "
3189 *statustext_time = 0;
3193 void Game::toggleFullViewRange(float *statustext_time)
3195 static const wchar_t *msg[] = {
3196 L"Disabled full viewing range",
3197 L"Enabled full viewing range"
3200 draw_control->range_all = !draw_control->range_all;
3201 infostream << msg[draw_control->range_all] << std::endl;
3202 statustext = msg[draw_control->range_all];
3203 *statustext_time = 0;
3207 void Game::updateCameraDirection(CameraOrientation *cam,
3208 VolatileRunFlags *flags, float dtime)
3210 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3213 if (!random_input) {
3214 // Mac OSX gets upset if this is set every frame
3215 if (device->getCursorControl()->isVisible())
3216 device->getCursorControl()->setVisible(false);
3220 if (flags->first_loop_after_window_activation)
3221 flags->first_loop_after_window_activation = false;
3223 updateCameraOrientation(cam, *flags, dtime);
3225 input->setMousePos((driver->getScreenSize().Width / 2),
3226 (driver->getScreenSize().Height / 2));
3230 // Mac OSX gets upset if this is set every frame
3231 if (device->getCursorControl()->isVisible() == false)
3232 device->getCursorControl()->setVisible(true);
3235 if (!flags->first_loop_after_window_activation)
3236 flags->first_loop_after_window_activation = true;
3241 void Game::updateCameraOrientation(CameraOrientation *cam,
3242 const VolatileRunFlags &flags, float dtime)
3244 #ifdef HAVE_TOUCHSCREENGUI
3245 if (g_touchscreengui) {
3246 cam->camera_yaw = g_touchscreengui->getYaw();
3247 cam->camera_pitch = g_touchscreengui->getPitch();
3251 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3252 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3254 if (flags.invert_mouse
3255 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3259 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3260 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3262 #ifdef HAVE_TOUCHSCREENGUI
3266 if (m_cache_enable_joysticks) {
3267 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3268 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) *
3270 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) *
3274 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3278 void Game::updatePlayerControl(const CameraOrientation &cam)
3280 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3282 // DO NOT use the isKeyDown method for the forward, backward, left, right
3283 // buttons, as the code that uses the controls needs to be able to
3284 // distinguish between the two in order to know when to use joysticks.
3286 PlayerControl control(
3287 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3288 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3289 input->isKeyDown(keycache.key[KeyType::LEFT]),
3290 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3291 isKeyDown(KeyType::JUMP),
3292 isKeyDown(KeyType::SPECIAL1),
3293 isKeyDown(KeyType::SNEAK),
3294 isKeyDown(KeyType::ZOOM),
3299 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3300 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3304 ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
3305 ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
3306 ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
3307 ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
3308 ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
3309 ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
3310 ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
3311 ( (u32)(isLeftPressed() & 0x1) << 7) |
3312 ( (u32)(isRightPressed() & 0x1) << 8
3316 /* For Android, simulate holding down AUX1 (fast move) if the user has
3317 * the fast_move setting toggled on. If there is an aux1 key defined for
3318 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3321 if (m_cache_hold_aux1) {
3322 control.aux1 = control.aux1 ^ true;
3323 keypress_bits ^= ((u32)(1U << 5));
3327 client->setPlayerControl(control);
3328 LocalPlayer *player = client->getEnv().getLocalPlayer();
3329 player->keyPressed = keypress_bits;
3335 inline void Game::step(f32 *dtime)
3337 bool can_be_and_is_paused =
3338 (simple_singleplayer_mode && g_menumgr.pausesGame());
3340 if (can_be_and_is_paused) { // This is for a singleplayer server
3341 *dtime = 0; // No time passes
3343 if (server != NULL) {
3344 //TimeTaker timer("server->step(dtime)");
3345 server->step(*dtime);
3348 //TimeTaker timer("client.step(dtime)");
3349 client->step(*dtime);
3354 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3356 ClientEvent event = client->getClientEvent();
3358 LocalPlayer *player = client->getEnv().getLocalPlayer();
3360 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3362 if (event.type == CE_PLAYER_DAMAGE &&
3363 client->getHP() != 0) {
3364 //u16 damage = event.player_damage.amount;
3365 //infostream<<"Player damage: "<<damage<<std::endl;
3367 *damage_flash += 100.0;
3368 *damage_flash += 8.0 * event.player_damage.amount;
3370 player->hurt_tilt_timer = 1.5;
3371 player->hurt_tilt_strength = event.player_damage.amount / 4;
3372 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3374 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3375 gamedef->event()->put(e);
3376 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3377 cam->camera_yaw = event.player_force_move.yaw;
3378 cam->camera_pitch = event.player_force_move.pitch;
3379 } else if (event.type == CE_DEATHSCREEN) {
3380 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3381 device, &input->joystick, client);
3383 chat_backend->addMessage(L"", L"You died.");
3385 /* Handle visualization */
3387 player->hurt_tilt_timer = 0;
3388 player->hurt_tilt_strength = 0;
3390 } else if (event.type == CE_SHOW_FORMSPEC) {
3391 FormspecFormSource *fs_src =
3392 new FormspecFormSource(*(event.show_formspec.formspec));
3393 TextDestPlayerInventory *txt_dst =
3394 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3396 create_formspec_menu(¤t_formspec, client, gamedef,
3397 texture_src, device, &input->joystick,
3398 fs_src, txt_dst, client);
3400 delete(event.show_formspec.formspec);
3401 delete(event.show_formspec.formname);
3402 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3403 (event.type == CE_ADD_PARTICLESPAWNER) ||
3404 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3405 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3407 } else if (event.type == CE_HUDADD) {
3408 u32 id = event.hudadd.id;
3410 LocalPlayer *player = client->getEnv().getLocalPlayer();
3411 HudElement *e = player->getHud(id);
3414 delete event.hudadd.pos;
3415 delete event.hudadd.name;
3416 delete event.hudadd.scale;
3417 delete event.hudadd.text;
3418 delete event.hudadd.align;
3419 delete event.hudadd.offset;
3420 delete event.hudadd.world_pos;
3421 delete event.hudadd.size;
3426 e->type = (HudElementType)event.hudadd.type;
3427 e->pos = *event.hudadd.pos;
3428 e->name = *event.hudadd.name;
3429 e->scale = *event.hudadd.scale;
3430 e->text = *event.hudadd.text;
3431 e->number = event.hudadd.number;
3432 e->item = event.hudadd.item;
3433 e->dir = event.hudadd.dir;
3434 e->align = *event.hudadd.align;
3435 e->offset = *event.hudadd.offset;
3436 e->world_pos = *event.hudadd.world_pos;
3437 e->size = *event.hudadd.size;
3439 u32 new_id = player->addHud(e);
3440 //if this isn't true our huds aren't consistent
3441 sanity_check(new_id == id);
3443 delete event.hudadd.pos;
3444 delete event.hudadd.name;
3445 delete event.hudadd.scale;
3446 delete event.hudadd.text;
3447 delete event.hudadd.align;
3448 delete event.hudadd.offset;
3449 delete event.hudadd.world_pos;
3450 delete event.hudadd.size;
3451 } else if (event.type == CE_HUDRM) {
3452 HudElement *e = player->removeHud(event.hudrm.id);
3456 } else if (event.type == CE_HUDCHANGE) {
3457 u32 id = event.hudchange.id;
3458 HudElement *e = player->getHud(id);
3461 delete event.hudchange.v3fdata;
3462 delete event.hudchange.v2fdata;
3463 delete event.hudchange.sdata;
3464 delete event.hudchange.v2s32data;
3468 switch (event.hudchange.stat) {
3470 e->pos = *event.hudchange.v2fdata;
3474 e->name = *event.hudchange.sdata;
3477 case HUD_STAT_SCALE:
3478 e->scale = *event.hudchange.v2fdata;
3482 e->text = *event.hudchange.sdata;
3485 case HUD_STAT_NUMBER:
3486 e->number = event.hudchange.data;
3490 e->item = event.hudchange.data;
3494 e->dir = event.hudchange.data;
3497 case HUD_STAT_ALIGN:
3498 e->align = *event.hudchange.v2fdata;
3501 case HUD_STAT_OFFSET:
3502 e->offset = *event.hudchange.v2fdata;
3505 case HUD_STAT_WORLD_POS:
3506 e->world_pos = *event.hudchange.v3fdata;
3510 e->size = *event.hudchange.v2s32data;
3514 delete event.hudchange.v3fdata;
3515 delete event.hudchange.v2fdata;
3516 delete event.hudchange.sdata;
3517 delete event.hudchange.v2s32data;
3518 } else if (event.type == CE_SET_SKY) {
3519 sky->setVisible(false);
3526 // Handle according to type
3527 if (*event.set_sky.type == "regular") {
3528 sky->setVisible(true);
3529 } else if (*event.set_sky.type == "skybox" &&
3530 event.set_sky.params->size() == 6) {
3531 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3532 skybox = smgr->addSkyBoxSceneNode(
3533 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3534 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3535 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3536 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3537 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3538 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3540 // Handle everything else as plain color
3542 if (*event.set_sky.type != "plain")
3543 infostream << "Unknown sky type: "
3544 << (*event.set_sky.type) << std::endl;
3546 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3549 delete event.set_sky.bgcolor;
3550 delete event.set_sky.type;
3551 delete event.set_sky.params;
3552 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3553 bool enable = event.override_day_night_ratio.do_override;
3554 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3555 client->getEnv().setDayNightRatioOverride(enable, value);
3561 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3562 f32 dtime, float time_from_last_punch)
3564 LocalPlayer *player = client->getEnv().getLocalPlayer();
3567 For interaction purposes, get info about the held item
3569 - Is it a usable item?
3570 - Can it point to liquids?
3572 ItemStack playeritem;
3574 InventoryList *mlist = local_inventory->getList("main");
3576 if (mlist && client->getPlayerItem() < mlist->getSize())
3577 playeritem = mlist->getItem(client->getPlayerItem());
3580 ToolCapabilities playeritem_toolcap =
3581 playeritem.getToolCapabilities(itemdef_manager);
3583 v3s16 old_camera_offset = camera->getOffset();
3585 if (wasKeyDown(KeyType::CAMERA_MODE)) {
3586 GenericCAO *playercao = player->getCAO();
3588 // If playercao not loaded, don't change camera
3589 if (playercao == NULL)
3592 camera->toggleCameraMode();
3594 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3595 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3598 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3599 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3601 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3602 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3604 camera->step(dtime);
3606 v3f camera_position = camera->getPosition();
3607 v3f camera_direction = camera->getDirection();
3608 f32 camera_fov = camera->getFovMax();
3609 v3s16 camera_offset = camera->getOffset();
3611 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3613 if (!flags->disable_camera_update) {
3614 client->getEnv().getClientMap().updateCamera(camera_position,
3615 camera_direction, camera_fov, camera_offset);
3617 if (flags->camera_offset_changed) {
3618 client->updateCameraOffset(camera_offset);
3619 client->getEnv().updateCameraOffset(camera_offset);
3622 clouds->updateCameraOffset(camera_offset);
3628 void Game::updateSound(f32 dtime)
3630 // Update sound listener
3631 v3s16 camera_offset = camera->getOffset();
3632 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3633 v3f(0, 0, 0), // velocity
3634 camera->getDirection(),
3635 camera->getCameraNode()->getUpVector());
3636 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3639 // Update sound maker
3640 soundmaker->step(dtime);
3642 LocalPlayer *player = client->getEnv().getLocalPlayer();
3644 ClientMap &map = client->getEnv().getClientMap();
3645 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3646 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3650 void Game::processPlayerInteraction(GameRunData *runData,
3651 f32 dtime, bool show_hud, bool show_debug)
3653 LocalPlayer *player = client->getEnv().getLocalPlayer();
3655 ItemStack playeritem;
3657 InventoryList *mlist = local_inventory->getList("main");
3659 if (mlist && client->getPlayerItem() < mlist->getSize())
3660 playeritem = mlist->getItem(client->getPlayerItem());
3663 const ItemDefinition &playeritem_def =
3664 playeritem.getDefinition(itemdef_manager);
3666 v3f player_position = player->getPosition();
3667 v3f camera_position = camera->getPosition();
3668 v3f camera_direction = camera->getDirection();
3669 v3s16 camera_offset = camera->getOffset();
3673 Calculate what block is the crosshair pointing to
3676 f32 d = playeritem_def.range; // max. distance
3677 f32 d_hand = itemdef_manager->get("").range;
3679 if (d < 0 && d_hand >= 0)
3684 core::line3d<f32> shootline;
3686 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3688 shootline = core::line3d<f32>(camera_position,
3689 camera_position + camera_direction * BS * (d + 1));
3692 // prevent player pointing anything in front-view
3693 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3694 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3697 #ifdef HAVE_TOUCHSCREENGUI
3699 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3700 shootline = g_touchscreengui->getShootline();
3701 shootline.start += intToFloat(camera_offset, BS);
3702 shootline.end += intToFloat(camera_offset, BS);
3707 PointedThing pointed = getPointedThing(
3709 client, hud, player_position, camera_direction,
3710 camera_position, shootline, d,
3711 playeritem_def.liquids_pointable,
3712 !runData->ldown_for_dig,
3715 runData->selected_object);
3717 if (pointed != runData->pointed_old) {
3718 infostream << "Pointing at " << pointed.dump() << std::endl;
3719 hud->updateSelectionMesh(camera_offset);
3724 - releasing left mouse button
3725 - pointing away from node
3727 if (runData->digging) {
3728 if (getLeftReleased()) {
3729 infostream << "Left button released"
3730 << " (stopped digging)" << std::endl;
3731 runData->digging = false;
3732 } else if (pointed != runData->pointed_old) {
3733 if (pointed.type == POINTEDTHING_NODE
3734 && runData->pointed_old.type == POINTEDTHING_NODE
3735 && pointed.node_undersurface
3736 == runData->pointed_old.node_undersurface) {
3737 // Still pointing to the same node, but a different face.
3740 infostream << "Pointing away from node"
3741 << " (stopped digging)" << std::endl;
3742 runData->digging = false;
3743 hud->updateSelectionMesh(camera_offset);
3747 if (!runData->digging) {
3748 client->interact(1, runData->pointed_old);
3749 client->setCrack(-1, v3s16(0, 0, 0));
3750 runData->dig_time = 0.0;
3754 if (!runData->digging && runData->ldown_for_dig && !isLeftPressed()) {
3755 runData->ldown_for_dig = false;
3758 runData->left_punch = false;
3760 soundmaker->m_player_leftpunch_sound.name = "";
3762 if (isRightPressed())
3763 runData->repeat_rightclick_timer += dtime;
3765 runData->repeat_rightclick_timer = 0;
3767 if (playeritem_def.usable && isLeftPressed()) {
3768 if (getLeftClicked())
3769 client->interact(4, pointed);
3770 } else if (pointed.type == POINTEDTHING_NODE) {
3771 ToolCapabilities playeritem_toolcap =
3772 playeritem.getToolCapabilities(itemdef_manager);
3773 handlePointingAtNode(runData, pointed, playeritem_def,
3774 playeritem_toolcap, dtime);
3775 } else if (pointed.type == POINTEDTHING_OBJECT) {
3776 handlePointingAtObject(runData, pointed, playeritem,
3777 player_position, show_debug);
3778 } else if (isLeftPressed()) {
3779 // When button is held down in air, show continuous animation
3780 runData->left_punch = true;
3781 } else if (getRightClicked()) {
3782 handlePointingAtNothing(runData, playeritem);
3785 runData->pointed_old = pointed;
3787 if (runData->left_punch || getLeftClicked())
3788 camera->setDigging(0); // left click animation
3790 input->resetLeftClicked();
3791 input->resetRightClicked();
3793 input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3794 input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3796 input->resetLeftReleased();
3797 input->resetRightReleased();
3799 input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3800 input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3804 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3806 infostream << "Right Clicked in Air" << std::endl;
3807 PointedThing fauxPointed;
3808 fauxPointed.type = POINTEDTHING_NOTHING;
3809 client->interact(5, fauxPointed);
3813 void Game::handlePointingAtNode(GameRunData *runData,
3814 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3815 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3817 v3s16 nodepos = pointed.node_undersurface;
3818 v3s16 neighbourpos = pointed.node_abovesurface;
3821 Check information text of node
3824 ClientMap &map = client->getEnv().getClientMap();
3825 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3828 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3830 MapNode n = map.getNodeNoEx(nodepos);
3832 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3833 infotext = L"Unknown node: ";
3834 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3838 if (runData->nodig_delay_timer <= 0.0 && isLeftPressed()
3839 && client->checkPrivilege("interact")) {
3840 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3843 if ((getRightClicked() ||
3844 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3845 client->checkPrivilege("interact")) {
3846 runData->repeat_rightclick_timer = 0;
3847 infostream << "Ground right-clicked" << std::endl;
3849 if (meta && meta->getString("formspec") != "" && !random_input
3850 && !isKeyDown(KeyType::SNEAK)) {
3851 infostream << "Launching custom inventory view" << std::endl;
3853 InventoryLocation inventoryloc;
3854 inventoryloc.setNodeMeta(nodepos);
3856 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3857 &client->getEnv().getClientMap(), nodepos);
3858 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3860 create_formspec_menu(¤t_formspec, client, gamedef,
3861 texture_src, device, &input->joystick, fs_src, txt_dst, client);
3863 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3865 // Report right click to server
3867 camera->setDigging(1); // right click animation (always shown for feedback)
3869 // If the wielded item has node placement prediction,
3871 bool placed = nodePlacementPrediction(*client,
3873 nodepos, neighbourpos);
3877 client->interact(3, pointed);
3879 soundmaker->m_player_rightpunch_sound =
3880 playeritem_def.sound_place;
3882 soundmaker->m_player_rightpunch_sound =
3885 if (playeritem_def.node_placement_prediction == "" ||
3886 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3887 client->interact(3, pointed); // Report to server
3889 soundmaker->m_player_rightpunch_sound =
3890 playeritem_def.sound_place_failed;
3898 void Game::handlePointingAtObject(GameRunData *runData,
3899 const PointedThing &pointed,
3900 const ItemStack &playeritem,
3901 const v3f &player_position,
3904 infotext = unescape_enriched(
3905 utf8_to_wide(runData->selected_object->infoText()));
3908 if (infotext != L"") {
3911 infotext += unescape_enriched(utf8_to_wide(
3912 runData->selected_object->debugInfoText()));
3915 if (isLeftPressed()) {
3916 bool do_punch = false;
3917 bool do_punch_damage = false;
3919 if (runData->object_hit_delay_timer <= 0.0) {
3921 do_punch_damage = true;
3922 runData->object_hit_delay_timer = object_hit_delay;
3925 if (getLeftClicked())
3929 infostream << "Left-clicked object" << std::endl;
3930 runData->left_punch = true;
3933 if (do_punch_damage) {
3934 // Report direct punch
3935 v3f objpos = runData->selected_object->getPosition();
3936 v3f dir = (objpos - player_position).normalize();
3938 bool disable_send = runData->selected_object->directReportPunch(
3939 dir, &playeritem, runData->time_from_last_punch);
3940 runData->time_from_last_punch = 0;
3943 client->interact(0, pointed);
3945 } else if (getRightClicked()) {
3946 infostream << "Right-clicked object" << std::endl;
3947 client->interact(3, pointed); // place
3952 void Game::handleDigging(GameRunData *runData,
3953 const PointedThing &pointed, const v3s16 &nodepos,
3954 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3956 if (!runData->digging) {
3957 infostream << "Started digging" << std::endl;
3958 client->interact(0, pointed);
3959 runData->digging = true;
3960 runData->ldown_for_dig = true;
3963 LocalPlayer *player = client->getEnv().getLocalPlayer();
3964 ClientMap &map = client->getEnv().getClientMap();
3965 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3967 // NOTE: Similar piece of code exists on the server side for
3969 // Get digging parameters
3970 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3971 &playeritem_toolcap);
3973 // If can't dig, try hand
3974 if (!params.diggable) {
3975 const ItemDefinition &hand = itemdef_manager->get("");
3976 const ToolCapabilities *tp = hand.tool_capabilities;
3979 params = getDigParams(nodedef_manager->get(n).groups, tp);
3982 if (params.diggable == false) {
3983 // I guess nobody will wait for this long
3984 runData->dig_time_complete = 10000000.0;
3986 runData->dig_time_complete = params.time;
3988 if (m_cache_enable_particles) {
3989 const ContentFeatures &features =
3990 client->getNodeDefManager()->get(n);
3991 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3992 player, nodepos, features.tiles);
3996 if (runData->dig_time_complete >= 0.001) {
3997 runData->dig_index = (float)crack_animation_length
3999 / runData->dig_time_complete;
4001 // This is for torches
4002 runData->dig_index = crack_animation_length;
4005 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
4007 if (sound_dig.exists() && params.diggable) {
4008 if (sound_dig.name == "__group") {
4009 if (params.main_group != "") {
4010 soundmaker->m_player_leftpunch_sound.gain = 0.5;
4011 soundmaker->m_player_leftpunch_sound.name =
4012 std::string("default_dig_") +
4016 soundmaker->m_player_leftpunch_sound = sound_dig;
4020 // Don't show cracks if not diggable
4021 if (runData->dig_time_complete >= 100000.0) {
4022 } else if (runData->dig_index < crack_animation_length) {
4023 //TimeTaker timer("client.setTempMod");
4024 //infostream<<"dig_index="<<dig_index<<std::endl;
4025 client->setCrack(runData->dig_index, nodepos);
4027 infostream << "Digging completed" << std::endl;
4028 client->interact(2, pointed);
4029 client->setCrack(-1, v3s16(0, 0, 0));
4030 bool is_valid_position;
4031 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4032 if (is_valid_position)
4033 client->removeNode(nodepos);
4035 if (m_cache_enable_particles) {
4036 const ContentFeatures &features =
4037 client->getNodeDefManager()->get(wasnode);
4038 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
4039 player, nodepos, features.tiles);
4042 runData->dig_time = 0;
4043 runData->digging = false;
4045 runData->nodig_delay_timer =
4046 runData->dig_time_complete / (float)crack_animation_length;
4048 // We don't want a corresponding delay to
4049 // very time consuming nodes
4050 if (runData->nodig_delay_timer > 0.3)
4051 runData->nodig_delay_timer = 0.3;
4053 // We want a slight delay to very little
4054 // time consuming nodes
4055 const float mindelay = 0.15;
4057 if (runData->nodig_delay_timer < mindelay)
4058 runData->nodig_delay_timer = mindelay;
4060 // Send event to trigger sound
4061 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4062 gamedef->event()->put(e);
4065 if (runData->dig_time_complete < 100000.0) {
4066 runData->dig_time += dtime;
4068 runData->dig_time = 0;
4069 client->setCrack(-1, nodepos);
4072 camera->setDigging(0); // left click animation
4076 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
4077 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
4078 const CameraOrientation &cam)
4080 LocalPlayer *player = client->getEnv().getLocalPlayer();
4086 if (draw_control->range_all) {
4087 runData->fog_range = 100000 * BS;
4089 runData->fog_range = 0.9 * draw_control->wanted_range * BS;
4093 Calculate general brightness
4095 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4096 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4097 float direct_brightness;
4100 if (g_settings->getBool("free_move")) {
4101 direct_brightness = time_brightness;
4102 sunlight_seen = true;
4104 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4105 float old_brightness = sky->getBrightness();
4106 direct_brightness = client->getEnv().getClientMap()
4107 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
4108 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4112 float time_of_day = runData->time_of_day;
4113 float time_of_day_smooth = runData->time_of_day_smooth;
4115 time_of_day = client->getEnv().getTimeOfDayF();
4117 const float maxsm = 0.05;
4118 const float todsm = 0.05;
4120 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4121 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4122 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4123 time_of_day_smooth = time_of_day;
4125 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4126 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4127 + (time_of_day + 1.0) * todsm;
4129 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4130 + time_of_day * todsm;
4132 runData->time_of_day = time_of_day;
4133 runData->time_of_day_smooth = time_of_day_smooth;
4135 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4136 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4137 player->getPitch());
4143 v3f player_position = player->getPosition();
4144 if (sky->getCloudsVisible()) {
4145 clouds->setVisible(true);
4146 clouds->step(dtime);
4147 clouds->update(v2f(player_position.X, player_position.Z),
4148 sky->getCloudColor());
4150 clouds->setVisible(false);
4157 client->getParticleManager()->step(dtime);
4163 if (m_cache_enable_fog && !flags.force_fog_off) {
4166 video::EFT_FOG_LINEAR,
4167 runData->fog_range * 0.4,
4168 runData->fog_range * 1.0,
4176 video::EFT_FOG_LINEAR,
4186 Get chat messages from client
4189 v2u32 screensize = driver->getScreenSize();
4191 updateChat(*client, dtime, flags.show_debug, screensize,
4192 flags.show_chat, runData->profiler_current_page,
4193 *chat_backend, guitext_chat);
4199 if (client->getPlayerItem() != runData->new_playeritem)
4200 client->selectPlayerItem(runData->new_playeritem);
4202 // Update local inventory if it has changed
4203 if (client->getLocalInventoryUpdated()) {
4204 //infostream<<"Updating local inventory"<<std::endl;
4205 client->getLocalInventory(*local_inventory);
4206 runData->update_wielded_item_trigger = true;
4209 if (runData->update_wielded_item_trigger) {
4210 // Update wielded tool
4211 InventoryList *mlist = local_inventory->getList("main");
4213 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4214 ItemStack item = mlist->getItem(client->getPlayerItem());
4215 camera->wield(item);
4217 runData->update_wielded_item_trigger = false;
4221 Update block draw list every 200ms or when camera direction has
4224 runData->update_draw_list_timer += dtime;
4226 v3f camera_direction = camera->getDirection();
4227 if (runData->update_draw_list_timer >= 0.2
4228 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4229 || flags.camera_offset_changed) {
4230 runData->update_draw_list_timer = 0;
4231 client->getEnv().getClientMap().updateDrawList(driver);
4232 runData->update_draw_list_last_cam_dir = camera_direction;
4235 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4238 make sure menu is on top
4239 1. Delete formspec menu reference if menu was removed
4240 2. Else, make sure formspec menu is on top
4242 if (current_formspec) {
4243 if (current_formspec->getReferenceCount() == 1) {
4244 current_formspec->drop();
4245 current_formspec = NULL;
4246 } else if (!noMenuActive()) {
4247 guiroot->bringToFront(current_formspec);
4255 video::SColor skycolor = sky->getSkyColor();
4257 TimeTaker tt_draw("mainloop: draw");
4259 TimeTaker timer("beginScene");
4260 driver->beginScene(true, true, skycolor);
4261 stats->beginscenetime = timer.stop(true);
4264 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4265 guienv, screensize, skycolor, flags.show_hud,
4266 flags.show_minimap);
4271 if (flags.show_profiler_graph)
4272 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4277 if (runData->damage_flash > 0.0) {
4278 video::SColor color(std::min(runData->damage_flash, 180.0f),
4282 driver->draw2DRectangle(color,
4283 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4286 runData->damage_flash -= 100.0 * dtime;
4292 if (player->hurt_tilt_timer > 0.0) {
4293 player->hurt_tilt_timer -= dtime * 5;
4295 if (player->hurt_tilt_timer < 0)
4296 player->hurt_tilt_strength = 0;
4300 Update minimap pos and rotation
4302 if (flags.show_minimap && flags.show_hud) {
4303 mapper->setPos(floatToInt(player->getPosition(), BS));
4304 mapper->setAngle(player->getYaw());
4311 TimeTaker timer("endScene");
4313 stats->endscenetime = timer.stop(true);
4316 stats->drawtime = tt_draw.stop(true);
4317 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4321 inline static const char *yawToDirectionString(int yaw)
4323 static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4325 yaw = wrapDegrees_0_360(yaw);
4326 yaw = (yaw + 45) % 360 / 90;
4328 return direction[yaw];
4332 void Game::updateGui(float *statustext_time, const RunStats &stats,
4333 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4334 const CameraOrientation &cam)
4336 v2u32 screensize = driver->getScreenSize();
4337 LocalPlayer *player = client->getEnv().getLocalPlayer();
4338 v3f player_position = player->getPosition();
4340 if (flags.show_debug) {
4341 static float drawtime_avg = 0;
4342 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4344 u16 fps = 1.0 / stats.dtime_jitter.avg;
4345 //s32 fps = driver->getFPS();
4347 std::ostringstream os(std::ios_base::binary);
4349 << PROJECT_NAME_C " " << g_version_hash
4351 << " (R: range_all=" << draw_control->range_all << ")"
4352 << std::setprecision(0)
4353 << " drawtime = " << drawtime_avg
4354 << std::setprecision(1)
4355 << ", dtime_jitter = "
4356 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4357 << std::setprecision(1)
4358 << ", v_range = " << draw_control->wanted_range
4359 << std::setprecision(3)
4360 << ", RTT = " << client->getRTT();
4361 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4362 guitext->setVisible(true);
4364 guitext->setVisible(false);
4367 if (guitext->isVisible()) {
4368 core::rect<s32> rect(
4370 screensize.X, 5 + g_fontengine->getTextHeight()
4372 guitext->setRelativePosition(rect);
4375 if (flags.show_debug) {
4376 std::ostringstream os(std::ios_base::binary);
4377 os << std::setprecision(1) << std::fixed
4378 << "(" << (player_position.X / BS)
4379 << ", " << (player_position.Y / BS)
4380 << ", " << (player_position.Z / BS)
4381 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4382 << " " << yawToDirectionString(cam.camera_yaw)
4383 << ") (seed = " << ((u64)client->getMapSeed())
4386 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4387 ClientMap &map = client->getEnv().getClientMap();
4388 const INodeDefManager *nodedef = client->getNodeDefManager();
4389 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4390 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4391 const ContentFeatures &features = nodedef->get(n);
4392 os << " (pointing_at = " << nodedef->get(n).name
4393 << " - " << features.tiledef[0].name.c_str()
4398 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4399 guitext2->setVisible(true);
4401 core::rect<s32> rect(
4402 5, 5 + g_fontengine->getTextHeight(),
4403 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4405 guitext2->setRelativePosition(rect);
4407 guitext2->setVisible(false);
4410 setStaticText(guitext_info, infotext.c_str());
4411 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4413 float statustext_time_max = 1.5;
4415 if (!statustext.empty()) {
4416 *statustext_time += dtime;
4418 if (*statustext_time >= statustext_time_max) {
4420 *statustext_time = 0;
4424 setStaticText(guitext_status, statustext.c_str());
4425 guitext_status->setVisible(!statustext.empty());
4427 if (!statustext.empty()) {
4428 s32 status_width = guitext_status->getTextWidth();
4429 s32 status_height = guitext_status->getTextHeight();
4430 s32 status_y = screensize.Y - 150;
4431 s32 status_x = (screensize.X - status_width) / 2;
4432 core::rect<s32> rect(
4433 status_x , status_y - status_height,
4434 status_x + status_width, status_y
4436 guitext_status->setRelativePosition(rect);
4439 video::SColor initial_color(255, 0, 0, 0);
4441 if (guienv->getSkin())
4442 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4444 video::SColor final_color = initial_color;
4445 final_color.setAlpha(0);
4446 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4447 initial_color, final_color,
4448 pow(*statustext_time / statustext_time_max, 2.0f));
4449 guitext_status->setOverrideColor(fade_color);
4450 guitext_status->enableOverrideColor(true);
4455 /* Log times and stuff for visualization */
4456 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4458 Profiler::GraphValues values;
4459 g_profiler->graphGet(values);
4465 /****************************************************************************
4467 ****************************************************************************/
4469 /* On some computers framerate doesn't seem to be automatically limited
4471 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4473 // not using getRealTime is necessary for wine
4474 device->getTimer()->tick(); // Maker sure device time is up-to-date
4475 u32 time = device->getTimer()->getTime();
4476 u32 last_time = fps_timings->last_time;
4478 if (time > last_time) // Make sure time hasn't overflowed
4479 fps_timings->busy_time = time - last_time;
4481 fps_timings->busy_time = 0;
4483 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4484 ? g_settings->getFloat("pause_fps_max")
4485 : g_settings->getFloat("fps_max"));
4487 if (fps_timings->busy_time < frametime_min) {
4488 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4489 device->sleep(fps_timings->sleep_time);
4491 fps_timings->sleep_time = 0;
4494 /* Get the new value of the device timer. Note that device->sleep() may
4495 * not sleep for the entire requested time as sleep may be interrupted and
4496 * therefore it is arguably more accurate to get the new time from the
4497 * device rather than calculating it by adding sleep_time to time.
4500 device->getTimer()->tick(); // Update device timer
4501 time = device->getTimer()->getTime();
4503 if (time > last_time) // Make sure last_time hasn't overflowed
4504 *dtime = (time - last_time) / 1000.0;
4508 fps_timings->last_time = time;
4511 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4512 // pass a copy of it to this function
4513 // Note: \p msg must be allocated using new (not malloc())
4514 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4515 int percent, bool draw_clouds)
4517 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4521 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4523 ((Game *)data)->readSettings();
4526 void Game::readSettings()
4528 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4529 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4530 m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
4531 m_cache_enable_particles = g_settings->getBool("enable_particles");
4532 m_cache_enable_fog = g_settings->getBool("enable_fog");
4533 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4534 m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4535 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4537 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4540 /****************************************************************************/
4541 /****************************************************************************
4543 ****************************************************************************/
4544 /****************************************************************************/
4546 void Game::extendedResourceCleanup()
4548 // Extended resource accounting
4549 infostream << "Irrlicht resources after cleanup:" << std::endl;
4550 infostream << "\tRemaining meshes : "
4551 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4552 infostream << "\tRemaining textures : "
4553 << driver->getTextureCount() << std::endl;
4555 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4556 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4557 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4561 clearTextureNameCache();
4562 infostream << "\tRemaining materials: "
4563 << driver-> getMaterialRendererCount()
4564 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4568 /****************************************************************************/
4569 /****************************************************************************
4570 extern function for launching the game
4571 ****************************************************************************/
4572 /****************************************************************************/
4574 void the_game(bool *kill,
4576 InputHandler *input,
4577 IrrlichtDevice *device,
4579 const std::string &map_dir,
4580 const std::string &playername,
4581 const std::string &password,
4582 const std::string &address, // If empty local server is created
4585 std::string &error_message,
4586 ChatBackend &chat_backend,
4587 bool *reconnect_requested,
4588 const SubgameSpec &gamespec, // Used for local game
4589 bool simple_singleplayer_mode)
4593 /* Make a copy of the server address because if a local singleplayer server
4594 * is created then this is updated and we don't want to change the value
4595 * passed to us by the calling function
4597 std::string server_address = address;
4601 if (game.startup(kill, random_input, input, device, map_dir,
4602 playername, password, &server_address, port, error_message,
4603 reconnect_requested, &chat_backend, gamespec,
4604 simple_singleplayer_mode)) {
4609 } catch (SerializationError &e) {
4610 error_message = std::string("A serialization error occurred:\n")
4611 + e.what() + "\n\nThe server is probably "
4612 " running a different version of " PROJECT_NAME_C ".";
4613 errorstream << error_message << std::endl;
4614 } catch (ServerError &e) {
4615 error_message = e.what();
4616 errorstream << "ServerError: " << error_message << std::endl;
4617 } catch (ModError &e) {
4618 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4619 errorstream << "ModError: " << error_message << std::endl;