3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include "client/tile.h" // For TextureSource
26 #include "clientmap.h"
29 #include "content_cao.h"
30 #include "drawscene.h"
31 #include "event_manager.h"
32 #include "fontengine.h"
37 #include "guiChatConsole.h"
38 #include "guiFormSpecMenu.h"
39 #include "guiKeyChangeMenu.h"
40 #include "guiPasswordChange.h"
41 #include "guiVolumeChange.h"
43 #include "mainmenumanager.h"
45 #include "nodedef.h" // Needed for determining pointing to nodes
46 #include "nodemetadata.h"
47 #include "particles.h"
49 #include "quicktune_shortcutter.h"
52 #include "shader.h" // For ShaderSource
56 #include "util/directiontables.h"
57 #include "util/pointedthing.h"
60 #include "mapblock_mesh.h"
65 #include "sound_openal.h"
68 #ifdef HAVE_TOUCHSCREENGUI
69 #include "touchscreengui.h"
72 extern Settings *g_settings;
73 extern Profiler *g_profiler;
79 struct TextDestNodeMetadata : public TextDest {
80 TextDestNodeMetadata(v3s16 p, Client *client)
85 // This is deprecated I guess? -celeron55
86 void gotText(std::wstring text)
88 std::string ntext = wide_to_utf8(text);
89 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
90 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
92 fields["text"] = ntext;
93 m_client->sendNodemetaFields(m_p, "", fields);
95 void gotText(const StringMap &fields)
97 m_client->sendNodemetaFields(m_p, "", fields);
104 struct TextDestPlayerInventory : public TextDest {
105 TextDestPlayerInventory(Client *client)
110 TextDestPlayerInventory(Client *client, std::string formname)
113 m_formname = formname;
115 void gotText(const StringMap &fields)
117 m_client->sendInventoryFields(m_formname, fields);
123 struct LocalFormspecHandler : public TextDest {
124 LocalFormspecHandler();
125 LocalFormspecHandler(std::string formname) :
128 m_formname = formname;
131 LocalFormspecHandler(std::string formname, Client *client) :
134 m_formname = formname;
137 void gotText(std::wstring message)
139 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
142 void gotText(const StringMap &fields)
144 if (m_formname == "MT_PAUSE_MENU") {
145 if (fields.find("btn_sound") != fields.end()) {
146 g_gamecallback->changeVolume();
150 if (fields.find("btn_key_config") != fields.end()) {
151 g_gamecallback->keyConfig();
155 if (fields.find("btn_exit_menu") != fields.end()) {
156 g_gamecallback->disconnect();
160 if (fields.find("btn_exit_os") != fields.end()) {
161 g_gamecallback->exitToOS();
165 if (fields.find("btn_change_password") != fields.end()) {
166 g_gamecallback->changePassword();
170 if (fields.find("quit") != fields.end()) {
174 if (fields.find("btn_continue") != fields.end()) {
179 if (m_formname == "MT_DEATH_SCREEN") {
180 assert(m_client != 0);
182 if ((fields.find("btn_respawn") != fields.end())) {
183 m_client->sendRespawn();
187 if (fields.find("quit") != fields.end()) {
188 m_client->sendRespawn();
193 // don't show error message for unhandled cursor keys
194 if ((fields.find("key_up") != fields.end()) ||
195 (fields.find("key_down") != fields.end()) ||
196 (fields.find("key_left") != fields.end()) ||
197 (fields.find("key_right") != fields.end())) {
201 errorstream << "LocalFormspecHandler::gotText unhandled >"
202 << m_formname << "< event" << std::endl;
205 StringMap::const_iterator it;
206 for (it = fields.begin(); it != fields.end(); ++it) {
207 errorstream << "\t" << i << ": " << it->first
208 << "=" << it->second << std::endl;
216 /* Form update callback */
218 class NodeMetadataFormSource: public IFormSource
221 NodeMetadataFormSource(ClientMap *map, v3s16 p):
226 std::string getForm()
228 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
233 return meta->getString("formspec");
235 std::string resolveText(std::string str)
237 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
242 return meta->resolveString(str);
249 class PlayerInventoryFormSource: public IFormSource
252 PlayerInventoryFormSource(Client *client):
256 std::string getForm()
258 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
259 return player->inventory_formspec;
266 Check if a node is pointable
268 inline bool isPointableNode(const MapNode &n,
269 Client *client, bool liquids_pointable)
271 const ContentFeatures &features = client->getNodeDefManager()->get(n);
272 return features.pointable ||
273 (liquids_pointable && features.isLiquid());
276 static inline void getNeighborConnectingFace(v3s16 p, INodeDefManager *nodedef,
277 ClientMap *map, MapNode n, u8 bitmask, u8 *neighbors)
279 MapNode n2 = map->getNodeNoEx(p);
280 if (nodedef->nodeboxConnects(n, n2, bitmask))
281 *neighbors |= bitmask;
284 static inline u8 getNeighbors(v3s16 p, INodeDefManager *nodedef, ClientMap *map, MapNode n)
287 const ContentFeatures &f = nodedef->get(n);
288 // locate possible neighboring nodes to connect to
289 if (f.drawtype == NDT_NODEBOX && f.node_box.type == NODEBOX_CONNECTED) {
293 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
297 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
301 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
305 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
309 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
313 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
320 Find what the player is pointing at
322 PointedThing getPointedThing(Client *client, Hud *hud, const v3f &player_position,
323 const v3f &camera_direction, const v3f &camera_position,
324 core::line3d<f32> shootline, f32 d, bool liquids_pointable,
325 bool look_for_object, const v3s16 &camera_offset,
326 ClientActiveObject *&selected_object)
330 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
331 selectionboxes->clear();
332 static const bool show_entity_selectionbox = g_settings->getBool("show_entity_selectionbox");
334 selected_object = NULL;
336 INodeDefManager *nodedef = client->getNodeDefManager();
337 ClientMap &map = client->getEnv().getClientMap();
339 f32 min_distance = BS * 1001;
341 // First try to find a pointed at active object
342 if (look_for_object) {
343 selected_object = client->getSelectedActiveObject(d * BS,
344 camera_position, shootline);
346 if (selected_object != NULL) {
347 if (show_entity_selectionbox &&
348 selected_object->doShowSelectionBox()) {
349 aabb3f *selection_box = selected_object->getSelectionBox();
350 // Box should exist because object was
351 // returned in the first place
352 assert(selection_box);
354 v3f pos = selected_object->getPosition();
355 selectionboxes->push_back(aabb3f(
356 selection_box->MinEdge, selection_box->MaxEdge));
357 hud->setSelectionPos(pos, camera_offset);
360 min_distance = (selected_object->getPosition() - camera_position).getLength();
362 result.type = POINTEDTHING_OBJECT;
363 result.object_id = selected_object->getId();
367 // That didn't work, try to find a pointed at node
369 v3s16 pos_i = floatToInt(player_position, BS);
371 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
375 s16 ystart = pos_i.Y - (camera_direction.Y < 0 ? a : 1);
376 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
377 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
378 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
379 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
380 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
382 // Prevent signed number overflow
392 v3s16 pointed_pos(0, 0, 0);
394 for (s16 y = ystart; y <= yend; y++) {
395 for (s16 z = zstart; z <= zend; z++) {
396 for (s16 x = xstart; x <= xend; x++) {
398 bool is_valid_position;
401 n = map.getNodeNoEx(p, &is_valid_position);
402 if (!is_valid_position) {
405 if (!isPointableNode(n, client, liquids_pointable)) {
409 std::vector<aabb3f> boxes;
410 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(p, nodedef, &map, n));
413 v3f npf = intToFloat(np, BS);
414 for (std::vector<aabb3f>::const_iterator
416 i != boxes.end(); ++i) {
421 v3f centerpoint = box.getCenter();
422 f32 distance = (centerpoint - camera_position).getLength();
423 if (distance >= min_distance) {
426 if (!box.intersectsWithLine(shootline)) {
429 result.type = POINTEDTHING_NODE;
430 min_distance = distance;
437 if (result.type == POINTEDTHING_NODE) {
439 MapNode n = map.getNodeNoEx(pointed_pos);
440 v3f npf = intToFloat(pointed_pos, BS);
441 std::vector<aabb3f> boxes;
442 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(pointed_pos, nodedef, &map, n));
443 f32 face_min_distance = 1000 * BS;
444 for (std::vector<aabb3f>::const_iterator
446 i != boxes.end(); ++i) {
450 for (u16 j = 0; j < 6; j++) {
451 v3s16 facedir = g_6dirs[j];
452 aabb3f facebox = box;
454 facebox.MinEdge.X = facebox.MaxEdge.X - d;
455 } else if (facedir.X < 0) {
456 facebox.MaxEdge.X = facebox.MinEdge.X + d;
457 } else if (facedir.Y > 0) {
458 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
459 } else if (facedir.Y < 0) {
460 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
461 } else if (facedir.Z > 0) {
462 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
463 } else if (facedir.Z < 0) {
464 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
466 v3f centerpoint = facebox.getCenter();
467 f32 distance = (centerpoint - camera_position).getLength();
468 if (distance >= face_min_distance)
470 if (!facebox.intersectsWithLine(shootline))
472 result.node_abovesurface = pointed_pos + facedir;
473 face_min_distance = distance;
476 selectionboxes->clear();
477 for (std::vector<aabb3f>::const_iterator
479 i != boxes.end(); ++i) {
481 box.MinEdge += v3f(-d, -d, -d);
482 box.MaxEdge += v3f(d, d, d);
483 selectionboxes->push_back(box);
485 hud->setSelectionPos(intToFloat(pointed_pos, BS), camera_offset);
486 result.node_undersurface = pointed_pos;
489 // Update selection mesh light level and vertex colors
490 if (selectionboxes->size() > 0) {
491 v3f pf = hud->getSelectionPos();
492 v3s16 p = floatToInt(pf, BS);
494 // Get selection mesh light level
495 MapNode n = map.getNodeNoEx(p);
496 u16 node_light = getInteriorLight(n, -1, nodedef);
497 u16 light_level = node_light;
499 for (u8 i = 0; i < 6; i++) {
500 n = map.getNodeNoEx(p + g_6dirs[i]);
501 node_light = getInteriorLight(n, -1, nodedef);
502 if (node_light > light_level)
503 light_level = node_light;
506 video::SColor c = MapBlock_LightColor(255, light_level, 0);
508 u8 night = c.getGreen();
509 u32 daynight_ratio = client->getEnv().getDayNightRatio();
510 finalColorBlend(c, day, night, daynight_ratio);
512 // Modify final color a bit with time
513 u32 timer = porting::getTimeMs() % 5000;
514 float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
515 float sin_r = 0.08 * sin(timerf);
516 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
517 float sin_b = 0.08 * sin(timerf + irr::core::PI);
518 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
519 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
520 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
522 // Set mesh final color
523 hud->setSelectionMeshColor(c);
528 /* Profiler display */
530 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
531 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
533 if (show_profiler == 0) {
534 guitext_profiler->setVisible(false);
537 std::ostringstream os(std::ios_base::binary);
538 g_profiler->printPage(os, show_profiler, show_profiler_max);
539 std::wstring text = utf8_to_wide(os.str());
540 guitext_profiler->setText(text.c_str());
541 guitext_profiler->setVisible(true);
543 s32 w = fe->getTextWidth(text.c_str());
548 unsigned text_height = fe->getTextHeight();
550 core::position2di upper_left, lower_right;
553 upper_left.Y = (text_height + 5) * 2;
554 lower_right.X = 12 + w;
555 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
557 if (lower_right.Y > screen_height * 2 / 3)
558 lower_right.Y = screen_height * 2 / 3;
560 core::rect<s32> rect(upper_left, lower_right);
562 guitext_profiler->setRelativePosition(rect);
563 guitext_profiler->setVisible(true);
571 Profiler::GraphValues values;
577 Meta(float initial = 0,
578 video::SColor color = video::SColor(255, 255, 255, 255)):
584 std::deque<Piece> m_log;
592 void put(const Profiler::GraphValues &values)
595 piece.values = values;
596 m_log.push_back(piece);
598 while (m_log.size() > m_log_max_size)
599 m_log.erase(m_log.begin());
602 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
603 gui::IGUIFont *font) const
605 std::map<std::string, Meta> m_meta;
607 for (std::deque<Piece>::const_iterator k = m_log.begin();
608 k != m_log.end(); ++k) {
609 const Piece &piece = *k;
611 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
612 i != piece.values.end(); ++i) {
613 const std::string &id = i->first;
614 const float &value = i->second;
615 std::map<std::string, Meta>::iterator j =
618 if (j == m_meta.end()) {
619 m_meta[id] = Meta(value);
623 if (value < j->second.min)
624 j->second.min = value;
626 if (value > j->second.max)
627 j->second.max = value;
632 static const video::SColor usable_colors[] = {
633 video::SColor(255, 255, 100, 100),
634 video::SColor(255, 90, 225, 90),
635 video::SColor(255, 100, 100, 255),
636 video::SColor(255, 255, 150, 50),
637 video::SColor(255, 220, 220, 100)
639 static const u32 usable_colors_count =
640 sizeof(usable_colors) / sizeof(*usable_colors);
641 u32 next_color_i = 0;
643 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
644 i != m_meta.end(); ++i) {
645 Meta &meta = i->second;
646 video::SColor color(255, 200, 200, 200);
648 if (next_color_i < usable_colors_count)
649 color = usable_colors[next_color_i++];
655 s32 textx = x_left + m_log_max_size + 15;
656 s32 textx2 = textx + 200 - 15;
659 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
660 i != m_meta.end(); ++i) {
661 const std::string &id = i->first;
662 const Meta &meta = i->second;
664 s32 y = y_bottom - meta_i * 50;
665 float show_min = meta.min;
666 float show_max = meta.max;
668 if (show_min >= -0.0001 && show_max >= -0.0001) {
669 if (show_min <= show_max * 0.5)
675 snprintf(buf, 10, "%.3g", show_max);
676 font->draw(utf8_to_wide(buf).c_str(),
677 core::rect<s32>(textx, y - graphh,
678 textx2, y - graphh + texth),
680 snprintf(buf, 10, "%.3g", show_min);
681 font->draw(utf8_to_wide(buf).c_str(),
682 core::rect<s32>(textx, y - texth,
685 font->draw(utf8_to_wide(id).c_str(),
686 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
687 textx2, y - graphh / 2 + texth / 2),
690 s32 graph1h = graphh;
691 bool relativegraph = (show_min != 0 && show_min != show_max);
692 float lastscaledvalue = 0.0;
693 bool lastscaledvalue_exists = false;
695 for (std::deque<Piece>::const_iterator j = m_log.begin();
696 j != m_log.end(); ++j) {
697 const Piece &piece = *j;
699 bool value_exists = false;
700 Profiler::GraphValues::const_iterator k =
701 piece.values.find(id);
703 if (k != piece.values.end()) {
710 lastscaledvalue_exists = false;
714 float scaledvalue = 1.0;
716 if (show_max != show_min)
717 scaledvalue = (value - show_min) / (show_max - show_min);
719 if (scaledvalue == 1.0 && value == 0) {
721 lastscaledvalue_exists = false;
726 if (lastscaledvalue_exists) {
727 s32 ivalue1 = lastscaledvalue * graph1h;
728 s32 ivalue2 = scaledvalue * graph1h;
729 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
730 v2s32(x, graph1y - ivalue2), meta.color);
733 lastscaledvalue = scaledvalue;
734 lastscaledvalue_exists = true;
736 s32 ivalue = scaledvalue * graph1h;
737 driver->draw2DLine(v2s32(x, graph1y),
738 v2s32(x, graph1y - ivalue), meta.color);
749 class NodeDugEvent: public MtEvent
755 NodeDugEvent(v3s16 p, MapNode n):
759 const char *getType() const
767 ISoundManager *m_sound;
768 INodeDefManager *m_ndef;
770 float m_player_step_timer;
772 SimpleSoundSpec m_player_step_sound;
773 SimpleSoundSpec m_player_leftpunch_sound;
774 SimpleSoundSpec m_player_rightpunch_sound;
776 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
779 m_player_step_timer(0)
783 void playPlayerStep()
785 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
786 m_player_step_timer = 0.03;
787 m_sound->playSound(m_player_step_sound, false);
791 static void viewBobbingStep(MtEvent *e, void *data)
793 SoundMaker *sm = (SoundMaker *)data;
794 sm->playPlayerStep();
797 static void playerRegainGround(MtEvent *e, void *data)
799 SoundMaker *sm = (SoundMaker *)data;
800 sm->playPlayerStep();
803 static void playerJump(MtEvent *e, void *data)
805 //SoundMaker *sm = (SoundMaker*)data;
808 static void cameraPunchLeft(MtEvent *e, void *data)
810 SoundMaker *sm = (SoundMaker *)data;
811 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
814 static void cameraPunchRight(MtEvent *e, void *data)
816 SoundMaker *sm = (SoundMaker *)data;
817 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
820 static void nodeDug(MtEvent *e, void *data)
822 SoundMaker *sm = (SoundMaker *)data;
823 NodeDugEvent *nde = (NodeDugEvent *)e;
824 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
827 static void playerDamage(MtEvent *e, void *data)
829 SoundMaker *sm = (SoundMaker *)data;
830 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
833 static void playerFallingDamage(MtEvent *e, void *data)
835 SoundMaker *sm = (SoundMaker *)data;
836 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
839 void registerReceiver(MtEventManager *mgr)
841 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
842 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
843 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
844 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
845 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
846 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
847 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
848 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
851 void step(float dtime)
853 m_player_step_timer -= dtime;
857 // Locally stored sounds don't need to be preloaded because of this
858 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
860 std::set<std::string> m_fetched;
862 void fetchSounds(const std::string &name,
863 std::set<std::string> &dst_paths,
864 std::set<std::string> &dst_datas)
866 if (m_fetched.count(name))
869 m_fetched.insert(name);
870 std::string base = porting::path_share + DIR_DELIM + "testsounds";
871 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
872 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
873 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
874 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
875 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
876 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
877 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
878 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
879 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
880 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
881 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
885 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
888 bool *m_force_fog_off;
894 void onSettingsChange(const std::string &name)
896 if (name == "enable_fog")
897 m_fogEnabled = g_settings->getBool("enable_fog");
900 static void SettingsCallback(const std::string &name, void *userdata)
902 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
905 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
906 f32 *fog_range, Client *client) :
908 m_force_fog_off(force_fog_off),
909 m_fog_range(fog_range),
912 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
913 m_fogEnabled = g_settings->getBool("enable_fog");
916 ~GameGlobalShaderConstantSetter()
918 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
921 virtual void onSetConstants(video::IMaterialRendererServices *services,
928 video::SColor bgcolor = m_sky->getBgColor();
929 video::SColorf bgcolorf(bgcolor);
930 float bgcolorfa[4] = {
936 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
939 float fog_distance = 10000 * BS;
941 if (m_fogEnabled && !*m_force_fog_off)
942 fog_distance = *m_fog_range;
944 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
947 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
948 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
949 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
951 u32 animation_timer = porting::getTimeMs() % 100000;
952 float animation_timer_f = (float)animation_timer / 100000.0;
953 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
954 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
956 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
957 v3f eye_position = player->getEyePosition();
958 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
959 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
961 v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
962 services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
964 // Uniform sampler layers
965 // before 1.8 there isn't a "integer interface", only float
966 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
970 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
971 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
972 services->setPixelShaderConstant("textureFlags" , (irr::f32 *)&layer2, 1);
977 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
978 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
979 services->setPixelShaderConstant("textureFlags" , (irr::s32 *)&layer2, 1);
984 bool nodePlacementPrediction(Client &client,
985 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
987 std::string prediction = playeritem_def.node_placement_prediction;
988 INodeDefManager *nodedef = client.ndef();
989 ClientMap &map = client.getEnv().getClientMap();
991 bool is_valid_position;
993 node = map.getNodeNoEx(nodepos, &is_valid_position);
994 if (!is_valid_position)
997 if (prediction != "" && !nodedef->get(node).rightclickable) {
998 verbosestream << "Node placement prediction for "
999 << playeritem_def.name << " is "
1000 << prediction << std::endl;
1001 v3s16 p = neighbourpos;
1003 // Place inside node itself if buildable_to
1004 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
1005 if (is_valid_position)
1007 if (nodedef->get(n_under).buildable_to)
1010 node = map.getNodeNoEx(p, &is_valid_position);
1011 if (is_valid_position &&!nodedef->get(node).buildable_to)
1016 // Find id of predicted node
1018 bool found = nodedef->getId(prediction, id);
1021 errorstream << "Node placement prediction failed for "
1022 << playeritem_def.name << " (places "
1024 << ") - Name not known" << std::endl;
1028 // Predict param2 for facedir and wallmounted nodes
1031 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
1032 v3s16 dir = nodepos - neighbourpos;
1034 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
1035 param2 = dir.Y < 0 ? 1 : 0;
1036 } else if (abs(dir.X) > abs(dir.Z)) {
1037 param2 = dir.X < 0 ? 3 : 2;
1039 param2 = dir.Z < 0 ? 5 : 4;
1043 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
1044 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
1046 if (abs(dir.X) > abs(dir.Z)) {
1047 param2 = dir.X < 0 ? 3 : 1;
1049 param2 = dir.Z < 0 ? 2 : 0;
1053 assert(param2 <= 5);
1055 //Check attachment if node is in group attached_node
1056 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
1057 static v3s16 wallmounted_dirs[8] = {
1067 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
1068 pp = p + wallmounted_dirs[param2];
1070 pp = p + v3s16(0, -1, 0);
1072 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
1076 // Add node to client map
1077 MapNode n(id, 0, param2);
1080 LocalPlayer *player = client.getEnv().getLocalPlayer();
1082 // Dont place node when player would be inside new node
1083 // NOTE: This is to be eventually implemented by a mod as client-side Lua
1084 if (!nodedef->get(n).walkable ||
1085 g_settings->getBool("enable_build_where_you_stand") ||
1086 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1087 (nodedef->get(n).walkable &&
1088 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1089 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1091 // This triggers the required mesh update too
1092 client.addNode(p, n);
1095 } catch (InvalidPositionException &e) {
1096 errorstream << "Node placement prediction failed for "
1097 << playeritem_def.name << " (places "
1099 << ") - Position not loaded" << std::endl;
1106 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1107 InventoryManager *invmgr, IGameDef *gamedef,
1108 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1109 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1112 if (*cur_formspec == 0) {
1113 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1114 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1115 (*cur_formspec)->doPause = false;
1118 Caution: do not call (*cur_formspec)->drop() here --
1119 the reference might outlive the menu, so we will
1120 periodically check if *cur_formspec is the only
1121 remaining reference (i.e. the menu was removed)
1122 and delete it in that case.
1126 (*cur_formspec)->setFormSource(fs_src);
1127 (*cur_formspec)->setTextDest(txt_dest);
1132 #define SIZE_TAG "size[11,5.5]"
1134 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1137 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1138 InventoryManager *invmgr, IGameDef *gamedef,
1139 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1141 std::string formspec =
1142 std::string(FORMSPEC_VERSION_STRING) +
1144 "bgcolor[#320000b4;true]"
1145 "label[4.85,1.35;" + gettext("You died.") + "]"
1146 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1150 /* Note: FormspecFormSource and LocalFormspecHandler
1151 * are deleted by guiFormSpecMenu */
1152 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1153 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1155 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1158 /******************************************************************************/
1159 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1160 InventoryManager *invmgr, IGameDef *gamedef,
1161 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1162 bool singleplayermode)
1165 std::string control_text = strgettext("Default Controls:\n"
1166 "No menu visible:\n"
1167 "- single tap: button activate\n"
1168 "- double tap: place/use\n"
1169 "- slide finger: look around\n"
1170 "Menu/Inventory visible:\n"
1171 "- double tap (outside):\n"
1173 "- touch stack, touch slot:\n"
1175 "- touch&drag, tap 2nd finger\n"
1176 " --> place single item to slot\n"
1179 std::string control_text = strgettext("Default Controls:\n"
1181 "- Space: jump/climb\n"
1182 "- Shift: sneak/go down\n"
1185 "- Mouse: turn/look\n"
1186 "- Mouse left: dig/punch\n"
1187 "- Mouse right: place/use\n"
1188 "- Mouse wheel: select item\n"
1193 float ypos = singleplayermode ? 0.5 : 0.1;
1194 std::ostringstream os;
1196 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1197 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1198 << strgettext("Continue") << "]";
1200 if (!singleplayermode) {
1201 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1202 << strgettext("Change Password") << "]";
1206 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1207 << strgettext("Sound Volume") << "]";
1208 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1209 << strgettext("Change Keys") << "]";
1211 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1212 << strgettext("Exit to Menu") << "]";
1213 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1214 << strgettext("Exit to OS") << "]"
1215 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1216 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1217 << g_build_info << "\n"
1218 << "path_user = " << wrap_rows(porting::path_user, 20)
1222 /* Note: FormspecFormSource and LocalFormspecHandler *
1223 * are deleted by guiFormSpecMenu */
1224 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1225 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1227 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1228 std::string con("btn_continue");
1229 (*cur_formspec)->setFocus(con);
1230 (*cur_formspec)->doPause = true;
1233 /******************************************************************************/
1234 static void updateChat(Client &client, f32 dtime, bool show_debug,
1235 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1236 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1238 // Add chat log output for errors to be shown in chat
1239 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1241 // Get new messages from error log buffer
1242 while (!chat_log_error_buf.empty()) {
1243 chat_backend.addMessage(L"", utf8_to_wide(chat_log_error_buf.get()));
1246 // Get new messages from client
1247 std::wstring message;
1249 while (client.getChatMessage(message)) {
1250 chat_backend.addUnparsedMessage(message);
1253 // Remove old messages
1254 chat_backend.step(dtime);
1256 // Display all messages in a static text element
1257 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1258 std::wstring recent_chat = chat_backend.getRecentChat();
1259 unsigned int line_height = g_fontengine->getLineHeight();
1261 guitext_chat->setText(recent_chat.c_str());
1263 // Update gui element size and position
1264 s32 chat_y = 5 + line_height;
1267 chat_y += line_height;
1269 // first pass to calculate height of text to be set
1270 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1271 porting::getWindowSize().X - 20);
1272 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1273 guitext_chat->setRelativePosition(rect);
1275 //now use real height of text and adjust rect according to this size
1276 rect = core::rect<s32>(10, chat_y, width,
1277 chat_y + guitext_chat->getTextHeight());
1280 guitext_chat->setRelativePosition(rect);
1281 // Don't show chat if disabled or empty or profiler is enabled
1282 guitext_chat->setVisible(
1283 show_chat && recent_chat_count != 0 && !show_profiler);
1287 /****************************************************************************
1288 Fast key cache for main game loop
1289 ****************************************************************************/
1291 /* This is faster than using getKeySetting with the tradeoff that functions
1292 * using it must make sure that it's initialised before using it and there is
1293 * no error handling (for example bounds checking). This is really intended for
1294 * use only in the main running loop of the client (the_game()) where the faster
1295 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1296 * (e.g. formspecs) should continue using getKeySetting().
1300 KeyCache() { populate(); }
1315 KEYMAP_ID_INVENTORY,
1323 KEYMAP_ID_CINEMATIC,
1324 KEYMAP_ID_SCREENSHOT,
1325 KEYMAP_ID_TOGGLE_HUD,
1326 KEYMAP_ID_TOGGLE_CHAT,
1327 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1328 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1329 KEYMAP_ID_TOGGLE_DEBUG,
1330 KEYMAP_ID_TOGGLE_PROFILER,
1331 KEYMAP_ID_CAMERA_MODE,
1332 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1333 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1334 KEYMAP_ID_RANGESELECT,
1336 KEYMAP_ID_QUICKTUNE_NEXT,
1337 KEYMAP_ID_QUICKTUNE_PREV,
1338 KEYMAP_ID_QUICKTUNE_INC,
1339 KEYMAP_ID_QUICKTUNE_DEC,
1341 KEYMAP_ID_DEBUG_STACKS,
1343 // Fake keycode for array size and internal checks
1344 KEYMAP_INTERNAL_ENUM_COUNT
1351 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1354 void KeyCache::populate()
1356 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1357 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1358 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1359 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1360 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1361 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1362 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1364 key[KEYMAP_ID_AUTORUN] = getKeySetting("keymap_autorun");
1366 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1367 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1368 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1369 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1370 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1371 key[KEYMAP_ID_MINIMAP] = getKeySetting("keymap_minimap");
1372 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1373 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1374 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1375 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1376 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1377 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1378 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1379 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1380 = getKeySetting("keymap_toggle_force_fog_off");
1381 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1382 = getKeySetting("keymap_toggle_update_camera");
1383 key[KEYMAP_ID_TOGGLE_DEBUG]
1384 = getKeySetting("keymap_toggle_debug");
1385 key[KEYMAP_ID_TOGGLE_PROFILER]
1386 = getKeySetting("keymap_toggle_profiler");
1387 key[KEYMAP_ID_CAMERA_MODE]
1388 = getKeySetting("keymap_camera_mode");
1389 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1390 = getKeySetting("keymap_increase_viewing_range_min");
1391 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1392 = getKeySetting("keymap_decrease_viewing_range_min");
1393 key[KEYMAP_ID_RANGESELECT]
1394 = getKeySetting("keymap_rangeselect");
1396 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1397 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1398 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1399 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1401 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1405 /****************************************************************************
1407 ****************************************************************************/
1409 const float object_hit_delay = 0.2;
1412 u32 last_time, busy_time, sleep_time;
1416 /* The reason the following structs are not anonymous structs within the
1417 * class is that they are not used by the majority of member functions and
1418 * many functions that do require objects of thse types do not modify them
1419 * (so they can be passed as a const qualified parameter)
1421 struct CameraOrientation {
1422 f32 camera_yaw; // "right/left"
1423 f32 camera_pitch; // "up/down"
1426 struct GameRunData {
1429 PointedThing pointed_old;
1433 bool update_wielded_item_trigger;
1434 bool reset_jump_timer;
1435 float nodig_delay_timer;
1437 float dig_time_complete;
1438 float repeat_rightclick_timer;
1439 float object_hit_delay_timer;
1440 float time_from_last_punch;
1441 ClientActiveObject *selected_object;
1445 float update_draw_list_timer;
1446 float statustext_time;
1450 v3f update_draw_list_last_cam_dir;
1452 u32 profiler_current_page;
1453 u32 profiler_max_page; // Number of pages
1456 float time_of_day_smooth;
1460 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1468 Jitter dtime_jitter, busy_time_jitter;
1471 /* Flags that can, or may, change during main game loop
1473 struct VolatileRunFlags {
1480 bool show_profiler_graph;
1481 bool disable_camera_update;
1482 bool first_loop_after_window_activation;
1483 bool camera_offset_changed;
1487 /****************************************************************************
1489 ****************************************************************************/
1491 /* This is not intended to be a public class. If a public class becomes
1492 * desirable then it may be better to create another 'wrapper' class that
1493 * hides most of the stuff in this class (nothing in this class is required
1494 * by any other file) but exposes the public methods/data only.
1501 bool startup(bool *kill,
1503 InputHandler *input,
1504 IrrlichtDevice *device,
1505 const std::string &map_dir,
1506 const std::string &playername,
1507 const std::string &password,
1508 // If address is "", local server is used and address is updated
1509 std::string *address,
1511 std::string &error_message,
1513 ChatBackend *chat_backend,
1514 const SubgameSpec &gamespec, // Used for local game
1515 bool simple_singleplayer_mode);
1522 void extendedResourceCleanup();
1524 // Basic initialisation
1525 bool init(const std::string &map_dir, std::string *address,
1527 const SubgameSpec &gamespec);
1529 bool createSingleplayerServer(const std::string map_dir,
1530 const SubgameSpec &gamespec, u16 port, std::string *address);
1533 bool createClient(const std::string &playername,
1534 const std::string &password, std::string *address, u16 port);
1537 // Client connection
1538 bool connectToServer(const std::string &playername,
1539 const std::string &password, std::string *address, u16 port,
1540 bool *connect_ok, bool *aborted);
1541 bool getServerContent(bool *aborted);
1545 void updateInteractTimers(GameRunData *runData, f32 dtime);
1546 bool checkConnection();
1547 bool handleCallbacks();
1548 void processQueues();
1549 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1550 const FpsControl &draw_times, f32 dtime);
1551 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1553 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1555 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1557 void processKeyboardInput(VolatileRunFlags *flags,
1558 float *statustext_time,
1560 bool *reset_jump_timer,
1561 u32 *profiler_current_page,
1562 u32 profiler_max_page);
1563 void processItemSelection(u16 *new_playeritem);
1565 void dropSelectedItem();
1566 void openInventory();
1567 void openConsole(float height, const wchar_t *line=NULL);
1568 void toggleFreeMove(float *statustext_time);
1569 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1570 void toggleFast(float *statustext_time);
1571 void toggleNoClip(float *statustext_time);
1572 void toggleCinematic(float *statustext_time);
1573 void toggleAutorun(float *statustext_time);
1575 void toggleChat(float *statustext_time, bool *flag);
1576 void toggleHud(float *statustext_time, bool *flag);
1577 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1578 bool shift_pressed);
1579 void toggleFog(float *statustext_time, bool *flag);
1580 void toggleDebug(float *statustext_time, bool *show_debug,
1581 bool *show_profiler_graph);
1582 void toggleUpdateCamera(float *statustext_time, bool *flag);
1583 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1584 u32 profiler_max_page);
1586 void increaseViewRange(float *statustext_time);
1587 void decreaseViewRange(float *statustext_time);
1588 void toggleFullViewRange(float *statustext_time);
1590 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1591 void updateCameraOrientation(CameraOrientation *cam,
1592 const VolatileRunFlags &flags);
1593 void updatePlayerControl(const CameraOrientation &cam);
1594 void step(f32 *dtime);
1595 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1596 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1597 float time_from_last_punch);
1598 void updateSound(f32 dtime);
1599 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1601 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1602 void handlePointingAtNode(GameRunData *runData,
1603 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1604 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1605 void handlePointingAtObject(GameRunData *runData,
1606 const PointedThing &pointed, const ItemStack &playeritem,
1607 const v3f &player_position, bool show_debug);
1608 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1609 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1611 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1612 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1613 void updateGui(float *statustext_time, const RunStats &stats,
1614 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1615 const CameraOrientation &cam);
1616 void updateProfilerGraphs(ProfilerGraph *graph);
1619 void limitFps(FpsControl *fps_timings, f32 *dtime);
1621 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1622 bool draw_clouds = true);
1624 static void settingChangedCallback(const std::string &setting_name, void *data);
1625 void readSettings();
1628 void handleAndroidChatInput();
1632 InputHandler *input;
1637 IWritableTextureSource *texture_src;
1638 IWritableShaderSource *shader_src;
1640 // When created, these will be filled with data received from the server
1641 IWritableItemDefManager *itemdef_manager;
1642 IWritableNodeDefManager *nodedef_manager;
1644 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1645 ISoundManager *sound;
1646 bool sound_is_dummy;
1647 SoundMaker *soundmaker;
1649 ChatBackend *chat_backend;
1651 GUIFormSpecMenu *current_formspec;
1653 EventManager *eventmgr;
1654 QuicktuneShortcutter *quicktune;
1656 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1657 MapDrawControl *draw_control;
1659 Clouds *clouds; // Free using ->Drop()
1660 Sky *sky; // Free using ->Drop()
1661 Inventory *local_inventory;
1666 This class does take ownership/responsibily for cleaning up etc of any of
1667 these items (e.g. device)
1669 IrrlichtDevice *device;
1670 video::IVideoDriver *driver;
1671 scene::ISceneManager *smgr;
1673 std::string *error_message;
1674 bool *reconnect_requested;
1675 IGameDef *gamedef; // Convenience (same as *client)
1676 scene::ISceneNode *skybox;
1679 bool simple_singleplayer_mode;
1682 /* Pre-calculated values
1684 int crack_animation_length;
1688 gui::IGUIStaticText *guitext; // First line of debug text
1689 gui::IGUIStaticText *guitext2; // Second line of debug text
1690 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1691 gui::IGUIStaticText *guitext_status;
1692 gui::IGUIStaticText *guitext_chat; // Chat text
1693 gui::IGUIStaticText *guitext_profiler; // Profiler text
1695 std::wstring infotext;
1696 std::wstring statustext;
1700 IntervalLimiter profiler_interval;
1703 * TODO: Local caching of settings is not optimal and should at some stage
1704 * be updated to use a global settings object for getting thse values
1705 * (as opposed to the this local caching). This can be addressed in
1708 bool m_cache_doubletap_jump;
1709 bool m_cache_enable_clouds;
1710 bool m_cache_enable_particles;
1711 bool m_cache_enable_fog;
1712 f32 m_cache_mouse_sensitivity;
1713 f32 m_repeat_right_click_time;
1716 bool m_cache_hold_aux1;
1717 bool m_android_chat_open;
1726 itemdef_manager(NULL),
1727 nodedef_manager(NULL),
1729 sound_is_dummy(false),
1732 current_formspec(NULL),
1735 gui_chat_console(NULL),
1740 local_inventory(NULL),
1744 g_settings->registerChangedCallback("doubletap_jump",
1745 &settingChangedCallback, this);
1746 g_settings->registerChangedCallback("enable_clouds",
1747 &settingChangedCallback, this);
1748 g_settings->registerChangedCallback("enable_particles",
1749 &settingChangedCallback, this);
1750 g_settings->registerChangedCallback("enable_fog",
1751 &settingChangedCallback, this);
1752 g_settings->registerChangedCallback("mouse_sensitivity",
1753 &settingChangedCallback, this);
1754 g_settings->registerChangedCallback("repeat_rightclick_time",
1755 &settingChangedCallback, this);
1760 m_cache_hold_aux1 = false; // This is initialised properly later
1767 /****************************************************************************
1769 ****************************************************************************/
1775 if (!sound_is_dummy)
1778 delete server; // deleted first to stop all server threads
1781 delete local_inventory;
1787 delete nodedef_manager;
1788 delete itemdef_manager;
1789 delete draw_control;
1791 extendedResourceCleanup();
1793 g_settings->deregisterChangedCallback("doubletap_jump",
1794 &settingChangedCallback, this);
1795 g_settings->deregisterChangedCallback("enable_clouds",
1796 &settingChangedCallback, this);
1797 g_settings->deregisterChangedCallback("enable_particles",
1798 &settingChangedCallback, this);
1799 g_settings->deregisterChangedCallback("enable_fog",
1800 &settingChangedCallback, this);
1801 g_settings->deregisterChangedCallback("mouse_sensitivity",
1802 &settingChangedCallback, this);
1803 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1804 &settingChangedCallback, this);
1807 bool Game::startup(bool *kill,
1809 InputHandler *input,
1810 IrrlichtDevice *device,
1811 const std::string &map_dir,
1812 const std::string &playername,
1813 const std::string &password,
1814 std::string *address, // can change if simple_singleplayer_mode
1816 std::string &error_message,
1818 ChatBackend *chat_backend,
1819 const SubgameSpec &gamespec,
1820 bool simple_singleplayer_mode)
1823 this->device = device;
1825 this->error_message = &error_message;
1826 this->reconnect_requested = reconnect;
1827 this->random_input = random_input;
1828 this->input = input;
1829 this->chat_backend = chat_backend;
1830 this->simple_singleplayer_mode = simple_singleplayer_mode;
1832 driver = device->getVideoDriver();
1833 smgr = device->getSceneManager();
1835 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1837 if (!init(map_dir, address, port, gamespec))
1840 if (!createClient(playername, password, address, port))
1849 ProfilerGraph graph;
1850 RunStats stats = { 0 };
1851 CameraOrientation cam_view_target = { 0 };
1852 CameraOrientation cam_view = { 0 };
1853 GameRunData runData = { 0 };
1854 FpsControl draw_times = { 0 };
1855 VolatileRunFlags flags = { 0 };
1856 f32 dtime; // in seconds
1858 runData.time_from_last_punch = 10.0;
1859 runData.profiler_max_page = 3;
1860 runData.update_wielded_item_trigger = true;
1862 flags.show_chat = true;
1863 flags.show_hud = true;
1864 flags.show_minimap = g_settings->getBool("enable_minimap");
1865 flags.show_debug = g_settings->getBool("show_debug");
1866 flags.invert_mouse = g_settings->getBool("invert_mouse");
1867 flags.first_loop_after_window_activation = true;
1869 /* Clear the profiler */
1870 Profiler::GraphValues dummyvalues;
1871 g_profiler->graphGet(dummyvalues);
1873 draw_times.last_time = device->getTimer()->getTime();
1875 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1877 &flags.force_fog_off,
1881 set_light_table(g_settings->getFloat("display_gamma"));
1884 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1885 && client->checkPrivilege("fast");
1888 while (device->run()
1889 && !(*kill || g_gamecallback->shutdown_requested
1890 || (server && server->getShutdownRequested()))) {
1892 /* Must be called immediately after a device->run() call because it
1893 * uses device->getTimer()->getTime()
1895 limitFps(&draw_times, &dtime);
1897 updateStats(&stats, draw_times, dtime);
1898 updateInteractTimers(&runData, dtime);
1900 if (!checkConnection())
1902 if (!handleCallbacks())
1908 hud->resizeHotbar();
1910 updateProfilers(runData, stats, draw_times, dtime);
1911 processUserInput(&flags, &runData, dtime);
1912 // Update camera before player movement to avoid camera lag of one frame
1913 updateCameraDirection(&cam_view_target, &flags);
1914 float cam_smoothing = 0;
1915 if (g_settings->getBool("cinematic"))
1916 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1918 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1919 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1920 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1921 cam_view.camera_yaw) * cam_smoothing;
1922 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1923 cam_view.camera_pitch) * cam_smoothing;
1924 updatePlayerControl(cam_view);
1926 processClientEvents(&cam_view_target, &runData.damage_flash);
1927 updateCamera(&flags, draw_times.busy_time, dtime,
1928 runData.time_from_last_punch);
1930 processPlayerInteraction(&runData, dtime, flags.show_hud,
1932 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1933 updateProfilerGraphs(&graph);
1935 // Update if minimap has been disabled by the server
1936 flags.show_minimap &= !client->isMinimapDisabledByServer();
1941 void Game::shutdown()
1943 if (g_settings->get("3d_mode") == "pageflip") {
1944 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1947 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1952 if (gui_chat_console)
1953 gui_chat_console->drop();
1959 while (g_menumgr.menuCount() > 0) {
1960 g_menumgr.m_stack.front()->setVisible(false);
1961 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1964 if (current_formspec) {
1965 current_formspec->drop();
1966 current_formspec = NULL;
1969 chat_backend->addMessage(L"", L"# Disconnected.");
1970 chat_backend->addMessage(L"", L"");
1974 while (!client->isShutdown()) {
1975 assert(texture_src != NULL);
1976 assert(shader_src != NULL);
1977 texture_src->processQueue();
1978 shader_src->processQueue();
1985 /****************************************************************************/
1986 /****************************************************************************
1988 ****************************************************************************/
1989 /****************************************************************************/
1992 const std::string &map_dir,
1993 std::string *address,
1995 const SubgameSpec &gamespec)
1997 showOverlayMessage(wgettext("Loading..."), 0, 0);
1999 texture_src = createTextureSource(device);
2000 shader_src = createShaderSource(device);
2002 itemdef_manager = createItemDefManager();
2003 nodedef_manager = createNodeDefManager();
2005 eventmgr = new EventManager();
2006 quicktune = new QuicktuneShortcutter();
2008 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
2009 && eventmgr && quicktune))
2015 // Create a server if not connecting to an existing one
2016 if (*address == "") {
2017 if (!createSingleplayerServer(map_dir, gamespec, port, address))
2024 bool Game::initSound()
2027 if (g_settings->getBool("enable_sound")) {
2028 infostream << "Attempting to use OpenAL audio" << std::endl;
2029 sound = createOpenALSoundManager(&soundfetcher);
2031 infostream << "Failed to initialize OpenAL audio" << std::endl;
2033 infostream << "Sound disabled." << std::endl;
2037 infostream << "Using dummy audio." << std::endl;
2038 sound = &dummySoundManager;
2039 sound_is_dummy = true;
2042 soundmaker = new SoundMaker(sound, nodedef_manager);
2046 soundmaker->registerReceiver(eventmgr);
2051 bool Game::createSingleplayerServer(const std::string map_dir,
2052 const SubgameSpec &gamespec, u16 port, std::string *address)
2054 showOverlayMessage(wgettext("Creating server..."), 0, 5);
2056 std::string bind_str = g_settings->get("bind_address");
2057 Address bind_addr(0, 0, 0, 0, port);
2059 if (g_settings->getBool("ipv6_server")) {
2060 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2064 bind_addr.Resolve(bind_str.c_str());
2065 } catch (ResolveError &e) {
2066 infostream << "Resolving bind address \"" << bind_str
2067 << "\" failed: " << e.what()
2068 << " -- Listening on all addresses." << std::endl;
2071 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2072 *error_message = "Unable to listen on " +
2073 bind_addr.serializeString() +
2074 " because IPv6 is disabled";
2075 errorstream << *error_message << std::endl;
2079 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2080 bind_addr.isIPv6());
2082 server->start(bind_addr);
2087 bool Game::createClient(const std::string &playername,
2088 const std::string &password, std::string *address, u16 port)
2090 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2092 draw_control = new MapDrawControl;
2096 bool could_connect, connect_aborted;
2098 if (!connectToServer(playername, password, address, port,
2099 &could_connect, &connect_aborted))
2102 if (!could_connect) {
2103 if (error_message->empty() && !connect_aborted) {
2104 // Should not happen if error messages are set properly
2105 *error_message = "Connection failed for unknown reason";
2106 errorstream << *error_message << std::endl;
2111 if (!getServerContent(&connect_aborted)) {
2112 if (error_message->empty() && !connect_aborted) {
2113 // Should not happen if error messages are set properly
2114 *error_message = "Connection failed for unknown reason";
2115 errorstream << *error_message << std::endl;
2120 // Update cached textures, meshes and materials
2121 client->afterContentReceived(device);
2125 camera = new Camera(smgr, *draw_control, gamedef);
2126 if (!camera || !camera->successfullyCreated(*error_message))
2128 client->setCamera(camera);
2132 if (m_cache_enable_clouds) {
2133 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2135 *error_message = "Memory allocation error (clouds)";
2136 errorstream << *error_message << std::endl;
2143 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2144 skybox = NULL; // This is used/set later on in the main run loop
2146 local_inventory = new Inventory(itemdef_manager);
2148 if (!(sky && local_inventory)) {
2149 *error_message = "Memory allocation error (sky or local inventory)";
2150 errorstream << *error_message << std::endl;
2154 /* Pre-calculated values
2156 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2158 v2u32 size = t->getOriginalSize();
2159 crack_animation_length = size.Y / size.X;
2161 crack_animation_length = 5;
2167 /* Set window caption
2169 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2171 str += driver->getName();
2173 device->setWindowCaption(str.c_str());
2175 LocalPlayer *player = client->getEnv().getLocalPlayer();
2176 player->hurt_tilt_timer = 0;
2177 player->hurt_tilt_strength = 0;
2179 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2182 *error_message = "Memory error: could not create HUD";
2183 errorstream << *error_message << std::endl;
2187 mapper = client->getMapper();
2188 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2193 bool Game::initGui()
2195 // First line of debug text
2196 guitext = guienv->addStaticText(
2197 utf8_to_wide(PROJECT_NAME_C).c_str(),
2198 core::rect<s32>(0, 0, 0, 0),
2199 false, false, guiroot);
2201 // Second line of debug text
2202 guitext2 = guienv->addStaticText(
2204 core::rect<s32>(0, 0, 0, 0),
2205 false, false, guiroot);
2207 // At the middle of the screen
2208 // Object infos are shown in this
2209 guitext_info = guienv->addStaticText(
2211 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2212 false, true, guiroot);
2214 // Status text (displays info when showing and hiding GUI stuff, etc.)
2215 guitext_status = guienv->addStaticText(
2217 core::rect<s32>(0, 0, 0, 0),
2218 false, false, guiroot);
2219 guitext_status->setVisible(false);
2222 guitext_chat = guienv->addStaticText(
2224 core::rect<s32>(0, 0, 0, 0),
2225 //false, false); // Disable word wrap as of now
2226 false, true, guiroot);
2227 // Remove stale "recent" chat messages from previous connections
2228 chat_backend->clearRecentChat();
2230 // Chat backend and console
2231 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2232 -1, chat_backend, client, &g_menumgr);
2233 if (!gui_chat_console) {
2234 *error_message = "Could not allocate memory for chat console";
2235 errorstream << *error_message << std::endl;
2239 // Profiler text (size is updated when text is updated)
2240 guitext_profiler = guienv->addStaticText(
2242 core::rect<s32>(0, 0, 0, 0),
2243 false, false, guiroot);
2244 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2245 guitext_profiler->setVisible(false);
2246 guitext_profiler->setWordWrap(true);
2248 #ifdef HAVE_TOUCHSCREENGUI
2250 if (g_touchscreengui)
2251 g_touchscreengui->init(texture_src);
2258 bool Game::connectToServer(const std::string &playername,
2259 const std::string &password, std::string *address, u16 port,
2260 bool *connect_ok, bool *aborted)
2262 *connect_ok = false; // Let's not be overly optimistic
2264 bool local_server_mode = false;
2266 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2268 Address connect_address(0, 0, 0, 0, port);
2271 connect_address.Resolve(address->c_str());
2273 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2274 //connect_address.Resolve("localhost");
2275 if (connect_address.isIPv6()) {
2276 IPv6AddressBytes addr_bytes;
2277 addr_bytes.bytes[15] = 1;
2278 connect_address.setAddress(&addr_bytes);
2280 connect_address.setAddress(127, 0, 0, 1);
2282 local_server_mode = true;
2284 } catch (ResolveError &e) {
2285 *error_message = std::string("Couldn't resolve address: ") + e.what();
2286 errorstream << *error_message << std::endl;
2290 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2291 *error_message = "Unable to connect to " +
2292 connect_address.serializeString() +
2293 " because IPv6 is disabled";
2294 errorstream << *error_message << std::endl;
2298 client = new Client(device,
2299 playername.c_str(), password,
2300 *draw_control, texture_src, shader_src,
2301 itemdef_manager, nodedef_manager, sound, eventmgr,
2302 connect_address.isIPv6());
2307 gamedef = client; // Client acts as our GameDef
2309 infostream << "Connecting to server at ";
2310 connect_address.print(&infostream);
2311 infostream << std::endl;
2313 client->connect(connect_address, *address,
2314 simple_singleplayer_mode || local_server_mode);
2317 Wait for server to accept connection
2323 FpsControl fps_control = { 0 };
2325 f32 wait_time = 0; // in seconds
2327 fps_control.last_time = device->getTimer()->getTime();
2329 while (device->run()) {
2331 limitFps(&fps_control, &dtime);
2333 // Update client and server
2334 client->step(dtime);
2337 server->step(dtime);
2340 if (client->getState() == LC_Init) {
2346 if (client->accessDenied()) {
2347 *error_message = "Access denied. Reason: "
2348 + client->accessDeniedReason();
2349 *reconnect_requested = client->reconnectRequested();
2350 errorstream << *error_message << std::endl;
2354 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2356 infostream << "Connect aborted [Escape]" << std::endl;
2361 // Only time out if we aren't waiting for the server we started
2362 if ((*address != "") && (wait_time > 10)) {
2363 *error_message = "Connection timed out.";
2364 errorstream << *error_message << std::endl;
2369 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2371 } catch (con::PeerNotFoundException &e) {
2372 // TODO: Should something be done here? At least an info/error
2380 bool Game::getServerContent(bool *aborted)
2384 FpsControl fps_control = { 0 };
2385 f32 dtime; // in seconds
2387 fps_control.last_time = device->getTimer()->getTime();
2389 while (device->run()) {
2391 limitFps(&fps_control, &dtime);
2393 // Update client and server
2394 client->step(dtime);
2397 server->step(dtime);
2400 if (client->mediaReceived() && client->itemdefReceived() &&
2401 client->nodedefReceived()) {
2406 if (!checkConnection())
2409 if (client->getState() < LC_Init) {
2410 *error_message = "Client disconnected";
2411 errorstream << *error_message << std::endl;
2415 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2417 infostream << "Connect aborted [Escape]" << std::endl;
2424 if (!client->itemdefReceived()) {
2425 const wchar_t *text = wgettext("Item definitions...");
2427 draw_load_screen(text, device, guienv, dtime, progress);
2429 } else if (!client->nodedefReceived()) {
2430 const wchar_t *text = wgettext("Node definitions...");
2432 draw_load_screen(text, device, guienv, dtime, progress);
2435 std::stringstream message;
2436 message.precision(3);
2437 message << gettext("Media...");
2439 if ((USE_CURL == 0) ||
2440 (!g_settings->getBool("enable_remote_media_server"))) {
2441 float cur = client->getCurRate();
2442 std::string cur_unit = gettext("KiB/s");
2446 cur_unit = gettext("MiB/s");
2449 message << " (" << cur << ' ' << cur_unit << ")";
2452 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2453 draw_load_screen(utf8_to_wide(message.str()), device,
2454 guienv, dtime, progress);
2462 /****************************************************************************/
2463 /****************************************************************************
2465 ****************************************************************************/
2466 /****************************************************************************/
2468 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2470 if (runData->nodig_delay_timer >= 0)
2471 runData->nodig_delay_timer -= dtime;
2473 if (runData->object_hit_delay_timer >= 0)
2474 runData->object_hit_delay_timer -= dtime;
2476 runData->time_from_last_punch += dtime;
2480 /* returns false if game should exit, otherwise true
2482 inline bool Game::checkConnection()
2484 if (client->accessDenied()) {
2485 *error_message = "Access denied. Reason: "
2486 + client->accessDeniedReason();
2487 *reconnect_requested = client->reconnectRequested();
2488 errorstream << *error_message << std::endl;
2496 /* returns false if game should exit, otherwise true
2498 inline bool Game::handleCallbacks()
2500 if (g_gamecallback->disconnect_requested) {
2501 g_gamecallback->disconnect_requested = false;
2505 if (g_gamecallback->changepassword_requested) {
2506 (new GUIPasswordChange(guienv, guiroot, -1,
2507 &g_menumgr, client))->drop();
2508 g_gamecallback->changepassword_requested = false;
2511 if (g_gamecallback->changevolume_requested) {
2512 (new GUIVolumeChange(guienv, guiroot, -1,
2513 &g_menumgr, client))->drop();
2514 g_gamecallback->changevolume_requested = false;
2517 if (g_gamecallback->keyconfig_requested) {
2518 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2519 &g_menumgr))->drop();
2520 g_gamecallback->keyconfig_requested = false;
2523 if (g_gamecallback->keyconfig_changed) {
2524 keycache.populate(); // update the cache with new settings
2525 g_gamecallback->keyconfig_changed = false;
2532 void Game::processQueues()
2534 texture_src->processQueue();
2535 itemdef_manager->processQueue(gamedef);
2536 shader_src->processQueue();
2540 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2541 const FpsControl &draw_times, f32 dtime)
2543 float profiler_print_interval =
2544 g_settings->getFloat("profiler_print_interval");
2545 bool print_to_log = true;
2547 if (profiler_print_interval == 0) {
2548 print_to_log = false;
2549 profiler_print_interval = 5;
2552 if (profiler_interval.step(dtime, profiler_print_interval)) {
2554 infostream << "Profiler:" << std::endl;
2555 g_profiler->print(infostream);
2558 update_profiler_gui(guitext_profiler, g_fontengine,
2559 runData.profiler_current_page, runData.profiler_max_page,
2560 driver->getScreenSize().Height);
2562 g_profiler->clear();
2565 addProfilerGraphs(stats, draw_times, dtime);
2569 void Game::addProfilerGraphs(const RunStats &stats,
2570 const FpsControl &draw_times, f32 dtime)
2572 g_profiler->graphAdd("mainloop_other",
2573 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2575 if (draw_times.sleep_time != 0)
2576 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2577 g_profiler->graphAdd("mainloop_dtime", dtime);
2579 g_profiler->add("Elapsed time", dtime);
2580 g_profiler->avg("FPS", 1. / dtime);
2584 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2591 /* Time average and jitter calculation
2593 jp = &stats->dtime_jitter;
2594 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2596 jitter = dtime - jp->avg;
2598 if (jitter > jp->max)
2601 jp->counter += dtime;
2603 if (jp->counter > 0.0) {
2605 jp->max_sample = jp->max;
2606 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2610 /* Busytime average and jitter calculation
2612 jp = &stats->busy_time_jitter;
2613 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2615 jitter = draw_times.busy_time - jp->avg;
2617 if (jitter > jp->max)
2619 if (jitter < jp->min)
2622 jp->counter += dtime;
2624 if (jp->counter > 0.0) {
2626 jp->max_sample = jp->max;
2627 jp->min_sample = jp->min;
2635 /****************************************************************************
2637 ****************************************************************************/
2639 void Game::processUserInput(VolatileRunFlags *flags,
2640 GameRunData *runData, f32 dtime)
2642 // Reset input if window not active or some menu is active
2643 if (device->isWindowActive() == false
2644 || noMenuActive() == false
2645 || guienv->hasFocus(gui_chat_console)) {
2647 #ifdef HAVE_TOUCHSCREENGUI
2648 g_touchscreengui->hide();
2651 #ifdef HAVE_TOUCHSCREENGUI
2652 else if (g_touchscreengui) {
2653 /* on touchscreengui step may generate own input events which ain't
2654 * what we want in case we just did clear them */
2655 g_touchscreengui->step(dtime);
2659 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2660 gui_chat_console->closeConsoleAtOnce();
2663 // Input handler step() (used by the random input generator)
2667 if (current_formspec != NULL)
2668 current_formspec->getAndroidUIInput();
2670 handleAndroidChatInput();
2673 // Increase timer for double tap of "keymap_jump"
2674 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2675 runData->jump_timer += dtime;
2677 processKeyboardInput(
2679 &runData->statustext_time,
2680 &runData->jump_timer,
2681 &runData->reset_jump_timer,
2682 &runData->profiler_current_page,
2683 runData->profiler_max_page);
2685 processItemSelection(&runData->new_playeritem);
2689 void Game::processKeyboardInput(VolatileRunFlags *flags,
2690 float *statustext_time,
2692 bool *reset_jump_timer,
2693 u32 *profiler_current_page,
2694 u32 profiler_max_page)
2697 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2699 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2701 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_AUTORUN])) {
2702 toggleAutorun(statustext_time);
2703 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2705 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2706 if (!gui_chat_console->isOpenInhibited()) {
2707 show_pause_menu(¤t_formspec, client, gamedef,
2708 texture_src, device, simple_singleplayer_mode);
2710 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2711 openConsole(0.2, L"");
2712 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2713 openConsole(0.2, L"/");
2714 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2716 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2717 toggleFreeMove(statustext_time);
2718 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2719 toggleFreeMoveAlt(statustext_time, jump_timer);
2720 *reset_jump_timer = true;
2721 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2722 toggleFast(statustext_time);
2723 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2724 toggleNoClip(statustext_time);
2725 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2726 toggleCinematic(statustext_time);
2727 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2728 client->makeScreenshot(device);
2729 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2730 toggleHud(statustext_time, &flags->show_hud);
2731 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_MINIMAP])) {
2732 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2733 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]));
2734 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2735 toggleChat(statustext_time, &flags->show_chat);
2736 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2737 toggleFog(statustext_time, &flags->force_fog_off);
2738 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2739 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2740 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2741 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2742 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2743 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2744 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2745 increaseViewRange(statustext_time);
2746 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2747 decreaseViewRange(statustext_time);
2748 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2749 toggleFullViewRange(statustext_time);
2750 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT])) {
2752 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV])) {
2754 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC])) {
2756 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC])) {
2758 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2759 // Print debug stacks
2760 dstream << "-----------------------------------------"
2762 dstream << "Printing debug stacks:" << std::endl;
2763 dstream << "-----------------------------------------"
2765 debug_stacks_print();
2768 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2769 *reset_jump_timer = false;
2775 if (quicktune->hasMessage()) {
2776 std::string msg = quicktune->getMessage();
2777 statustext = utf8_to_wide(msg);
2778 *statustext_time = 0;
2783 void Game::processItemSelection(u16 *new_playeritem)
2785 LocalPlayer *player = client->getEnv().getLocalPlayer();
2787 /* Item selection using mouse wheel
2789 *new_playeritem = client->getPlayerItem();
2791 s32 wheel = input->getMouseWheel();
2792 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2793 player->hud_hotbar_itemcount - 1);
2796 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2798 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2802 /* Item selection using keyboard
2804 for (u16 i = 0; i < 10; i++) {
2805 static const KeyPress *item_keys[10] = {
2806 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2807 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2808 NumberKey + 9, NumberKey + 0,
2811 if (input->wasKeyDown(*item_keys[i])) {
2812 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2813 *new_playeritem = i;
2814 infostream << "Selected item: " << new_playeritem << std::endl;
2822 void Game::dropSelectedItem()
2824 IDropAction *a = new IDropAction();
2826 a->from_inv.setCurrentPlayer();
2827 a->from_list = "main";
2828 a->from_i = client->getPlayerItem();
2829 client->inventoryAction(a);
2833 void Game::openInventory()
2836 * Don't permit to open inventory is CAO or player doesn't exists.
2837 * This prevent showing an empty inventory at player load
2840 LocalPlayer *player = client->getEnv().getLocalPlayer();
2841 if (player == NULL || player->getCAO() == NULL)
2844 infostream << "the_game: " << "Launching inventory" << std::endl;
2846 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2847 TextDest *txt_dst = new TextDestPlayerInventory(client);
2849 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2850 device, fs_src, txt_dst, client);
2852 InventoryLocation inventoryloc;
2853 inventoryloc.setCurrentPlayer();
2854 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2858 void Game::openConsole(float height, const wchar_t *line)
2861 porting::showInputDialog(gettext("ok"), "", "", 2);
2862 m_android_chat_open = true;
2864 if (gui_chat_console->isOpenInhibited())
2866 gui_chat_console->openConsole(height);
2868 gui_chat_console->setCloseOnEnter(true);
2869 gui_chat_console->replaceAndAddToHistory(line);
2875 void Game::handleAndroidChatInput()
2877 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2878 std::string text = porting::getInputDialogValue();
2879 client->typeChatMessage(utf8_to_wide(text));
2885 void Game::toggleFreeMove(float *statustext_time)
2887 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2889 bool free_move = !g_settings->getBool("free_move");
2890 g_settings->set("free_move", bool_to_cstr(free_move));
2892 *statustext_time = 0;
2893 statustext = msg[free_move];
2894 if (free_move && !client->checkPrivilege("fly"))
2895 statustext += L" (note: no 'fly' privilege)";
2899 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2901 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2902 toggleFreeMove(statustext_time);
2906 void Game::toggleFast(float *statustext_time)
2908 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2909 bool fast_move = !g_settings->getBool("fast_move");
2910 g_settings->set("fast_move", bool_to_cstr(fast_move));
2912 *statustext_time = 0;
2913 statustext = msg[fast_move];
2915 bool has_fast_privs = client->checkPrivilege("fast");
2917 if (fast_move && !has_fast_privs)
2918 statustext += L" (note: no 'fast' privilege)";
2921 m_cache_hold_aux1 = fast_move && has_fast_privs;
2926 void Game::toggleNoClip(float *statustext_time)
2928 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2929 bool noclip = !g_settings->getBool("noclip");
2930 g_settings->set("noclip", bool_to_cstr(noclip));
2932 *statustext_time = 0;
2933 statustext = msg[noclip];
2935 if (noclip && !client->checkPrivilege("noclip"))
2936 statustext += L" (note: no 'noclip' privilege)";
2939 void Game::toggleCinematic(float *statustext_time)
2941 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2942 bool cinematic = !g_settings->getBool("cinematic");
2943 g_settings->set("cinematic", bool_to_cstr(cinematic));
2945 *statustext_time = 0;
2946 statustext = msg[cinematic];
2949 // Add WoW-style autorun by toggling continuous forward.
2950 void Game::toggleAutorun(float *statustext_time)
2952 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2953 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2954 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2956 *statustext_time = 0;
2957 statustext = msg[autorun_enabled ? 1 : 0];
2960 void Game::toggleChat(float *statustext_time, bool *flag)
2962 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2965 *statustext_time = 0;
2966 statustext = msg[*flag];
2970 void Game::toggleHud(float *statustext_time, bool *flag)
2972 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2975 *statustext_time = 0;
2976 statustext = msg[*flag];
2979 void Game::toggleMinimap(float *statustext_time, bool *flag,
2980 bool show_hud, bool shift_pressed)
2982 if (!show_hud || !g_settings->getBool("enable_minimap"))
2985 if (shift_pressed) {
2986 mapper->toggleMinimapShape();
2990 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2992 MinimapMode mode = MINIMAP_MODE_OFF;
2993 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2994 mode = mapper->getMinimapMode();
2995 mode = (MinimapMode)((int)mode + 1);
3000 case MINIMAP_MODE_SURFACEx1:
3001 statustext = L"Minimap in surface mode, Zoom x1";
3003 case MINIMAP_MODE_SURFACEx2:
3004 statustext = L"Minimap in surface mode, Zoom x2";
3006 case MINIMAP_MODE_SURFACEx4:
3007 statustext = L"Minimap in surface mode, Zoom x4";
3009 case MINIMAP_MODE_RADARx1:
3010 statustext = L"Minimap in radar mode, Zoom x1";
3012 case MINIMAP_MODE_RADARx2:
3013 statustext = L"Minimap in radar mode, Zoom x2";
3015 case MINIMAP_MODE_RADARx4:
3016 statustext = L"Minimap in radar mode, Zoom x4";
3019 mode = MINIMAP_MODE_OFF;
3021 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
3022 L"Minimap hidden" : L"Minimap disabled by server";
3025 *statustext_time = 0;
3026 mapper->setMinimapMode(mode);
3029 void Game::toggleFog(float *statustext_time, bool *flag)
3031 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
3034 *statustext_time = 0;
3035 statustext = msg[*flag];
3039 void Game::toggleDebug(float *statustext_time, bool *show_debug,
3040 bool *show_profiler_graph)
3042 // Initial / 3x toggle: Chat only
3043 // 1x toggle: Debug text with chat
3044 // 2x toggle: Debug text with profiler graph
3047 *show_profiler_graph = false;
3048 statustext = L"Debug info shown";
3049 } else if (*show_profiler_graph) {
3050 *show_debug = false;
3051 *show_profiler_graph = false;
3052 statustext = L"Debug info and profiler graph hidden";
3054 *show_profiler_graph = true;
3055 statustext = L"Profiler graph shown";
3057 *statustext_time = 0;
3061 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3063 static const wchar_t *msg[] = {
3064 L"Camera update enabled",
3065 L"Camera update disabled"
3069 *statustext_time = 0;
3070 statustext = msg[*flag];
3074 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3075 u32 profiler_max_page)
3077 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3079 // FIXME: This updates the profiler with incomplete values
3080 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3081 profiler_max_page, driver->getScreenSize().Height);
3083 if (*profiler_current_page != 0) {
3084 std::wstringstream sstr;
3085 sstr << "Profiler shown (page " << *profiler_current_page
3086 << " of " << profiler_max_page << ")";
3087 statustext = sstr.str();
3089 statustext = L"Profiler hidden";
3091 *statustext_time = 0;
3095 void Game::increaseViewRange(float *statustext_time)
3097 s16 range = g_settings->getS16("viewing_range");
3098 s16 range_new = range + 10;
3099 g_settings->set("viewing_range", itos(range_new));
3100 statustext = utf8_to_wide("Viewing range changed to "
3102 *statustext_time = 0;
3106 void Game::decreaseViewRange(float *statustext_time)
3108 s16 range = g_settings->getS16("viewing_range");
3109 s16 range_new = range - 10;
3114 g_settings->set("viewing_range", itos(range_new));
3115 statustext = utf8_to_wide("Viewing range changed to "
3117 *statustext_time = 0;
3121 void Game::toggleFullViewRange(float *statustext_time)
3123 static const wchar_t *msg[] = {
3124 L"Disabled full viewing range",
3125 L"Enabled full viewing range"
3128 draw_control->range_all = !draw_control->range_all;
3129 infostream << msg[draw_control->range_all] << std::endl;
3130 statustext = msg[draw_control->range_all];
3131 *statustext_time = 0;
3135 void Game::updateCameraDirection(CameraOrientation *cam,
3136 VolatileRunFlags *flags)
3138 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3141 if (!random_input) {
3142 // Mac OSX gets upset if this is set every frame
3143 if (device->getCursorControl()->isVisible())
3144 device->getCursorControl()->setVisible(false);
3148 if (flags->first_loop_after_window_activation)
3149 flags->first_loop_after_window_activation = false;
3151 updateCameraOrientation(cam, *flags);
3153 input->setMousePos((driver->getScreenSize().Width / 2),
3154 (driver->getScreenSize().Height / 2));
3158 // Mac OSX gets upset if this is set every frame
3159 if (device->getCursorControl()->isVisible() == false)
3160 device->getCursorControl()->setVisible(true);
3163 if (!flags->first_loop_after_window_activation)
3164 flags->first_loop_after_window_activation = true;
3170 void Game::updateCameraOrientation(CameraOrientation *cam,
3171 const VolatileRunFlags &flags)
3173 #ifdef HAVE_TOUCHSCREENGUI
3174 if (g_touchscreengui) {
3175 cam->camera_yaw = g_touchscreengui->getYaw();
3176 cam->camera_pitch = g_touchscreengui->getPitch();
3179 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3180 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3182 if (flags.invert_mouse
3183 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3187 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3188 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3190 #ifdef HAVE_TOUCHSCREENGUI
3194 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3198 void Game::updatePlayerControl(const CameraOrientation &cam)
3200 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3202 PlayerControl control(
3203 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
3204 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
3205 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
3206 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
3207 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
3208 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
3209 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
3210 input->getLeftState(),
3211 input->getRightState(),
3217 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
3218 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
3219 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
3220 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
3221 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
3222 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
3223 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
3224 ( (u32)(input->getLeftState() & 0x1) << 7) |
3225 ( (u32)(input->getRightState() & 0x1) << 8
3229 /* For Android, simulate holding down AUX1 (fast move) if the user has
3230 * the fast_move setting toggled on. If there is an aux1 key defined for
3231 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3234 if (m_cache_hold_aux1) {
3235 control.aux1 = control.aux1 ^ true;
3236 keypress_bits ^= ((u32)(1U << 5));
3240 client->setPlayerControl(control);
3241 LocalPlayer *player = client->getEnv().getLocalPlayer();
3242 player->keyPressed = keypress_bits;
3248 inline void Game::step(f32 *dtime)
3250 bool can_be_and_is_paused =
3251 (simple_singleplayer_mode && g_menumgr.pausesGame());
3253 if (can_be_and_is_paused) { // This is for a singleplayer server
3254 *dtime = 0; // No time passes
3256 if (server != NULL) {
3257 //TimeTaker timer("server->step(dtime)");
3258 server->step(*dtime);
3261 //TimeTaker timer("client.step(dtime)");
3262 client->step(*dtime);
3267 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3269 ClientEvent event = client->getClientEvent();
3271 LocalPlayer *player = client->getEnv().getLocalPlayer();
3273 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3275 if (event.type == CE_PLAYER_DAMAGE &&
3276 client->getHP() != 0) {
3277 //u16 damage = event.player_damage.amount;
3278 //infostream<<"Player damage: "<<damage<<std::endl;
3280 *damage_flash += 100.0;
3281 *damage_flash += 8.0 * event.player_damage.amount;
3283 player->hurt_tilt_timer = 1.5;
3284 player->hurt_tilt_strength = event.player_damage.amount / 4;
3285 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3287 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3288 gamedef->event()->put(e);
3289 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3290 cam->camera_yaw = event.player_force_move.yaw;
3291 cam->camera_pitch = event.player_force_move.pitch;
3292 } else if (event.type == CE_DEATHSCREEN) {
3293 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3296 chat_backend->addMessage(L"", L"You died.");
3298 /* Handle visualization */
3300 player->hurt_tilt_timer = 0;
3301 player->hurt_tilt_strength = 0;
3303 } else if (event.type == CE_SHOW_FORMSPEC) {
3304 FormspecFormSource *fs_src =
3305 new FormspecFormSource(*(event.show_formspec.formspec));
3306 TextDestPlayerInventory *txt_dst =
3307 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3309 create_formspec_menu(¤t_formspec, client, gamedef,
3310 texture_src, device, fs_src, txt_dst, client);
3312 delete(event.show_formspec.formspec);
3313 delete(event.show_formspec.formname);
3314 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3315 (event.type == CE_ADD_PARTICLESPAWNER) ||
3316 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3317 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3319 } else if (event.type == CE_HUDADD) {
3320 u32 id = event.hudadd.id;
3322 LocalPlayer *player = client->getEnv().getLocalPlayer();
3323 HudElement *e = player->getHud(id);
3326 delete event.hudadd.pos;
3327 delete event.hudadd.name;
3328 delete event.hudadd.scale;
3329 delete event.hudadd.text;
3330 delete event.hudadd.align;
3331 delete event.hudadd.offset;
3332 delete event.hudadd.world_pos;
3333 delete event.hudadd.size;
3338 e->type = (HudElementType)event.hudadd.type;
3339 e->pos = *event.hudadd.pos;
3340 e->name = *event.hudadd.name;
3341 e->scale = *event.hudadd.scale;
3342 e->text = *event.hudadd.text;
3343 e->number = event.hudadd.number;
3344 e->item = event.hudadd.item;
3345 e->dir = event.hudadd.dir;
3346 e->align = *event.hudadd.align;
3347 e->offset = *event.hudadd.offset;
3348 e->world_pos = *event.hudadd.world_pos;
3349 e->size = *event.hudadd.size;
3351 u32 new_id = player->addHud(e);
3352 //if this isn't true our huds aren't consistent
3353 sanity_check(new_id == id);
3355 delete event.hudadd.pos;
3356 delete event.hudadd.name;
3357 delete event.hudadd.scale;
3358 delete event.hudadd.text;
3359 delete event.hudadd.align;
3360 delete event.hudadd.offset;
3361 delete event.hudadd.world_pos;
3362 delete event.hudadd.size;
3363 } else if (event.type == CE_HUDRM) {
3364 HudElement *e = player->removeHud(event.hudrm.id);
3368 } else if (event.type == CE_HUDCHANGE) {
3369 u32 id = event.hudchange.id;
3370 HudElement *e = player->getHud(id);
3373 delete event.hudchange.v3fdata;
3374 delete event.hudchange.v2fdata;
3375 delete event.hudchange.sdata;
3376 delete event.hudchange.v2s32data;
3380 switch (event.hudchange.stat) {
3382 e->pos = *event.hudchange.v2fdata;
3386 e->name = *event.hudchange.sdata;
3389 case HUD_STAT_SCALE:
3390 e->scale = *event.hudchange.v2fdata;
3394 e->text = *event.hudchange.sdata;
3397 case HUD_STAT_NUMBER:
3398 e->number = event.hudchange.data;
3402 e->item = event.hudchange.data;
3406 e->dir = event.hudchange.data;
3409 case HUD_STAT_ALIGN:
3410 e->align = *event.hudchange.v2fdata;
3413 case HUD_STAT_OFFSET:
3414 e->offset = *event.hudchange.v2fdata;
3417 case HUD_STAT_WORLD_POS:
3418 e->world_pos = *event.hudchange.v3fdata;
3422 e->size = *event.hudchange.v2s32data;
3426 delete event.hudchange.v3fdata;
3427 delete event.hudchange.v2fdata;
3428 delete event.hudchange.sdata;
3429 delete event.hudchange.v2s32data;
3430 } else if (event.type == CE_SET_SKY) {
3431 sky->setVisible(false);
3438 // Handle according to type
3439 if (*event.set_sky.type == "regular") {
3440 sky->setVisible(true);
3441 } else if (*event.set_sky.type == "skybox" &&
3442 event.set_sky.params->size() == 6) {
3443 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3444 skybox = smgr->addSkyBoxSceneNode(
3445 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3446 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3447 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3448 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3449 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3450 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3452 // Handle everything else as plain color
3454 if (*event.set_sky.type != "plain")
3455 infostream << "Unknown sky type: "
3456 << (*event.set_sky.type) << std::endl;
3458 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3461 delete event.set_sky.bgcolor;
3462 delete event.set_sky.type;
3463 delete event.set_sky.params;
3464 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3465 bool enable = event.override_day_night_ratio.do_override;
3466 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3467 client->getEnv().setDayNightRatioOverride(enable, value);
3473 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3474 f32 dtime, float time_from_last_punch)
3476 LocalPlayer *player = client->getEnv().getLocalPlayer();
3479 For interaction purposes, get info about the held item
3481 - Is it a usable item?
3482 - Can it point to liquids?
3484 ItemStack playeritem;
3486 InventoryList *mlist = local_inventory->getList("main");
3488 if (mlist && client->getPlayerItem() < mlist->getSize())
3489 playeritem = mlist->getItem(client->getPlayerItem());
3492 ToolCapabilities playeritem_toolcap =
3493 playeritem.getToolCapabilities(itemdef_manager);
3495 v3s16 old_camera_offset = camera->getOffset();
3497 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3498 GenericCAO *playercao = player->getCAO();
3500 // If playercao not loaded, don't change camera
3501 if (playercao == NULL)
3504 camera->toggleCameraMode();
3506 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3507 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3510 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3511 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3513 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3514 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3516 camera->step(dtime);
3518 v3f camera_position = camera->getPosition();
3519 v3f camera_direction = camera->getDirection();
3520 f32 camera_fov = camera->getFovMax();
3521 v3s16 camera_offset = camera->getOffset();
3523 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3525 if (!flags->disable_camera_update) {
3526 client->getEnv().getClientMap().updateCamera(camera_position,
3527 camera_direction, camera_fov, camera_offset);
3529 if (flags->camera_offset_changed) {
3530 client->updateCameraOffset(camera_offset);
3531 client->getEnv().updateCameraOffset(camera_offset);
3534 clouds->updateCameraOffset(camera_offset);
3540 void Game::updateSound(f32 dtime)
3542 // Update sound listener
3543 v3s16 camera_offset = camera->getOffset();
3544 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3545 v3f(0, 0, 0), // velocity
3546 camera->getDirection(),
3547 camera->getCameraNode()->getUpVector());
3548 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3551 // Update sound maker
3552 soundmaker->step(dtime);
3554 LocalPlayer *player = client->getEnv().getLocalPlayer();
3556 ClientMap &map = client->getEnv().getClientMap();
3557 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3558 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3562 void Game::processPlayerInteraction(GameRunData *runData,
3563 f32 dtime, bool show_hud, bool show_debug)
3565 LocalPlayer *player = client->getEnv().getLocalPlayer();
3567 ItemStack playeritem;
3569 InventoryList *mlist = local_inventory->getList("main");
3571 if (mlist && client->getPlayerItem() < mlist->getSize())
3572 playeritem = mlist->getItem(client->getPlayerItem());
3575 const ItemDefinition &playeritem_def =
3576 playeritem.getDefinition(itemdef_manager);
3578 v3f player_position = player->getPosition();
3579 v3f camera_position = camera->getPosition();
3580 v3f camera_direction = camera->getDirection();
3581 v3s16 camera_offset = camera->getOffset();
3585 Calculate what block is the crosshair pointing to
3588 f32 d = playeritem_def.range; // max. distance
3589 f32 d_hand = itemdef_manager->get("").range;
3591 if (d < 0 && d_hand >= 0)
3596 core::line3d<f32> shootline;
3598 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3600 shootline = core::line3d<f32>(camera_position,
3601 camera_position + camera_direction * BS * (d + 1));
3604 // prevent player pointing anything in front-view
3605 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3606 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3609 #ifdef HAVE_TOUCHSCREENGUI
3611 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3612 shootline = g_touchscreengui->getShootline();
3613 shootline.start += intToFloat(camera_offset, BS);
3614 shootline.end += intToFloat(camera_offset, BS);
3619 PointedThing pointed = getPointedThing(
3621 client, hud, player_position, camera_direction,
3622 camera_position, shootline, d,
3623 playeritem_def.liquids_pointable,
3624 !runData->ldown_for_dig,
3627 runData->selected_object);
3629 if (pointed != runData->pointed_old) {
3630 infostream << "Pointing at " << pointed.dump() << std::endl;
3631 hud->updateSelectionMesh(camera_offset);
3636 - releasing left mouse button
3637 - pointing away from node
3639 if (runData->digging) {
3640 if (input->getLeftReleased()) {
3641 infostream << "Left button released"
3642 << " (stopped digging)" << std::endl;
3643 runData->digging = false;
3644 } else if (pointed != runData->pointed_old) {
3645 if (pointed.type == POINTEDTHING_NODE
3646 && runData->pointed_old.type == POINTEDTHING_NODE
3647 && pointed.node_undersurface
3648 == runData->pointed_old.node_undersurface) {
3649 // Still pointing to the same node, but a different face.
3652 infostream << "Pointing away from node"
3653 << " (stopped digging)" << std::endl;
3654 runData->digging = false;
3655 hud->updateSelectionMesh(camera_offset);
3659 if (!runData->digging) {
3660 client->interact(1, runData->pointed_old);
3661 client->setCrack(-1, v3s16(0, 0, 0));
3662 runData->dig_time = 0.0;
3666 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3667 runData->ldown_for_dig = false;
3670 runData->left_punch = false;
3672 soundmaker->m_player_leftpunch_sound.name = "";
3674 if (input->getRightState())
3675 runData->repeat_rightclick_timer += dtime;
3677 runData->repeat_rightclick_timer = 0;
3679 if (playeritem_def.usable && input->getLeftState()) {
3680 if (input->getLeftClicked())
3681 client->interact(4, pointed);
3682 } else if (pointed.type == POINTEDTHING_NODE) {
3683 ToolCapabilities playeritem_toolcap =
3684 playeritem.getToolCapabilities(itemdef_manager);
3685 handlePointingAtNode(runData, pointed, playeritem_def,
3686 playeritem_toolcap, dtime);
3687 } else if (pointed.type == POINTEDTHING_OBJECT) {
3688 handlePointingAtObject(runData, pointed, playeritem,
3689 player_position, show_debug);
3690 } else if (input->getLeftState()) {
3691 // When button is held down in air, show continuous animation
3692 runData->left_punch = true;
3693 } else if (input->getRightClicked()) {
3694 handlePointingAtNothing(runData, playeritem);
3697 runData->pointed_old = pointed;
3699 if (runData->left_punch || input->getLeftClicked())
3700 camera->setDigging(0); // left click animation
3702 input->resetLeftClicked();
3703 input->resetRightClicked();
3705 input->resetLeftReleased();
3706 input->resetRightReleased();
3710 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3712 infostream << "Right Clicked in Air" << std::endl;
3713 PointedThing fauxPointed;
3714 fauxPointed.type = POINTEDTHING_NOTHING;
3715 client->interact(5, fauxPointed);
3719 void Game::handlePointingAtNode(GameRunData *runData,
3720 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3721 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3723 v3s16 nodepos = pointed.node_undersurface;
3724 v3s16 neighbourpos = pointed.node_abovesurface;
3727 Check information text of node
3730 ClientMap &map = client->getEnv().getClientMap();
3731 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3734 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3736 MapNode n = map.getNodeNoEx(nodepos);
3738 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3739 infotext = L"Unknown node: ";
3740 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3744 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3745 && client->checkPrivilege("interact")) {
3746 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3749 if ((input->getRightClicked() ||
3750 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3751 client->checkPrivilege("interact")) {
3752 runData->repeat_rightclick_timer = 0;
3753 infostream << "Ground right-clicked" << std::endl;
3755 if (meta && meta->getString("formspec") != "" && !random_input
3756 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3757 infostream << "Launching custom inventory view" << std::endl;
3759 InventoryLocation inventoryloc;
3760 inventoryloc.setNodeMeta(nodepos);
3762 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3763 &client->getEnv().getClientMap(), nodepos);
3764 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3766 create_formspec_menu(¤t_formspec, client, gamedef,
3767 texture_src, device, fs_src, txt_dst, client);
3769 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3771 // Report right click to server
3773 camera->setDigging(1); // right click animation (always shown for feedback)
3775 // If the wielded item has node placement prediction,
3777 bool placed = nodePlacementPrediction(*client,
3779 nodepos, neighbourpos);
3783 client->interact(3, pointed);
3785 soundmaker->m_player_rightpunch_sound =
3786 playeritem_def.sound_place;
3788 soundmaker->m_player_rightpunch_sound =
3791 if (playeritem_def.node_placement_prediction == "" ||
3792 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3793 client->interact(3, pointed); // Report to server
3795 soundmaker->m_player_rightpunch_sound =
3796 playeritem_def.sound_place_failed;
3804 void Game::handlePointingAtObject(GameRunData *runData,
3805 const PointedThing &pointed,
3806 const ItemStack &playeritem,
3807 const v3f &player_position,
3810 infotext = unescape_enriched(
3811 utf8_to_wide(runData->selected_object->infoText()));
3814 if (infotext != L"") {
3817 infotext += unescape_enriched(utf8_to_wide(
3818 runData->selected_object->debugInfoText()));
3821 if (input->getLeftState()) {
3822 bool do_punch = false;
3823 bool do_punch_damage = false;
3825 if (runData->object_hit_delay_timer <= 0.0) {
3827 do_punch_damage = true;
3828 runData->object_hit_delay_timer = object_hit_delay;
3831 if (input->getLeftClicked())
3835 infostream << "Left-clicked object" << std::endl;
3836 runData->left_punch = true;
3839 if (do_punch_damage) {
3840 // Report direct punch
3841 v3f objpos = runData->selected_object->getPosition();
3842 v3f dir = (objpos - player_position).normalize();
3844 bool disable_send = runData->selected_object->directReportPunch(
3845 dir, &playeritem, runData->time_from_last_punch);
3846 runData->time_from_last_punch = 0;
3849 client->interact(0, pointed);
3851 } else if (input->getRightClicked()) {
3852 infostream << "Right-clicked object" << std::endl;
3853 client->interact(3, pointed); // place
3858 void Game::handleDigging(GameRunData *runData,
3859 const PointedThing &pointed, const v3s16 &nodepos,
3860 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3862 if (!runData->digging) {
3863 infostream << "Started digging" << std::endl;
3864 client->interact(0, pointed);
3865 runData->digging = true;
3866 runData->ldown_for_dig = true;
3869 LocalPlayer *player = client->getEnv().getLocalPlayer();
3870 ClientMap &map = client->getEnv().getClientMap();
3871 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3873 // NOTE: Similar piece of code exists on the server side for
3875 // Get digging parameters
3876 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3877 &playeritem_toolcap);
3879 // If can't dig, try hand
3880 if (!params.diggable) {
3881 const ItemDefinition &hand = itemdef_manager->get("");
3882 const ToolCapabilities *tp = hand.tool_capabilities;
3885 params = getDigParams(nodedef_manager->get(n).groups, tp);
3888 if (params.diggable == false) {
3889 // I guess nobody will wait for this long
3890 runData->dig_time_complete = 10000000.0;
3892 runData->dig_time_complete = params.time;
3894 if (m_cache_enable_particles) {
3895 const ContentFeatures &features =
3896 client->getNodeDefManager()->get(n);
3897 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3898 player, nodepos, features.tiles);
3902 if (runData->dig_time_complete >= 0.001) {
3903 runData->dig_index = (float)crack_animation_length
3905 / runData->dig_time_complete;
3907 // This is for torches
3908 runData->dig_index = crack_animation_length;
3911 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3913 if (sound_dig.exists() && params.diggable) {
3914 if (sound_dig.name == "__group") {
3915 if (params.main_group != "") {
3916 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3917 soundmaker->m_player_leftpunch_sound.name =
3918 std::string("default_dig_") +
3922 soundmaker->m_player_leftpunch_sound = sound_dig;
3926 // Don't show cracks if not diggable
3927 if (runData->dig_time_complete >= 100000.0) {
3928 } else if (runData->dig_index < crack_animation_length) {
3929 //TimeTaker timer("client.setTempMod");
3930 //infostream<<"dig_index="<<dig_index<<std::endl;
3931 client->setCrack(runData->dig_index, nodepos);
3933 infostream << "Digging completed" << std::endl;
3934 client->interact(2, pointed);
3935 client->setCrack(-1, v3s16(0, 0, 0));
3936 bool is_valid_position;
3937 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3938 if (is_valid_position)
3939 client->removeNode(nodepos);
3941 if (m_cache_enable_particles) {
3942 const ContentFeatures &features =
3943 client->getNodeDefManager()->get(wasnode);
3944 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3945 player, nodepos, features.tiles);
3948 runData->dig_time = 0;
3949 runData->digging = false;
3951 runData->nodig_delay_timer =
3952 runData->dig_time_complete / (float)crack_animation_length;
3954 // We don't want a corresponding delay to
3955 // very time consuming nodes
3956 if (runData->nodig_delay_timer > 0.3)
3957 runData->nodig_delay_timer = 0.3;
3959 // We want a slight delay to very little
3960 // time consuming nodes
3961 const float mindelay = 0.15;
3963 if (runData->nodig_delay_timer < mindelay)
3964 runData->nodig_delay_timer = mindelay;
3966 // Send event to trigger sound
3967 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3968 gamedef->event()->put(e);
3971 if (runData->dig_time_complete < 100000.0) {
3972 runData->dig_time += dtime;
3974 runData->dig_time = 0;
3975 client->setCrack(-1, nodepos);
3978 camera->setDigging(0); // left click animation
3982 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
3983 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
3984 const CameraOrientation &cam)
3986 LocalPlayer *player = client->getEnv().getLocalPlayer();
3992 if (draw_control->range_all) {
3993 runData->fog_range = 100000 * BS;
3995 runData->fog_range = 0.9 * draw_control->wanted_range * BS;
3999 Calculate general brightness
4001 u32 daynight_ratio = client->getEnv().getDayNightRatio();
4002 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4003 float direct_brightness;
4006 if (g_settings->getBool("free_move")) {
4007 direct_brightness = time_brightness;
4008 sunlight_seen = true;
4010 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4011 float old_brightness = sky->getBrightness();
4012 direct_brightness = client->getEnv().getClientMap()
4013 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
4014 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4018 float time_of_day = runData->time_of_day;
4019 float time_of_day_smooth = runData->time_of_day_smooth;
4021 time_of_day = client->getEnv().getTimeOfDayF();
4023 const float maxsm = 0.05;
4024 const float todsm = 0.05;
4026 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4027 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4028 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4029 time_of_day_smooth = time_of_day;
4031 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4032 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4033 + (time_of_day + 1.0) * todsm;
4035 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4036 + time_of_day * todsm;
4038 runData->time_of_day = time_of_day;
4039 runData->time_of_day_smooth = time_of_day_smooth;
4041 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4042 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4043 player->getPitch());
4049 v3f player_position = player->getPosition();
4050 if (sky->getCloudsVisible()) {
4051 clouds->setVisible(true);
4052 clouds->step(dtime);
4053 clouds->update(v2f(player_position.X, player_position.Z),
4054 sky->getCloudColor());
4056 clouds->setVisible(false);
4063 client->getParticleManager()->step(dtime);
4069 if (m_cache_enable_fog && !flags.force_fog_off) {
4072 video::EFT_FOG_LINEAR,
4073 runData->fog_range * 0.4,
4074 runData->fog_range * 1.0,
4082 video::EFT_FOG_LINEAR,
4092 Get chat messages from client
4095 v2u32 screensize = driver->getScreenSize();
4097 updateChat(*client, dtime, flags.show_debug, screensize,
4098 flags.show_chat, runData->profiler_current_page,
4099 *chat_backend, guitext_chat);
4105 if (client->getPlayerItem() != runData->new_playeritem)
4106 client->selectPlayerItem(runData->new_playeritem);
4108 // Update local inventory if it has changed
4109 if (client->getLocalInventoryUpdated()) {
4110 //infostream<<"Updating local inventory"<<std::endl;
4111 client->getLocalInventory(*local_inventory);
4112 runData->update_wielded_item_trigger = true;
4115 if (runData->update_wielded_item_trigger) {
4116 // Update wielded tool
4117 InventoryList *mlist = local_inventory->getList("main");
4119 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4120 ItemStack item = mlist->getItem(client->getPlayerItem());
4121 camera->wield(item);
4123 runData->update_wielded_item_trigger = false;
4127 Update block draw list every 200ms or when camera direction has
4130 runData->update_draw_list_timer += dtime;
4132 v3f camera_direction = camera->getDirection();
4133 if (runData->update_draw_list_timer >= 0.2
4134 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4135 || flags.camera_offset_changed) {
4136 runData->update_draw_list_timer = 0;
4137 client->getEnv().getClientMap().updateDrawList(driver);
4138 runData->update_draw_list_last_cam_dir = camera_direction;
4141 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4144 make sure menu is on top
4145 1. Delete formspec menu reference if menu was removed
4146 2. Else, make sure formspec menu is on top
4148 if (current_formspec) {
4149 if (current_formspec->getReferenceCount() == 1) {
4150 current_formspec->drop();
4151 current_formspec = NULL;
4152 } else if (!noMenuActive()) {
4153 guiroot->bringToFront(current_formspec);
4161 video::SColor skycolor = sky->getSkyColor();
4163 TimeTaker tt_draw("mainloop: draw");
4165 TimeTaker timer("beginScene");
4166 driver->beginScene(true, true, skycolor);
4167 stats->beginscenetime = timer.stop(true);
4170 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4171 guienv, screensize, skycolor, flags.show_hud,
4172 flags.show_minimap);
4177 if (flags.show_profiler_graph)
4178 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4183 if (runData->damage_flash > 0.0) {
4184 video::SColor color(std::min(runData->damage_flash, 180.0f),
4188 driver->draw2DRectangle(color,
4189 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4192 runData->damage_flash -= 100.0 * dtime;
4198 if (player->hurt_tilt_timer > 0.0) {
4199 player->hurt_tilt_timer -= dtime * 5;
4201 if (player->hurt_tilt_timer < 0)
4202 player->hurt_tilt_strength = 0;
4206 Update minimap pos and rotation
4208 if (flags.show_minimap && flags.show_hud) {
4209 mapper->setPos(floatToInt(player->getPosition(), BS));
4210 mapper->setAngle(player->getYaw());
4217 TimeTaker timer("endScene");
4219 stats->endscenetime = timer.stop(true);
4222 stats->drawtime = tt_draw.stop(true);
4223 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4227 inline static const char *yawToDirectionString(int yaw)
4229 // NOTE: TODO: This can be done mathematically without the else/else-if
4232 const char *player_direction;
4234 yaw = wrapDegrees_0_360(yaw);
4236 if (yaw >= 45 && yaw < 135)
4237 player_direction = "West [-X]";
4238 else if (yaw >= 135 && yaw < 225)
4239 player_direction = "South [-Z]";
4240 else if (yaw >= 225 && yaw < 315)
4241 player_direction = "East [+X]";
4243 player_direction = "North [+Z]";
4245 return player_direction;
4249 void Game::updateGui(float *statustext_time, const RunStats &stats,
4250 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4251 const CameraOrientation &cam)
4253 v2u32 screensize = driver->getScreenSize();
4254 LocalPlayer *player = client->getEnv().getLocalPlayer();
4255 v3f player_position = player->getPosition();
4257 if (flags.show_debug) {
4258 static float drawtime_avg = 0;
4259 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4261 u16 fps = 1.0 / stats.dtime_jitter.avg;
4262 //s32 fps = driver->getFPS();
4264 std::ostringstream os(std::ios_base::binary);
4266 << PROJECT_NAME_C " " << g_version_hash
4268 << " (R: range_all=" << draw_control->range_all << ")"
4269 << std::setprecision(0)
4270 << " drawtime = " << drawtime_avg
4271 << std::setprecision(1)
4272 << ", dtime_jitter = "
4273 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4274 << std::setprecision(1)
4275 << ", v_range = " << draw_control->wanted_range
4276 << std::setprecision(3)
4277 << ", RTT = " << client->getRTT();
4278 guitext->setText(utf8_to_wide(os.str()).c_str());
4279 guitext->setVisible(true);
4280 } else if (flags.show_hud || flags.show_chat) {
4281 std::ostringstream os(std::ios_base::binary);
4282 os << PROJECT_NAME_C " " << g_version_hash;
4283 guitext->setText(utf8_to_wide(os.str()).c_str());
4284 guitext->setVisible(true);
4286 guitext->setVisible(false);
4289 if (guitext->isVisible()) {
4290 core::rect<s32> rect(
4292 screensize.X, 5 + g_fontengine->getTextHeight()
4294 guitext->setRelativePosition(rect);
4297 if (flags.show_debug) {
4298 std::ostringstream os(std::ios_base::binary);
4299 os << std::setprecision(1) << std::fixed
4300 << "(" << (player_position.X / BS)
4301 << ", " << (player_position.Y / BS)
4302 << ", " << (player_position.Z / BS)
4303 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4304 << " " << yawToDirectionString(cam.camera_yaw)
4305 << ") (seed = " << ((u64)client->getMapSeed())
4308 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4309 ClientMap &map = client->getEnv().getClientMap();
4310 const INodeDefManager *nodedef = client->getNodeDefManager();
4311 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4312 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4313 const ContentFeatures &features = nodedef->get(n);
4314 os << " (pointing_at = " << nodedef->get(n).name
4315 << " - " << features.tiledef[0].name.c_str()
4320 guitext2->setText(utf8_to_wide(os.str()).c_str());
4321 guitext2->setVisible(true);
4323 core::rect<s32> rect(
4324 5, 5 + g_fontengine->getTextHeight(),
4325 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4327 guitext2->setRelativePosition(rect);
4329 guitext2->setVisible(false);
4332 guitext_info->setText(infotext.c_str());
4333 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4335 float statustext_time_max = 1.5;
4337 if (!statustext.empty()) {
4338 *statustext_time += dtime;
4340 if (*statustext_time >= statustext_time_max) {
4342 *statustext_time = 0;
4346 guitext_status->setText(statustext.c_str());
4347 guitext_status->setVisible(!statustext.empty());
4349 if (!statustext.empty()) {
4350 s32 status_width = guitext_status->getTextWidth();
4351 s32 status_height = guitext_status->getTextHeight();
4352 s32 status_y = screensize.Y - 150;
4353 s32 status_x = (screensize.X - status_width) / 2;
4354 core::rect<s32> rect(
4355 status_x , status_y - status_height,
4356 status_x + status_width, status_y
4358 guitext_status->setRelativePosition(rect);
4361 video::SColor initial_color(255, 0, 0, 0);
4363 if (guienv->getSkin())
4364 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4366 video::SColor final_color = initial_color;
4367 final_color.setAlpha(0);
4368 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4369 initial_color, final_color,
4370 pow(*statustext_time / statustext_time_max, 2.0f));
4371 guitext_status->setOverrideColor(fade_color);
4372 guitext_status->enableOverrideColor(true);
4377 /* Log times and stuff for visualization */
4378 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4380 Profiler::GraphValues values;
4381 g_profiler->graphGet(values);
4387 /****************************************************************************
4389 ****************************************************************************/
4391 /* On some computers framerate doesn't seem to be automatically limited
4393 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4395 // not using getRealTime is necessary for wine
4396 device->getTimer()->tick(); // Maker sure device time is up-to-date
4397 u32 time = device->getTimer()->getTime();
4398 u32 last_time = fps_timings->last_time;
4400 if (time > last_time) // Make sure time hasn't overflowed
4401 fps_timings->busy_time = time - last_time;
4403 fps_timings->busy_time = 0;
4405 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4406 ? g_settings->getFloat("pause_fps_max")
4407 : g_settings->getFloat("fps_max"));
4409 if (fps_timings->busy_time < frametime_min) {
4410 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4411 device->sleep(fps_timings->sleep_time);
4413 fps_timings->sleep_time = 0;
4416 /* Get the new value of the device timer. Note that device->sleep() may
4417 * not sleep for the entire requested time as sleep may be interrupted and
4418 * therefore it is arguably more accurate to get the new time from the
4419 * device rather than calculating it by adding sleep_time to time.
4422 device->getTimer()->tick(); // Update device timer
4423 time = device->getTimer()->getTime();
4425 if (time > last_time) // Make sure last_time hasn't overflowed
4426 *dtime = (time - last_time) / 1000.0;
4430 fps_timings->last_time = time;
4433 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4434 // pass a copy of it to this function
4435 // Note: \p msg must be allocated using new (not malloc())
4436 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4437 int percent, bool draw_clouds)
4439 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4443 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4445 ((Game *)data)->readSettings();
4448 void Game::readSettings()
4450 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4451 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4452 m_cache_enable_particles = g_settings->getBool("enable_particles");
4453 m_cache_enable_fog = g_settings->getBool("enable_fog");
4454 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4455 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4457 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4460 /****************************************************************************/
4461 /****************************************************************************
4463 ****************************************************************************/
4464 /****************************************************************************/
4466 void Game::extendedResourceCleanup()
4468 // Extended resource accounting
4469 infostream << "Irrlicht resources after cleanup:" << std::endl;
4470 infostream << "\tRemaining meshes : "
4471 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4472 infostream << "\tRemaining textures : "
4473 << driver->getTextureCount() << std::endl;
4475 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4476 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4477 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4481 clearTextureNameCache();
4482 infostream << "\tRemaining materials: "
4483 << driver-> getMaterialRendererCount()
4484 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4488 /****************************************************************************/
4489 /****************************************************************************
4490 extern function for launching the game
4491 ****************************************************************************/
4492 /****************************************************************************/
4494 void the_game(bool *kill,
4496 InputHandler *input,
4497 IrrlichtDevice *device,
4499 const std::string &map_dir,
4500 const std::string &playername,
4501 const std::string &password,
4502 const std::string &address, // If empty local server is created
4505 std::string &error_message,
4506 ChatBackend &chat_backend,
4507 bool *reconnect_requested,
4508 const SubgameSpec &gamespec, // Used for local game
4509 bool simple_singleplayer_mode)
4513 /* Make a copy of the server address because if a local singleplayer server
4514 * is created then this is updated and we don't want to change the value
4515 * passed to us by the calling function
4517 std::string server_address = address;
4521 if (game.startup(kill, random_input, input, device, map_dir,
4522 playername, password, &server_address, port, error_message,
4523 reconnect_requested, &chat_backend, gamespec,
4524 simple_singleplayer_mode)) {
4529 } catch (SerializationError &e) {
4530 error_message = std::string("A serialization error occurred:\n")
4531 + e.what() + "\n\nThe server is probably "
4532 " running a different version of " PROJECT_NAME_C ".";
4533 errorstream << error_message << std::endl;
4534 } catch (ServerError &e) {
4535 error_message = e.what();
4536 errorstream << "ServerError: " << error_message << std::endl;
4537 } catch (ModError &e) {
4538 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4539 errorstream << "ModError: " << error_message << std::endl;