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());
277 Find what the player is pointing at
279 PointedThing getPointedThing(Client *client, Hud *hud, const v3f &player_position,
280 const v3f &camera_direction, const v3f &camera_position,
281 core::line3d<f32> shootline, f32 d, bool liquids_pointable,
282 bool look_for_object, const v3s16 &camera_offset,
283 ClientActiveObject *&selected_object)
287 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
288 selectionboxes->clear();
289 selected_object = NULL;
291 INodeDefManager *nodedef = client->getNodeDefManager();
292 ClientMap &map = client->getEnv().getClientMap();
294 f32 min_distance = BS * 1001;
296 // First try to find a pointed at active object
297 if (look_for_object) {
298 selected_object = client->getSelectedActiveObject(d * BS,
299 camera_position, shootline);
301 if (selected_object != NULL) {
302 if (selected_object->doShowSelectionBox()) {
303 aabb3f *selection_box = selected_object->getSelectionBox();
304 // Box should exist because object was
305 // returned in the first place
306 assert(selection_box);
308 v3f pos = selected_object->getPosition();
309 selectionboxes->push_back(aabb3f(
310 selection_box->MinEdge, selection_box->MaxEdge));
311 hud->setSelectionPos(pos, camera_offset);
314 min_distance = (selected_object->getPosition() - camera_position).getLength();
316 result.type = POINTEDTHING_OBJECT;
317 result.object_id = selected_object->getId();
321 // That didn't work, try to find a pointed at node
323 v3s16 pos_i = floatToInt(player_position, BS);
325 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
329 s16 ystart = pos_i.Y - (camera_direction.Y < 0 ? a : 1);
330 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
331 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
332 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
333 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
334 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
336 // Prevent signed number overflow
346 v3s16 pointed_pos(0, 0, 0);
348 for (s16 y = ystart; y <= yend; y++) {
349 for (s16 z = zstart; z <= zend; z++) {
350 for (s16 x = xstart; x <= xend; x++) {
352 bool is_valid_position;
354 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
355 if (!is_valid_position) {
358 if (!isPointableNode(n, client, liquids_pointable)) {
362 std::vector<aabb3f> boxes;
363 n.getSelectionBoxes(nodedef, &boxes);
366 v3f npf = intToFloat(np, BS);
367 for (std::vector<aabb3f>::const_iterator
369 i != boxes.end(); ++i) {
374 v3f centerpoint = box.getCenter();
375 f32 distance = (centerpoint - camera_position).getLength();
376 if (distance >= min_distance) {
379 if (!box.intersectsWithLine(shootline)) {
382 result.type = POINTEDTHING_NODE;
383 min_distance = distance;
390 if (result.type == POINTEDTHING_NODE) {
392 MapNode n = map.getNodeNoEx(pointed_pos);
393 v3f npf = intToFloat(pointed_pos, BS);
394 std::vector<aabb3f> boxes;
395 n.getSelectionBoxes(nodedef, &boxes);
396 f32 face_min_distance = 1000 * BS;
397 for (std::vector<aabb3f>::const_iterator
399 i != boxes.end(); ++i) {
403 for (u16 j = 0; j < 6; j++) {
404 v3s16 facedir = g_6dirs[j];
405 aabb3f facebox = box;
407 facebox.MinEdge.X = facebox.MaxEdge.X - d;
408 } else if (facedir.X < 0) {
409 facebox.MaxEdge.X = facebox.MinEdge.X + d;
410 } else if (facedir.Y > 0) {
411 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
412 } else if (facedir.Y < 0) {
413 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
414 } else if (facedir.Z > 0) {
415 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
416 } else if (facedir.Z < 0) {
417 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
419 v3f centerpoint = facebox.getCenter();
420 f32 distance = (centerpoint - camera_position).getLength();
421 if (distance >= face_min_distance)
423 if (!facebox.intersectsWithLine(shootline))
425 result.node_abovesurface = pointed_pos + facedir;
426 face_min_distance = distance;
429 selectionboxes->clear();
430 for (std::vector<aabb3f>::const_iterator
432 i != boxes.end(); ++i) {
434 box.MinEdge += v3f(-d, -d, -d);
435 box.MaxEdge += v3f(d, d, d);
436 selectionboxes->push_back(box);
438 hud->setSelectionPos(intToFloat(pointed_pos, BS), camera_offset);
439 result.node_undersurface = pointed_pos;
442 // Update selection mesh light level and vertex colors
443 if (selectionboxes->size() > 0) {
444 v3f pf = hud->getSelectionPos();
445 v3s16 p = floatToInt(pf, BS);
447 // Get selection mesh light level
448 MapNode n = map.getNodeNoEx(p);
449 u16 node_light = getInteriorLight(n, -1, nodedef);
450 u16 light_level = node_light;
452 for (u8 i = 0; i < 6; i++) {
453 n = map.getNodeNoEx(p + g_6dirs[i]);
454 node_light = getInteriorLight(n, -1, nodedef);
455 if (node_light > light_level)
456 light_level = node_light;
459 video::SColor c = MapBlock_LightColor(255, light_level, 0);
461 u8 night = c.getGreen();
462 u32 daynight_ratio = client->getEnv().getDayNightRatio();
463 finalColorBlend(c, day, night, daynight_ratio);
465 // Modify final color a bit with time
466 u32 timer = porting::getTimeMs() % 5000;
467 float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
468 float sin_r = 0.08 * sin(timerf);
469 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
470 float sin_b = 0.08 * sin(timerf + irr::core::PI);
471 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
472 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
473 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
475 // Set mesh final color
476 hud->setSelectionMeshColor(c);
481 /* Profiler display */
483 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
484 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
486 if (show_profiler == 0) {
487 guitext_profiler->setVisible(false);
490 std::ostringstream os(std::ios_base::binary);
491 g_profiler->printPage(os, show_profiler, show_profiler_max);
492 std::wstring text = utf8_to_wide(os.str());
493 guitext_profiler->setText(text.c_str());
494 guitext_profiler->setVisible(true);
496 s32 w = fe->getTextWidth(text.c_str());
501 unsigned text_height = fe->getTextHeight();
503 core::position2di upper_left, lower_right;
506 upper_left.Y = (text_height + 5) * 2;
507 lower_right.X = 12 + w;
508 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
510 if (lower_right.Y > screen_height * 2 / 3)
511 lower_right.Y = screen_height * 2 / 3;
513 core::rect<s32> rect(upper_left, lower_right);
515 guitext_profiler->setRelativePosition(rect);
516 guitext_profiler->setVisible(true);
524 Profiler::GraphValues values;
530 Meta(float initial = 0,
531 video::SColor color = video::SColor(255, 255, 255, 255)):
537 std::deque<Piece> m_log;
545 void put(const Profiler::GraphValues &values)
548 piece.values = values;
549 m_log.push_back(piece);
551 while (m_log.size() > m_log_max_size)
552 m_log.erase(m_log.begin());
555 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
556 gui::IGUIFont *font) const
558 std::map<std::string, Meta> m_meta;
560 for (std::deque<Piece>::const_iterator k = m_log.begin();
561 k != m_log.end(); ++k) {
562 const Piece &piece = *k;
564 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
565 i != piece.values.end(); ++i) {
566 const std::string &id = i->first;
567 const float &value = i->second;
568 std::map<std::string, Meta>::iterator j =
571 if (j == m_meta.end()) {
572 m_meta[id] = Meta(value);
576 if (value < j->second.min)
577 j->second.min = value;
579 if (value > j->second.max)
580 j->second.max = value;
585 static const video::SColor usable_colors[] = {
586 video::SColor(255, 255, 100, 100),
587 video::SColor(255, 90, 225, 90),
588 video::SColor(255, 100, 100, 255),
589 video::SColor(255, 255, 150, 50),
590 video::SColor(255, 220, 220, 100)
592 static const u32 usable_colors_count =
593 sizeof(usable_colors) / sizeof(*usable_colors);
594 u32 next_color_i = 0;
596 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
597 i != m_meta.end(); ++i) {
598 Meta &meta = i->second;
599 video::SColor color(255, 200, 200, 200);
601 if (next_color_i < usable_colors_count)
602 color = usable_colors[next_color_i++];
608 s32 textx = x_left + m_log_max_size + 15;
609 s32 textx2 = textx + 200 - 15;
612 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
613 i != m_meta.end(); ++i) {
614 const std::string &id = i->first;
615 const Meta &meta = i->second;
617 s32 y = y_bottom - meta_i * 50;
618 float show_min = meta.min;
619 float show_max = meta.max;
621 if (show_min >= -0.0001 && show_max >= -0.0001) {
622 if (show_min <= show_max * 0.5)
628 snprintf(buf, 10, "%.3g", show_max);
629 font->draw(utf8_to_wide(buf).c_str(),
630 core::rect<s32>(textx, y - graphh,
631 textx2, y - graphh + texth),
633 snprintf(buf, 10, "%.3g", show_min);
634 font->draw(utf8_to_wide(buf).c_str(),
635 core::rect<s32>(textx, y - texth,
638 font->draw(utf8_to_wide(id).c_str(),
639 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
640 textx2, y - graphh / 2 + texth / 2),
643 s32 graph1h = graphh;
644 bool relativegraph = (show_min != 0 && show_min != show_max);
645 float lastscaledvalue = 0.0;
646 bool lastscaledvalue_exists = false;
648 for (std::deque<Piece>::const_iterator j = m_log.begin();
649 j != m_log.end(); ++j) {
650 const Piece &piece = *j;
652 bool value_exists = false;
653 Profiler::GraphValues::const_iterator k =
654 piece.values.find(id);
656 if (k != piece.values.end()) {
663 lastscaledvalue_exists = false;
667 float scaledvalue = 1.0;
669 if (show_max != show_min)
670 scaledvalue = (value - show_min) / (show_max - show_min);
672 if (scaledvalue == 1.0 && value == 0) {
674 lastscaledvalue_exists = false;
679 if (lastscaledvalue_exists) {
680 s32 ivalue1 = lastscaledvalue * graph1h;
681 s32 ivalue2 = scaledvalue * graph1h;
682 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
683 v2s32(x, graph1y - ivalue2), meta.color);
686 lastscaledvalue = scaledvalue;
687 lastscaledvalue_exists = true;
689 s32 ivalue = scaledvalue * graph1h;
690 driver->draw2DLine(v2s32(x, graph1y),
691 v2s32(x, graph1y - ivalue), meta.color);
702 class NodeDugEvent: public MtEvent
708 NodeDugEvent(v3s16 p, MapNode n):
712 const char *getType() const
720 ISoundManager *m_sound;
721 INodeDefManager *m_ndef;
723 float m_player_step_timer;
725 SimpleSoundSpec m_player_step_sound;
726 SimpleSoundSpec m_player_leftpunch_sound;
727 SimpleSoundSpec m_player_rightpunch_sound;
729 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
732 m_player_step_timer(0)
736 void playPlayerStep()
738 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
739 m_player_step_timer = 0.03;
740 m_sound->playSound(m_player_step_sound, false);
744 static void viewBobbingStep(MtEvent *e, void *data)
746 SoundMaker *sm = (SoundMaker *)data;
747 sm->playPlayerStep();
750 static void playerRegainGround(MtEvent *e, void *data)
752 SoundMaker *sm = (SoundMaker *)data;
753 sm->playPlayerStep();
756 static void playerJump(MtEvent *e, void *data)
758 //SoundMaker *sm = (SoundMaker*)data;
761 static void cameraPunchLeft(MtEvent *e, void *data)
763 SoundMaker *sm = (SoundMaker *)data;
764 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
767 static void cameraPunchRight(MtEvent *e, void *data)
769 SoundMaker *sm = (SoundMaker *)data;
770 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
773 static void nodeDug(MtEvent *e, void *data)
775 SoundMaker *sm = (SoundMaker *)data;
776 NodeDugEvent *nde = (NodeDugEvent *)e;
777 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
780 static void playerDamage(MtEvent *e, void *data)
782 SoundMaker *sm = (SoundMaker *)data;
783 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
786 static void playerFallingDamage(MtEvent *e, void *data)
788 SoundMaker *sm = (SoundMaker *)data;
789 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
792 void registerReceiver(MtEventManager *mgr)
794 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
795 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
796 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
797 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
798 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
799 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
800 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
801 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
804 void step(float dtime)
806 m_player_step_timer -= dtime;
810 // Locally stored sounds don't need to be preloaded because of this
811 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
813 std::set<std::string> m_fetched;
815 void fetchSounds(const std::string &name,
816 std::set<std::string> &dst_paths,
817 std::set<std::string> &dst_datas)
819 if (m_fetched.count(name))
822 m_fetched.insert(name);
823 std::string base = porting::path_share + DIR_DELIM + "testsounds";
824 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
825 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
826 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
827 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
828 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
829 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
830 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
831 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
832 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
833 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
834 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
838 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
841 bool *m_force_fog_off;
847 void onSettingsChange(const std::string &name)
849 if (name == "enable_fog")
850 m_fogEnabled = g_settings->getBool("enable_fog");
853 static void SettingsCallback(const std::string &name, void *userdata)
855 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
858 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
859 f32 *fog_range, Client *client) :
861 m_force_fog_off(force_fog_off),
862 m_fog_range(fog_range),
865 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
866 m_fogEnabled = g_settings->getBool("enable_fog");
869 ~GameGlobalShaderConstantSetter()
871 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
874 virtual void onSetConstants(video::IMaterialRendererServices *services,
881 video::SColor bgcolor = m_sky->getBgColor();
882 video::SColorf bgcolorf(bgcolor);
883 float bgcolorfa[4] = {
889 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
892 float fog_distance = 10000 * BS;
894 if (m_fogEnabled && !*m_force_fog_off)
895 fog_distance = *m_fog_range;
897 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
900 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
901 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
902 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
904 u32 animation_timer = porting::getTimeMs() % 100000;
905 float animation_timer_f = (float)animation_timer / 100000.0;
906 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
907 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
909 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
910 v3f eye_position = player->getEyePosition();
911 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
912 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
914 v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
915 services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
917 // Uniform sampler layers
918 // before 1.8 there isn't a "integer interface", only float
919 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
923 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
924 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
925 services->setPixelShaderConstant("textureFlags" , (irr::f32 *)&layer2, 1);
930 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
931 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
932 services->setPixelShaderConstant("textureFlags" , (irr::s32 *)&layer2, 1);
937 bool nodePlacementPrediction(Client &client,
938 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
940 std::string prediction = playeritem_def.node_placement_prediction;
941 INodeDefManager *nodedef = client.ndef();
942 ClientMap &map = client.getEnv().getClientMap();
944 bool is_valid_position;
946 node = map.getNodeNoEx(nodepos, &is_valid_position);
947 if (!is_valid_position)
950 if (prediction != "" && !nodedef->get(node).rightclickable) {
951 verbosestream << "Node placement prediction for "
952 << playeritem_def.name << " is "
953 << prediction << std::endl;
954 v3s16 p = neighbourpos;
956 // Place inside node itself if buildable_to
957 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
958 if (is_valid_position)
960 if (nodedef->get(n_under).buildable_to)
963 node = map.getNodeNoEx(p, &is_valid_position);
964 if (is_valid_position &&!nodedef->get(node).buildable_to)
969 // Find id of predicted node
971 bool found = nodedef->getId(prediction, id);
974 errorstream << "Node placement prediction failed for "
975 << playeritem_def.name << " (places "
977 << ") - Name not known" << std::endl;
981 // Predict param2 for facedir and wallmounted nodes
984 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
985 v3s16 dir = nodepos - neighbourpos;
987 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
988 param2 = dir.Y < 0 ? 1 : 0;
989 } else if (abs(dir.X) > abs(dir.Z)) {
990 param2 = dir.X < 0 ? 3 : 2;
992 param2 = dir.Z < 0 ? 5 : 4;
996 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
997 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
999 if (abs(dir.X) > abs(dir.Z)) {
1000 param2 = dir.X < 0 ? 3 : 1;
1002 param2 = dir.Z < 0 ? 2 : 0;
1006 assert(param2 <= 5);
1008 //Check attachment if node is in group attached_node
1009 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
1010 static v3s16 wallmounted_dirs[8] = {
1020 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
1021 pp = p + wallmounted_dirs[param2];
1023 pp = p + v3s16(0, -1, 0);
1025 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
1029 // Add node to client map
1030 MapNode n(id, 0, param2);
1033 LocalPlayer *player = client.getEnv().getLocalPlayer();
1035 // Dont place node when player would be inside new node
1036 // NOTE: This is to be eventually implemented by a mod as client-side Lua
1037 if (!nodedef->get(n).walkable ||
1038 g_settings->getBool("enable_build_where_you_stand") ||
1039 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1040 (nodedef->get(n).walkable &&
1041 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1042 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1044 // This triggers the required mesh update too
1045 client.addNode(p, n);
1048 } catch (InvalidPositionException &e) {
1049 errorstream << "Node placement prediction failed for "
1050 << playeritem_def.name << " (places "
1052 << ") - Position not loaded" << std::endl;
1059 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1060 InventoryManager *invmgr, IGameDef *gamedef,
1061 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1062 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1065 if (*cur_formspec == 0) {
1066 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1067 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1068 (*cur_formspec)->doPause = false;
1071 Caution: do not call (*cur_formspec)->drop() here --
1072 the reference might outlive the menu, so we will
1073 periodically check if *cur_formspec is the only
1074 remaining reference (i.e. the menu was removed)
1075 and delete it in that case.
1079 (*cur_formspec)->setFormSource(fs_src);
1080 (*cur_formspec)->setTextDest(txt_dest);
1085 #define SIZE_TAG "size[11,5.5]"
1087 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1090 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1091 InventoryManager *invmgr, IGameDef *gamedef,
1092 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1094 std::string formspec =
1095 std::string(FORMSPEC_VERSION_STRING) +
1097 "bgcolor[#320000b4;true]"
1098 "label[4.85,1.35;" + gettext("You died.") + "]"
1099 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1103 /* Note: FormspecFormSource and LocalFormspecHandler
1104 * are deleted by guiFormSpecMenu */
1105 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1106 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1108 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1111 /******************************************************************************/
1112 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1113 InventoryManager *invmgr, IGameDef *gamedef,
1114 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1115 bool singleplayermode)
1118 std::string control_text = strgettext("Default Controls:\n"
1119 "No menu visible:\n"
1120 "- single tap: button activate\n"
1121 "- double tap: place/use\n"
1122 "- slide finger: look around\n"
1123 "Menu/Inventory visible:\n"
1124 "- double tap (outside):\n"
1126 "- touch stack, touch slot:\n"
1128 "- touch&drag, tap 2nd finger\n"
1129 " --> place single item to slot\n"
1132 std::string control_text = strgettext("Default Controls:\n"
1134 "- Space: jump/climb\n"
1135 "- Shift: sneak/go down\n"
1138 "- Mouse: turn/look\n"
1139 "- Mouse left: dig/punch\n"
1140 "- Mouse right: place/use\n"
1141 "- Mouse wheel: select item\n"
1146 float ypos = singleplayermode ? 0.5 : 0.1;
1147 std::ostringstream os;
1149 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1150 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1151 << strgettext("Continue") << "]";
1153 if (!singleplayermode) {
1154 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1155 << strgettext("Change Password") << "]";
1159 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1160 << strgettext("Sound Volume") << "]";
1161 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1162 << strgettext("Change Keys") << "]";
1164 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1165 << strgettext("Exit to Menu") << "]";
1166 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1167 << strgettext("Exit to OS") << "]"
1168 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1169 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1170 << g_build_info << "\n"
1171 << "path_user = " << wrap_rows(porting::path_user, 20)
1175 /* Note: FormspecFormSource and LocalFormspecHandler *
1176 * are deleted by guiFormSpecMenu */
1177 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1178 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1180 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1181 std::string con("btn_continue");
1182 (*cur_formspec)->setFocus(con);
1183 (*cur_formspec)->doPause = true;
1186 /******************************************************************************/
1187 static void updateChat(Client &client, f32 dtime, bool show_debug,
1188 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1189 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1191 // Add chat log output for errors to be shown in chat
1192 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1194 // Get new messages from error log buffer
1195 while (!chat_log_error_buf.empty()) {
1196 chat_backend.addMessage(L"", utf8_to_wide(chat_log_error_buf.get()));
1199 // Get new messages from client
1200 std::wstring message;
1202 while (client.getChatMessage(message)) {
1203 chat_backend.addUnparsedMessage(message);
1206 // Remove old messages
1207 chat_backend.step(dtime);
1209 // Display all messages in a static text element
1210 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1211 std::wstring recent_chat = chat_backend.getRecentChat();
1212 unsigned int line_height = g_fontengine->getLineHeight();
1214 guitext_chat->setText(recent_chat.c_str());
1216 // Update gui element size and position
1217 s32 chat_y = 5 + line_height;
1220 chat_y += line_height;
1222 // first pass to calculate height of text to be set
1223 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1224 porting::getWindowSize().X - 20);
1225 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1226 guitext_chat->setRelativePosition(rect);
1228 //now use real height of text and adjust rect according to this size
1229 rect = core::rect<s32>(10, chat_y, width,
1230 chat_y + guitext_chat->getTextHeight());
1233 guitext_chat->setRelativePosition(rect);
1234 // Don't show chat if disabled or empty or profiler is enabled
1235 guitext_chat->setVisible(
1236 show_chat && recent_chat_count != 0 && !show_profiler);
1240 /****************************************************************************
1241 Fast key cache for main game loop
1242 ****************************************************************************/
1244 /* This is faster than using getKeySetting with the tradeoff that functions
1245 * using it must make sure that it's initialised before using it and there is
1246 * no error handling (for example bounds checking). This is really intended for
1247 * use only in the main running loop of the client (the_game()) where the faster
1248 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1249 * (e.g. formspecs) should continue using getKeySetting().
1253 KeyCache() { populate(); }
1268 KEYMAP_ID_INVENTORY,
1276 KEYMAP_ID_CINEMATIC,
1277 KEYMAP_ID_SCREENSHOT,
1278 KEYMAP_ID_TOGGLE_HUD,
1279 KEYMAP_ID_TOGGLE_CHAT,
1280 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1281 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1282 KEYMAP_ID_TOGGLE_DEBUG,
1283 KEYMAP_ID_TOGGLE_PROFILER,
1284 KEYMAP_ID_CAMERA_MODE,
1285 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1286 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1287 KEYMAP_ID_RANGESELECT,
1289 KEYMAP_ID_QUICKTUNE_NEXT,
1290 KEYMAP_ID_QUICKTUNE_PREV,
1291 KEYMAP_ID_QUICKTUNE_INC,
1292 KEYMAP_ID_QUICKTUNE_DEC,
1294 KEYMAP_ID_DEBUG_STACKS,
1296 // Fake keycode for array size and internal checks
1297 KEYMAP_INTERNAL_ENUM_COUNT
1304 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1307 void KeyCache::populate()
1309 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1310 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1311 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1312 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1313 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1314 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1315 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1317 key[KEYMAP_ID_AUTORUN] = getKeySetting("keymap_autorun");
1319 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1320 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1321 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1322 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1323 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1324 key[KEYMAP_ID_MINIMAP] = getKeySetting("keymap_minimap");
1325 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1326 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1327 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1328 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1329 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1330 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1331 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1332 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1333 = getKeySetting("keymap_toggle_force_fog_off");
1334 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1335 = getKeySetting("keymap_toggle_update_camera");
1336 key[KEYMAP_ID_TOGGLE_DEBUG]
1337 = getKeySetting("keymap_toggle_debug");
1338 key[KEYMAP_ID_TOGGLE_PROFILER]
1339 = getKeySetting("keymap_toggle_profiler");
1340 key[KEYMAP_ID_CAMERA_MODE]
1341 = getKeySetting("keymap_camera_mode");
1342 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1343 = getKeySetting("keymap_increase_viewing_range_min");
1344 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1345 = getKeySetting("keymap_decrease_viewing_range_min");
1346 key[KEYMAP_ID_RANGESELECT]
1347 = getKeySetting("keymap_rangeselect");
1349 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1350 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1351 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1352 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1354 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1358 /****************************************************************************
1360 ****************************************************************************/
1362 const float object_hit_delay = 0.2;
1365 u32 last_time, busy_time, sleep_time;
1369 /* The reason the following structs are not anonymous structs within the
1370 * class is that they are not used by the majority of member functions and
1371 * many functions that do require objects of thse types do not modify them
1372 * (so they can be passed as a const qualified parameter)
1374 struct CameraOrientation {
1375 f32 camera_yaw; // "right/left"
1376 f32 camera_pitch; // "up/down"
1379 struct GameRunData {
1382 PointedThing pointed_old;
1386 bool update_wielded_item_trigger;
1387 bool reset_jump_timer;
1388 float nodig_delay_timer;
1390 float dig_time_complete;
1391 float repeat_rightclick_timer;
1392 float object_hit_delay_timer;
1393 float time_from_last_punch;
1394 ClientActiveObject *selected_object;
1398 float update_draw_list_timer;
1399 float statustext_time;
1403 v3f update_draw_list_last_cam_dir;
1405 u32 profiler_current_page;
1406 u32 profiler_max_page; // Number of pages
1409 float time_of_day_smooth;
1413 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1421 Jitter dtime_jitter, busy_time_jitter;
1424 /* Flags that can, or may, change during main game loop
1426 struct VolatileRunFlags {
1433 bool show_profiler_graph;
1434 bool disable_camera_update;
1435 bool first_loop_after_window_activation;
1436 bool camera_offset_changed;
1440 /****************************************************************************
1442 ****************************************************************************/
1444 /* This is not intended to be a public class. If a public class becomes
1445 * desirable then it may be better to create another 'wrapper' class that
1446 * hides most of the stuff in this class (nothing in this class is required
1447 * by any other file) but exposes the public methods/data only.
1454 bool startup(bool *kill,
1456 InputHandler *input,
1457 IrrlichtDevice *device,
1458 const std::string &map_dir,
1459 const std::string &playername,
1460 const std::string &password,
1461 // If address is "", local server is used and address is updated
1462 std::string *address,
1464 std::string &error_message,
1466 ChatBackend *chat_backend,
1467 const SubgameSpec &gamespec, // Used for local game
1468 bool simple_singleplayer_mode);
1475 void extendedResourceCleanup();
1477 // Basic initialisation
1478 bool init(const std::string &map_dir, std::string *address,
1480 const SubgameSpec &gamespec);
1482 bool createSingleplayerServer(const std::string map_dir,
1483 const SubgameSpec &gamespec, u16 port, std::string *address);
1486 bool createClient(const std::string &playername,
1487 const std::string &password, std::string *address, u16 port);
1490 // Client connection
1491 bool connectToServer(const std::string &playername,
1492 const std::string &password, std::string *address, u16 port,
1493 bool *connect_ok, bool *aborted);
1494 bool getServerContent(bool *aborted);
1498 void updateInteractTimers(GameRunData *runData, f32 dtime);
1499 bool checkConnection();
1500 bool handleCallbacks();
1501 void processQueues();
1502 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1503 const FpsControl &draw_times, f32 dtime);
1504 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1506 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1508 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1510 void processKeyboardInput(VolatileRunFlags *flags,
1511 float *statustext_time,
1513 bool *reset_jump_timer,
1514 u32 *profiler_current_page,
1515 u32 profiler_max_page);
1516 void processItemSelection(u16 *new_playeritem);
1518 void dropSelectedItem();
1519 void openInventory();
1520 void openConsole(float height, const wchar_t *line=NULL);
1521 void toggleFreeMove(float *statustext_time);
1522 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1523 void toggleFast(float *statustext_time);
1524 void toggleNoClip(float *statustext_time);
1525 void toggleCinematic(float *statustext_time);
1526 void toggleAutorun(float *statustext_time);
1528 void toggleChat(float *statustext_time, bool *flag);
1529 void toggleHud(float *statustext_time, bool *flag);
1530 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1531 bool shift_pressed);
1532 void toggleFog(float *statustext_time, bool *flag);
1533 void toggleDebug(float *statustext_time, bool *show_debug,
1534 bool *show_profiler_graph);
1535 void toggleUpdateCamera(float *statustext_time, bool *flag);
1536 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1537 u32 profiler_max_page);
1539 void increaseViewRange(float *statustext_time);
1540 void decreaseViewRange(float *statustext_time);
1541 void toggleFullViewRange(float *statustext_time);
1543 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1544 void updateCameraOrientation(CameraOrientation *cam,
1545 const VolatileRunFlags &flags);
1546 void updatePlayerControl(const CameraOrientation &cam);
1547 void step(f32 *dtime);
1548 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1549 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1550 float time_from_last_punch);
1551 void updateSound(f32 dtime);
1552 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1554 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1555 void handlePointingAtNode(GameRunData *runData,
1556 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1557 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1558 void handlePointingAtObject(GameRunData *runData,
1559 const PointedThing &pointed, const ItemStack &playeritem,
1560 const v3f &player_position, bool show_debug);
1561 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1562 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1564 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1565 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1566 void updateGui(float *statustext_time, const RunStats &stats,
1567 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1568 const CameraOrientation &cam);
1569 void updateProfilerGraphs(ProfilerGraph *graph);
1572 void limitFps(FpsControl *fps_timings, f32 *dtime);
1574 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1575 bool draw_clouds = true);
1577 static void settingChangedCallback(const std::string &setting_name, void *data);
1578 void readSettings();
1581 void handleAndroidChatInput();
1585 InputHandler *input;
1590 IWritableTextureSource *texture_src;
1591 IWritableShaderSource *shader_src;
1593 // When created, these will be filled with data received from the server
1594 IWritableItemDefManager *itemdef_manager;
1595 IWritableNodeDefManager *nodedef_manager;
1597 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1598 ISoundManager *sound;
1599 bool sound_is_dummy;
1600 SoundMaker *soundmaker;
1602 ChatBackend *chat_backend;
1604 GUIFormSpecMenu *current_formspec;
1606 EventManager *eventmgr;
1607 QuicktuneShortcutter *quicktune;
1609 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1610 MapDrawControl *draw_control;
1612 Clouds *clouds; // Free using ->Drop()
1613 Sky *sky; // Free using ->Drop()
1614 Inventory *local_inventory;
1619 This class does take ownership/responsibily for cleaning up etc of any of
1620 these items (e.g. device)
1622 IrrlichtDevice *device;
1623 video::IVideoDriver *driver;
1624 scene::ISceneManager *smgr;
1626 std::string *error_message;
1627 bool *reconnect_requested;
1628 IGameDef *gamedef; // Convenience (same as *client)
1629 scene::ISceneNode *skybox;
1632 bool simple_singleplayer_mode;
1635 /* Pre-calculated values
1637 int crack_animation_length;
1641 gui::IGUIStaticText *guitext; // First line of debug text
1642 gui::IGUIStaticText *guitext2; // Second line of debug text
1643 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1644 gui::IGUIStaticText *guitext_status;
1645 gui::IGUIStaticText *guitext_chat; // Chat text
1646 gui::IGUIStaticText *guitext_profiler; // Profiler text
1648 std::wstring infotext;
1649 std::wstring statustext;
1653 IntervalLimiter profiler_interval;
1656 * TODO: Local caching of settings is not optimal and should at some stage
1657 * be updated to use a global settings object for getting thse values
1658 * (as opposed to the this local caching). This can be addressed in
1661 bool m_cache_doubletap_jump;
1662 bool m_cache_enable_clouds;
1663 bool m_cache_enable_particles;
1664 bool m_cache_enable_fog;
1665 f32 m_cache_mouse_sensitivity;
1666 f32 m_repeat_right_click_time;
1669 bool m_cache_hold_aux1;
1670 bool m_android_chat_open;
1679 itemdef_manager(NULL),
1680 nodedef_manager(NULL),
1682 sound_is_dummy(false),
1685 current_formspec(NULL),
1688 gui_chat_console(NULL),
1693 local_inventory(NULL),
1697 g_settings->registerChangedCallback("doubletap_jump",
1698 &settingChangedCallback, this);
1699 g_settings->registerChangedCallback("enable_clouds",
1700 &settingChangedCallback, this);
1701 g_settings->registerChangedCallback("enable_particles",
1702 &settingChangedCallback, this);
1703 g_settings->registerChangedCallback("enable_fog",
1704 &settingChangedCallback, this);
1705 g_settings->registerChangedCallback("mouse_sensitivity",
1706 &settingChangedCallback, this);
1707 g_settings->registerChangedCallback("repeat_rightclick_time",
1708 &settingChangedCallback, this);
1713 m_cache_hold_aux1 = false; // This is initialised properly later
1720 /****************************************************************************
1722 ****************************************************************************/
1728 if (!sound_is_dummy)
1731 delete server; // deleted first to stop all server threads
1734 delete local_inventory;
1740 delete nodedef_manager;
1741 delete itemdef_manager;
1742 delete draw_control;
1744 extendedResourceCleanup();
1746 g_settings->deregisterChangedCallback("doubletap_jump",
1747 &settingChangedCallback, this);
1748 g_settings->deregisterChangedCallback("enable_clouds",
1749 &settingChangedCallback, this);
1750 g_settings->deregisterChangedCallback("enable_particles",
1751 &settingChangedCallback, this);
1752 g_settings->deregisterChangedCallback("enable_fog",
1753 &settingChangedCallback, this);
1754 g_settings->deregisterChangedCallback("mouse_sensitivity",
1755 &settingChangedCallback, this);
1756 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1757 &settingChangedCallback, this);
1760 bool Game::startup(bool *kill,
1762 InputHandler *input,
1763 IrrlichtDevice *device,
1764 const std::string &map_dir,
1765 const std::string &playername,
1766 const std::string &password,
1767 std::string *address, // can change if simple_singleplayer_mode
1769 std::string &error_message,
1771 ChatBackend *chat_backend,
1772 const SubgameSpec &gamespec,
1773 bool simple_singleplayer_mode)
1776 this->device = device;
1778 this->error_message = &error_message;
1779 this->reconnect_requested = reconnect;
1780 this->random_input = random_input;
1781 this->input = input;
1782 this->chat_backend = chat_backend;
1783 this->simple_singleplayer_mode = simple_singleplayer_mode;
1785 driver = device->getVideoDriver();
1786 smgr = device->getSceneManager();
1788 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1790 if (!init(map_dir, address, port, gamespec))
1793 if (!createClient(playername, password, address, port))
1802 ProfilerGraph graph;
1803 RunStats stats = { 0 };
1804 CameraOrientation cam_view_target = { 0 };
1805 CameraOrientation cam_view = { 0 };
1806 GameRunData runData = { 0 };
1807 FpsControl draw_times = { 0 };
1808 VolatileRunFlags flags = { 0 };
1809 f32 dtime; // in seconds
1811 runData.time_from_last_punch = 10.0;
1812 runData.profiler_max_page = 3;
1813 runData.update_wielded_item_trigger = true;
1815 flags.show_chat = true;
1816 flags.show_hud = true;
1817 flags.show_minimap = g_settings->getBool("enable_minimap");
1818 flags.show_debug = g_settings->getBool("show_debug");
1819 flags.invert_mouse = g_settings->getBool("invert_mouse");
1820 flags.first_loop_after_window_activation = true;
1822 /* Clear the profiler */
1823 Profiler::GraphValues dummyvalues;
1824 g_profiler->graphGet(dummyvalues);
1826 draw_times.last_time = device->getTimer()->getTime();
1828 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1830 &flags.force_fog_off,
1834 set_light_table(g_settings->getFloat("display_gamma"));
1837 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1838 && client->checkPrivilege("fast");
1841 while (device->run()
1842 && !(*kill || g_gamecallback->shutdown_requested
1843 || (server && server->getShutdownRequested()))) {
1845 /* Must be called immediately after a device->run() call because it
1846 * uses device->getTimer()->getTime()
1848 limitFps(&draw_times, &dtime);
1850 updateStats(&stats, draw_times, dtime);
1851 updateInteractTimers(&runData, dtime);
1853 if (!checkConnection())
1855 if (!handleCallbacks())
1861 hud->resizeHotbar();
1863 updateProfilers(runData, stats, draw_times, dtime);
1864 processUserInput(&flags, &runData, dtime);
1865 // Update camera before player movement to avoid camera lag of one frame
1866 updateCameraDirection(&cam_view_target, &flags);
1867 float cam_smoothing = 0;
1868 if (g_settings->getBool("cinematic"))
1869 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1871 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1872 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1873 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1874 cam_view.camera_yaw) * cam_smoothing;
1875 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1876 cam_view.camera_pitch) * cam_smoothing;
1877 updatePlayerControl(cam_view);
1879 processClientEvents(&cam_view_target, &runData.damage_flash);
1880 updateCamera(&flags, draw_times.busy_time, dtime,
1881 runData.time_from_last_punch);
1883 processPlayerInteraction(&runData, dtime, flags.show_hud,
1885 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1886 updateProfilerGraphs(&graph);
1888 // Update if minimap has been disabled by the server
1889 flags.show_minimap &= !client->isMinimapDisabledByServer();
1894 void Game::shutdown()
1896 if (g_settings->get("3d_mode") == "pageflip") {
1897 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1900 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1905 if (gui_chat_console)
1906 gui_chat_console->drop();
1912 while (g_menumgr.menuCount() > 0) {
1913 g_menumgr.m_stack.front()->setVisible(false);
1914 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1917 if (current_formspec) {
1918 current_formspec->drop();
1919 current_formspec = NULL;
1922 chat_backend->addMessage(L"", L"# Disconnected.");
1923 chat_backend->addMessage(L"", L"");
1927 while (!client->isShutdown()) {
1928 assert(texture_src != NULL);
1929 assert(shader_src != NULL);
1930 texture_src->processQueue();
1931 shader_src->processQueue();
1938 /****************************************************************************/
1939 /****************************************************************************
1941 ****************************************************************************/
1942 /****************************************************************************/
1945 const std::string &map_dir,
1946 std::string *address,
1948 const SubgameSpec &gamespec)
1950 showOverlayMessage(wgettext("Loading..."), 0, 0);
1952 texture_src = createTextureSource(device);
1953 shader_src = createShaderSource(device);
1955 itemdef_manager = createItemDefManager();
1956 nodedef_manager = createNodeDefManager();
1958 eventmgr = new EventManager();
1959 quicktune = new QuicktuneShortcutter();
1961 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1962 && eventmgr && quicktune))
1968 // Create a server if not connecting to an existing one
1969 if (*address == "") {
1970 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1977 bool Game::initSound()
1980 if (g_settings->getBool("enable_sound")) {
1981 infostream << "Attempting to use OpenAL audio" << std::endl;
1982 sound = createOpenALSoundManager(&soundfetcher);
1984 infostream << "Failed to initialize OpenAL audio" << std::endl;
1986 infostream << "Sound disabled." << std::endl;
1990 infostream << "Using dummy audio." << std::endl;
1991 sound = &dummySoundManager;
1992 sound_is_dummy = true;
1995 soundmaker = new SoundMaker(sound, nodedef_manager);
1999 soundmaker->registerReceiver(eventmgr);
2004 bool Game::createSingleplayerServer(const std::string map_dir,
2005 const SubgameSpec &gamespec, u16 port, std::string *address)
2007 showOverlayMessage(wgettext("Creating server..."), 0, 5);
2009 std::string bind_str = g_settings->get("bind_address");
2010 Address bind_addr(0, 0, 0, 0, port);
2012 if (g_settings->getBool("ipv6_server")) {
2013 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2017 bind_addr.Resolve(bind_str.c_str());
2018 } catch (ResolveError &e) {
2019 infostream << "Resolving bind address \"" << bind_str
2020 << "\" failed: " << e.what()
2021 << " -- Listening on all addresses." << std::endl;
2024 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2025 *error_message = "Unable to listen on " +
2026 bind_addr.serializeString() +
2027 " because IPv6 is disabled";
2028 errorstream << *error_message << std::endl;
2032 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2033 bind_addr.isIPv6());
2035 server->start(bind_addr);
2040 bool Game::createClient(const std::string &playername,
2041 const std::string &password, std::string *address, u16 port)
2043 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2045 draw_control = new MapDrawControl;
2049 bool could_connect, connect_aborted;
2051 if (!connectToServer(playername, password, address, port,
2052 &could_connect, &connect_aborted))
2055 if (!could_connect) {
2056 if (error_message->empty() && !connect_aborted) {
2057 // Should not happen if error messages are set properly
2058 *error_message = "Connection failed for unknown reason";
2059 errorstream << *error_message << std::endl;
2064 if (!getServerContent(&connect_aborted)) {
2065 if (error_message->empty() && !connect_aborted) {
2066 // Should not happen if error messages are set properly
2067 *error_message = "Connection failed for unknown reason";
2068 errorstream << *error_message << std::endl;
2073 // Update cached textures, meshes and materials
2074 client->afterContentReceived(device);
2078 camera = new Camera(smgr, *draw_control, gamedef);
2079 if (!camera || !camera->successfullyCreated(*error_message))
2081 client->setCamera(camera);
2085 if (m_cache_enable_clouds) {
2086 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2088 *error_message = "Memory allocation error (clouds)";
2089 errorstream << *error_message << std::endl;
2096 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2097 skybox = NULL; // This is used/set later on in the main run loop
2099 local_inventory = new Inventory(itemdef_manager);
2101 if (!(sky && local_inventory)) {
2102 *error_message = "Memory allocation error (sky or local inventory)";
2103 errorstream << *error_message << std::endl;
2107 /* Pre-calculated values
2109 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2111 v2u32 size = t->getOriginalSize();
2112 crack_animation_length = size.Y / size.X;
2114 crack_animation_length = 5;
2120 /* Set window caption
2122 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2124 str += driver->getName();
2126 device->setWindowCaption(str.c_str());
2128 LocalPlayer *player = client->getEnv().getLocalPlayer();
2129 player->hurt_tilt_timer = 0;
2130 player->hurt_tilt_strength = 0;
2132 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2135 *error_message = "Memory error: could not create HUD";
2136 errorstream << *error_message << std::endl;
2140 mapper = client->getMapper();
2141 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2146 bool Game::initGui()
2148 // First line of debug text
2149 guitext = guienv->addStaticText(
2150 utf8_to_wide(PROJECT_NAME_C).c_str(),
2151 core::rect<s32>(0, 0, 0, 0),
2152 false, false, guiroot);
2154 // Second line of debug text
2155 guitext2 = guienv->addStaticText(
2157 core::rect<s32>(0, 0, 0, 0),
2158 false, false, guiroot);
2160 // At the middle of the screen
2161 // Object infos are shown in this
2162 guitext_info = guienv->addStaticText(
2164 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2165 false, true, guiroot);
2167 // Status text (displays info when showing and hiding GUI stuff, etc.)
2168 guitext_status = guienv->addStaticText(
2170 core::rect<s32>(0, 0, 0, 0),
2171 false, false, guiroot);
2172 guitext_status->setVisible(false);
2175 guitext_chat = guienv->addStaticText(
2177 core::rect<s32>(0, 0, 0, 0),
2178 //false, false); // Disable word wrap as of now
2179 false, true, guiroot);
2180 // Remove stale "recent" chat messages from previous connections
2181 chat_backend->clearRecentChat();
2183 // Chat backend and console
2184 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2185 -1, chat_backend, client, &g_menumgr);
2186 if (!gui_chat_console) {
2187 *error_message = "Could not allocate memory for chat console";
2188 errorstream << *error_message << std::endl;
2192 // Profiler text (size is updated when text is updated)
2193 guitext_profiler = guienv->addStaticText(
2195 core::rect<s32>(0, 0, 0, 0),
2196 false, false, guiroot);
2197 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2198 guitext_profiler->setVisible(false);
2199 guitext_profiler->setWordWrap(true);
2201 #ifdef HAVE_TOUCHSCREENGUI
2203 if (g_touchscreengui)
2204 g_touchscreengui->init(texture_src);
2211 bool Game::connectToServer(const std::string &playername,
2212 const std::string &password, std::string *address, u16 port,
2213 bool *connect_ok, bool *aborted)
2215 *connect_ok = false; // Let's not be overly optimistic
2217 bool local_server_mode = false;
2219 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2221 Address connect_address(0, 0, 0, 0, port);
2224 connect_address.Resolve(address->c_str());
2226 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2227 //connect_address.Resolve("localhost");
2228 if (connect_address.isIPv6()) {
2229 IPv6AddressBytes addr_bytes;
2230 addr_bytes.bytes[15] = 1;
2231 connect_address.setAddress(&addr_bytes);
2233 connect_address.setAddress(127, 0, 0, 1);
2235 local_server_mode = true;
2237 } catch (ResolveError &e) {
2238 *error_message = std::string("Couldn't resolve address: ") + e.what();
2239 errorstream << *error_message << std::endl;
2243 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2244 *error_message = "Unable to connect to " +
2245 connect_address.serializeString() +
2246 " because IPv6 is disabled";
2247 errorstream << *error_message << std::endl;
2251 client = new Client(device,
2252 playername.c_str(), password,
2253 *draw_control, texture_src, shader_src,
2254 itemdef_manager, nodedef_manager, sound, eventmgr,
2255 connect_address.isIPv6());
2260 gamedef = client; // Client acts as our GameDef
2262 infostream << "Connecting to server at ";
2263 connect_address.print(&infostream);
2264 infostream << std::endl;
2266 client->connect(connect_address, *address,
2267 simple_singleplayer_mode || local_server_mode);
2270 Wait for server to accept connection
2276 FpsControl fps_control = { 0 };
2278 f32 wait_time = 0; // in seconds
2280 fps_control.last_time = device->getTimer()->getTime();
2282 while (device->run()) {
2284 limitFps(&fps_control, &dtime);
2286 // Update client and server
2287 client->step(dtime);
2290 server->step(dtime);
2293 if (client->getState() == LC_Init) {
2299 if (client->accessDenied()) {
2300 *error_message = "Access denied. Reason: "
2301 + client->accessDeniedReason();
2302 *reconnect_requested = client->reconnectRequested();
2303 errorstream << *error_message << std::endl;
2307 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2309 infostream << "Connect aborted [Escape]" << std::endl;
2314 // Only time out if we aren't waiting for the server we started
2315 if ((*address != "") && (wait_time > 10)) {
2316 *error_message = "Connection timed out.";
2317 errorstream << *error_message << std::endl;
2322 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2324 } catch (con::PeerNotFoundException &e) {
2325 // TODO: Should something be done here? At least an info/error
2333 bool Game::getServerContent(bool *aborted)
2337 FpsControl fps_control = { 0 };
2338 f32 dtime; // in seconds
2340 fps_control.last_time = device->getTimer()->getTime();
2342 while (device->run()) {
2344 limitFps(&fps_control, &dtime);
2346 // Update client and server
2347 client->step(dtime);
2350 server->step(dtime);
2353 if (client->mediaReceived() && client->itemdefReceived() &&
2354 client->nodedefReceived()) {
2359 if (!checkConnection())
2362 if (client->getState() < LC_Init) {
2363 *error_message = "Client disconnected";
2364 errorstream << *error_message << std::endl;
2368 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2370 infostream << "Connect aborted [Escape]" << std::endl;
2377 if (!client->itemdefReceived()) {
2378 const wchar_t *text = wgettext("Item definitions...");
2380 draw_load_screen(text, device, guienv, dtime, progress);
2382 } else if (!client->nodedefReceived()) {
2383 const wchar_t *text = wgettext("Node definitions...");
2385 draw_load_screen(text, device, guienv, dtime, progress);
2388 std::stringstream message;
2389 message.precision(3);
2390 message << gettext("Media...");
2392 if ((USE_CURL == 0) ||
2393 (!g_settings->getBool("enable_remote_media_server"))) {
2394 float cur = client->getCurRate();
2395 std::string cur_unit = gettext("KiB/s");
2399 cur_unit = gettext("MiB/s");
2402 message << " (" << cur << ' ' << cur_unit << ")";
2405 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2406 draw_load_screen(utf8_to_wide(message.str()), device,
2407 guienv, dtime, progress);
2415 /****************************************************************************/
2416 /****************************************************************************
2418 ****************************************************************************/
2419 /****************************************************************************/
2421 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2423 if (runData->nodig_delay_timer >= 0)
2424 runData->nodig_delay_timer -= dtime;
2426 if (runData->object_hit_delay_timer >= 0)
2427 runData->object_hit_delay_timer -= dtime;
2429 runData->time_from_last_punch += dtime;
2433 /* returns false if game should exit, otherwise true
2435 inline bool Game::checkConnection()
2437 if (client->accessDenied()) {
2438 *error_message = "Access denied. Reason: "
2439 + client->accessDeniedReason();
2440 *reconnect_requested = client->reconnectRequested();
2441 errorstream << *error_message << std::endl;
2449 /* returns false if game should exit, otherwise true
2451 inline bool Game::handleCallbacks()
2453 if (g_gamecallback->disconnect_requested) {
2454 g_gamecallback->disconnect_requested = false;
2458 if (g_gamecallback->changepassword_requested) {
2459 (new GUIPasswordChange(guienv, guiroot, -1,
2460 &g_menumgr, client))->drop();
2461 g_gamecallback->changepassword_requested = false;
2464 if (g_gamecallback->changevolume_requested) {
2465 (new GUIVolumeChange(guienv, guiroot, -1,
2466 &g_menumgr, client))->drop();
2467 g_gamecallback->changevolume_requested = false;
2470 if (g_gamecallback->keyconfig_requested) {
2471 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2472 &g_menumgr))->drop();
2473 g_gamecallback->keyconfig_requested = false;
2476 if (g_gamecallback->keyconfig_changed) {
2477 keycache.populate(); // update the cache with new settings
2478 g_gamecallback->keyconfig_changed = false;
2485 void Game::processQueues()
2487 texture_src->processQueue();
2488 itemdef_manager->processQueue(gamedef);
2489 shader_src->processQueue();
2493 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2494 const FpsControl &draw_times, f32 dtime)
2496 float profiler_print_interval =
2497 g_settings->getFloat("profiler_print_interval");
2498 bool print_to_log = true;
2500 if (profiler_print_interval == 0) {
2501 print_to_log = false;
2502 profiler_print_interval = 5;
2505 if (profiler_interval.step(dtime, profiler_print_interval)) {
2507 infostream << "Profiler:" << std::endl;
2508 g_profiler->print(infostream);
2511 update_profiler_gui(guitext_profiler, g_fontengine,
2512 runData.profiler_current_page, runData.profiler_max_page,
2513 driver->getScreenSize().Height);
2515 g_profiler->clear();
2518 addProfilerGraphs(stats, draw_times, dtime);
2522 void Game::addProfilerGraphs(const RunStats &stats,
2523 const FpsControl &draw_times, f32 dtime)
2525 g_profiler->graphAdd("mainloop_other",
2526 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2528 if (draw_times.sleep_time != 0)
2529 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2530 g_profiler->graphAdd("mainloop_dtime", dtime);
2532 g_profiler->add("Elapsed time", dtime);
2533 g_profiler->avg("FPS", 1. / dtime);
2537 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2544 /* Time average and jitter calculation
2546 jp = &stats->dtime_jitter;
2547 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2549 jitter = dtime - jp->avg;
2551 if (jitter > jp->max)
2554 jp->counter += dtime;
2556 if (jp->counter > 0.0) {
2558 jp->max_sample = jp->max;
2559 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2563 /* Busytime average and jitter calculation
2565 jp = &stats->busy_time_jitter;
2566 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2568 jitter = draw_times.busy_time - jp->avg;
2570 if (jitter > jp->max)
2572 if (jitter < jp->min)
2575 jp->counter += dtime;
2577 if (jp->counter > 0.0) {
2579 jp->max_sample = jp->max;
2580 jp->min_sample = jp->min;
2588 /****************************************************************************
2590 ****************************************************************************/
2592 void Game::processUserInput(VolatileRunFlags *flags,
2593 GameRunData *runData, f32 dtime)
2595 // Reset input if window not active or some menu is active
2596 if (device->isWindowActive() == false
2597 || noMenuActive() == false
2598 || guienv->hasFocus(gui_chat_console)) {
2600 #ifdef HAVE_TOUCHSCREENGUI
2601 g_touchscreengui->hide();
2604 #ifdef HAVE_TOUCHSCREENGUI
2605 else if (g_touchscreengui) {
2606 /* on touchscreengui step may generate own input events which ain't
2607 * what we want in case we just did clear them */
2608 g_touchscreengui->step(dtime);
2612 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2613 gui_chat_console->closeConsoleAtOnce();
2616 // Input handler step() (used by the random input generator)
2620 if (current_formspec != NULL)
2621 current_formspec->getAndroidUIInput();
2623 handleAndroidChatInput();
2626 // Increase timer for double tap of "keymap_jump"
2627 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2628 runData->jump_timer += dtime;
2630 processKeyboardInput(
2632 &runData->statustext_time,
2633 &runData->jump_timer,
2634 &runData->reset_jump_timer,
2635 &runData->profiler_current_page,
2636 runData->profiler_max_page);
2638 processItemSelection(&runData->new_playeritem);
2642 void Game::processKeyboardInput(VolatileRunFlags *flags,
2643 float *statustext_time,
2645 bool *reset_jump_timer,
2646 u32 *profiler_current_page,
2647 u32 profiler_max_page)
2650 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2652 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2654 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_AUTORUN])) {
2655 toggleAutorun(statustext_time);
2656 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2658 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2659 if (!gui_chat_console->isOpenInhibited()) {
2660 show_pause_menu(¤t_formspec, client, gamedef,
2661 texture_src, device, simple_singleplayer_mode);
2663 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2664 openConsole(0.2, L"");
2665 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2666 openConsole(0.2, L"/");
2667 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2669 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2670 toggleFreeMove(statustext_time);
2671 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2672 toggleFreeMoveAlt(statustext_time, jump_timer);
2673 *reset_jump_timer = true;
2674 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2675 toggleFast(statustext_time);
2676 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2677 toggleNoClip(statustext_time);
2678 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2679 toggleCinematic(statustext_time);
2680 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2681 client->makeScreenshot(device);
2682 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2683 toggleHud(statustext_time, &flags->show_hud);
2684 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_MINIMAP])) {
2685 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2686 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]));
2687 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2688 toggleChat(statustext_time, &flags->show_chat);
2689 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2690 toggleFog(statustext_time, &flags->force_fog_off);
2691 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2692 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2693 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2694 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2695 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2696 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2697 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2698 increaseViewRange(statustext_time);
2699 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2700 decreaseViewRange(statustext_time);
2701 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2702 toggleFullViewRange(statustext_time);
2703 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT])) {
2705 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV])) {
2707 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC])) {
2709 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC])) {
2711 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2712 // Print debug stacks
2713 dstream << "-----------------------------------------"
2715 dstream << "Printing debug stacks:" << std::endl;
2716 dstream << "-----------------------------------------"
2718 debug_stacks_print();
2721 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2722 *reset_jump_timer = false;
2728 if (quicktune->hasMessage()) {
2729 std::string msg = quicktune->getMessage();
2730 statustext = utf8_to_wide(msg);
2731 *statustext_time = 0;
2736 void Game::processItemSelection(u16 *new_playeritem)
2738 LocalPlayer *player = client->getEnv().getLocalPlayer();
2740 /* Item selection using mouse wheel
2742 *new_playeritem = client->getPlayerItem();
2744 s32 wheel = input->getMouseWheel();
2745 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2746 player->hud_hotbar_itemcount - 1);
2749 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2751 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2755 /* Item selection using keyboard
2757 for (u16 i = 0; i < 10; i++) {
2758 static const KeyPress *item_keys[10] = {
2759 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2760 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2761 NumberKey + 9, NumberKey + 0,
2764 if (input->wasKeyDown(*item_keys[i])) {
2765 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2766 *new_playeritem = i;
2767 infostream << "Selected item: " << new_playeritem << std::endl;
2775 void Game::dropSelectedItem()
2777 IDropAction *a = new IDropAction();
2779 a->from_inv.setCurrentPlayer();
2780 a->from_list = "main";
2781 a->from_i = client->getPlayerItem();
2782 client->inventoryAction(a);
2786 void Game::openInventory()
2789 * Don't permit to open inventory is CAO or player doesn't exists.
2790 * This prevent showing an empty inventory at player load
2793 LocalPlayer *player = client->getEnv().getLocalPlayer();
2794 if (player == NULL || player->getCAO() == NULL)
2797 infostream << "the_game: " << "Launching inventory" << std::endl;
2799 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2800 TextDest *txt_dst = new TextDestPlayerInventory(client);
2802 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2803 device, fs_src, txt_dst, client);
2805 InventoryLocation inventoryloc;
2806 inventoryloc.setCurrentPlayer();
2807 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2811 void Game::openConsole(float height, const wchar_t *line)
2814 porting::showInputDialog(gettext("ok"), "", "", 2);
2815 m_android_chat_open = true;
2817 if (gui_chat_console->isOpenInhibited())
2819 gui_chat_console->openConsole(height);
2821 gui_chat_console->setCloseOnEnter(true);
2822 gui_chat_console->replaceAndAddToHistory(line);
2828 void Game::handleAndroidChatInput()
2830 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2831 std::string text = porting::getInputDialogValue();
2832 client->typeChatMessage(utf8_to_wide(text));
2838 void Game::toggleFreeMove(float *statustext_time)
2840 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2842 bool free_move = !g_settings->getBool("free_move");
2843 g_settings->set("free_move", bool_to_cstr(free_move));
2845 *statustext_time = 0;
2846 statustext = msg[free_move];
2847 if (free_move && !client->checkPrivilege("fly"))
2848 statustext += L" (note: no 'fly' privilege)";
2852 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2854 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2855 toggleFreeMove(statustext_time);
2859 void Game::toggleFast(float *statustext_time)
2861 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2862 bool fast_move = !g_settings->getBool("fast_move");
2863 g_settings->set("fast_move", bool_to_cstr(fast_move));
2865 *statustext_time = 0;
2866 statustext = msg[fast_move];
2868 bool has_fast_privs = client->checkPrivilege("fast");
2870 if (fast_move && !has_fast_privs)
2871 statustext += L" (note: no 'fast' privilege)";
2874 m_cache_hold_aux1 = fast_move && has_fast_privs;
2879 void Game::toggleNoClip(float *statustext_time)
2881 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2882 bool noclip = !g_settings->getBool("noclip");
2883 g_settings->set("noclip", bool_to_cstr(noclip));
2885 *statustext_time = 0;
2886 statustext = msg[noclip];
2888 if (noclip && !client->checkPrivilege("noclip"))
2889 statustext += L" (note: no 'noclip' privilege)";
2892 void Game::toggleCinematic(float *statustext_time)
2894 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2895 bool cinematic = !g_settings->getBool("cinematic");
2896 g_settings->set("cinematic", bool_to_cstr(cinematic));
2898 *statustext_time = 0;
2899 statustext = msg[cinematic];
2902 // Add WoW-style autorun by toggling continuous forward.
2903 void Game::toggleAutorun(float *statustext_time)
2905 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2906 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2907 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2909 *statustext_time = 0;
2910 statustext = msg[autorun_enabled ? 1 : 0];
2913 void Game::toggleChat(float *statustext_time, bool *flag)
2915 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2918 *statustext_time = 0;
2919 statustext = msg[*flag];
2923 void Game::toggleHud(float *statustext_time, bool *flag)
2925 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2928 *statustext_time = 0;
2929 statustext = msg[*flag];
2932 void Game::toggleMinimap(float *statustext_time, bool *flag,
2933 bool show_hud, bool shift_pressed)
2935 if (!show_hud || !g_settings->getBool("enable_minimap"))
2938 if (shift_pressed) {
2939 mapper->toggleMinimapShape();
2943 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2945 MinimapMode mode = MINIMAP_MODE_OFF;
2946 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2947 mode = mapper->getMinimapMode();
2948 mode = (MinimapMode)((int)mode + 1);
2953 case MINIMAP_MODE_SURFACEx1:
2954 statustext = L"Minimap in surface mode, Zoom x1";
2956 case MINIMAP_MODE_SURFACEx2:
2957 statustext = L"Minimap in surface mode, Zoom x2";
2959 case MINIMAP_MODE_SURFACEx4:
2960 statustext = L"Minimap in surface mode, Zoom x4";
2962 case MINIMAP_MODE_RADARx1:
2963 statustext = L"Minimap in radar mode, Zoom x1";
2965 case MINIMAP_MODE_RADARx2:
2966 statustext = L"Minimap in radar mode, Zoom x2";
2968 case MINIMAP_MODE_RADARx4:
2969 statustext = L"Minimap in radar mode, Zoom x4";
2972 mode = MINIMAP_MODE_OFF;
2974 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2975 L"Minimap hidden" : L"Minimap disabled by server";
2978 *statustext_time = 0;
2979 mapper->setMinimapMode(mode);
2982 void Game::toggleFog(float *statustext_time, bool *flag)
2984 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2987 *statustext_time = 0;
2988 statustext = msg[*flag];
2992 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2993 bool *show_profiler_graph)
2995 // Initial / 3x toggle: Chat only
2996 // 1x toggle: Debug text with chat
2997 // 2x toggle: Debug text with profiler graph
3000 *show_profiler_graph = false;
3001 statustext = L"Debug info shown";
3002 } else if (*show_profiler_graph) {
3003 *show_debug = false;
3004 *show_profiler_graph = false;
3005 statustext = L"Debug info and profiler graph hidden";
3007 *show_profiler_graph = true;
3008 statustext = L"Profiler graph shown";
3010 *statustext_time = 0;
3014 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3016 static const wchar_t *msg[] = {
3017 L"Camera update enabled",
3018 L"Camera update disabled"
3022 *statustext_time = 0;
3023 statustext = msg[*flag];
3027 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3028 u32 profiler_max_page)
3030 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3032 // FIXME: This updates the profiler with incomplete values
3033 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3034 profiler_max_page, driver->getScreenSize().Height);
3036 if (*profiler_current_page != 0) {
3037 std::wstringstream sstr;
3038 sstr << "Profiler shown (page " << *profiler_current_page
3039 << " of " << profiler_max_page << ")";
3040 statustext = sstr.str();
3042 statustext = L"Profiler hidden";
3044 *statustext_time = 0;
3048 void Game::increaseViewRange(float *statustext_time)
3050 s16 range = g_settings->getS16("viewing_range");
3051 s16 range_new = range + 10;
3052 g_settings->set("viewing_range", itos(range_new));
3053 statustext = utf8_to_wide("Viewing range changed to "
3055 *statustext_time = 0;
3059 void Game::decreaseViewRange(float *statustext_time)
3061 s16 range = g_settings->getS16("viewing_range");
3062 s16 range_new = range - 10;
3067 g_settings->set("viewing_range", itos(range_new));
3068 statustext = utf8_to_wide("Viewing range changed to "
3070 *statustext_time = 0;
3074 void Game::toggleFullViewRange(float *statustext_time)
3076 static const wchar_t *msg[] = {
3077 L"Disabled full viewing range",
3078 L"Enabled full viewing range"
3081 draw_control->range_all = !draw_control->range_all;
3082 infostream << msg[draw_control->range_all] << std::endl;
3083 statustext = msg[draw_control->range_all];
3084 *statustext_time = 0;
3088 void Game::updateCameraDirection(CameraOrientation *cam,
3089 VolatileRunFlags *flags)
3091 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3094 if (!random_input) {
3095 // Mac OSX gets upset if this is set every frame
3096 if (device->getCursorControl()->isVisible())
3097 device->getCursorControl()->setVisible(false);
3101 if (flags->first_loop_after_window_activation)
3102 flags->first_loop_after_window_activation = false;
3104 updateCameraOrientation(cam, *flags);
3106 input->setMousePos((driver->getScreenSize().Width / 2),
3107 (driver->getScreenSize().Height / 2));
3111 // Mac OSX gets upset if this is set every frame
3112 if (device->getCursorControl()->isVisible() == false)
3113 device->getCursorControl()->setVisible(true);
3116 if (!flags->first_loop_after_window_activation)
3117 flags->first_loop_after_window_activation = true;
3123 void Game::updateCameraOrientation(CameraOrientation *cam,
3124 const VolatileRunFlags &flags)
3126 #ifdef HAVE_TOUCHSCREENGUI
3127 if (g_touchscreengui) {
3128 cam->camera_yaw = g_touchscreengui->getYaw();
3129 cam->camera_pitch = g_touchscreengui->getPitch();
3132 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3133 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3135 if (flags.invert_mouse
3136 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3140 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3141 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3143 #ifdef HAVE_TOUCHSCREENGUI
3147 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3151 void Game::updatePlayerControl(const CameraOrientation &cam)
3153 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3155 PlayerControl control(
3156 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
3157 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
3158 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
3159 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
3160 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
3161 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
3162 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
3163 input->getLeftState(),
3164 input->getRightState(),
3170 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
3171 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
3172 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
3173 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
3174 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
3175 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
3176 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
3177 ( (u32)(input->getLeftState() & 0x1) << 7) |
3178 ( (u32)(input->getRightState() & 0x1) << 8
3182 /* For Android, simulate holding down AUX1 (fast move) if the user has
3183 * the fast_move setting toggled on. If there is an aux1 key defined for
3184 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3187 if (m_cache_hold_aux1) {
3188 control.aux1 = control.aux1 ^ true;
3189 keypress_bits ^= ((u32)(1U << 5));
3193 client->setPlayerControl(control);
3194 LocalPlayer *player = client->getEnv().getLocalPlayer();
3195 player->keyPressed = keypress_bits;
3201 inline void Game::step(f32 *dtime)
3203 bool can_be_and_is_paused =
3204 (simple_singleplayer_mode && g_menumgr.pausesGame());
3206 if (can_be_and_is_paused) { // This is for a singleplayer server
3207 *dtime = 0; // No time passes
3209 if (server != NULL) {
3210 //TimeTaker timer("server->step(dtime)");
3211 server->step(*dtime);
3214 //TimeTaker timer("client.step(dtime)");
3215 client->step(*dtime);
3220 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3222 ClientEvent event = client->getClientEvent();
3224 LocalPlayer *player = client->getEnv().getLocalPlayer();
3226 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3228 if (event.type == CE_PLAYER_DAMAGE &&
3229 client->getHP() != 0) {
3230 //u16 damage = event.player_damage.amount;
3231 //infostream<<"Player damage: "<<damage<<std::endl;
3233 *damage_flash += 100.0;
3234 *damage_flash += 8.0 * event.player_damage.amount;
3236 player->hurt_tilt_timer = 1.5;
3237 player->hurt_tilt_strength = event.player_damage.amount / 4;
3238 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3240 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3241 gamedef->event()->put(e);
3242 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3243 cam->camera_yaw = event.player_force_move.yaw;
3244 cam->camera_pitch = event.player_force_move.pitch;
3245 } else if (event.type == CE_DEATHSCREEN) {
3246 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3249 chat_backend->addMessage(L"", L"You died.");
3251 /* Handle visualization */
3253 player->hurt_tilt_timer = 0;
3254 player->hurt_tilt_strength = 0;
3256 } else if (event.type == CE_SHOW_FORMSPEC) {
3257 FormspecFormSource *fs_src =
3258 new FormspecFormSource(*(event.show_formspec.formspec));
3259 TextDestPlayerInventory *txt_dst =
3260 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3262 create_formspec_menu(¤t_formspec, client, gamedef,
3263 texture_src, device, fs_src, txt_dst, client);
3265 delete(event.show_formspec.formspec);
3266 delete(event.show_formspec.formname);
3267 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3268 (event.type == CE_ADD_PARTICLESPAWNER) ||
3269 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3270 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3272 } else if (event.type == CE_HUDADD) {
3273 u32 id = event.hudadd.id;
3275 LocalPlayer *player = client->getEnv().getLocalPlayer();
3276 HudElement *e = player->getHud(id);
3279 delete event.hudadd.pos;
3280 delete event.hudadd.name;
3281 delete event.hudadd.scale;
3282 delete event.hudadd.text;
3283 delete event.hudadd.align;
3284 delete event.hudadd.offset;
3285 delete event.hudadd.world_pos;
3286 delete event.hudadd.size;
3291 e->type = (HudElementType)event.hudadd.type;
3292 e->pos = *event.hudadd.pos;
3293 e->name = *event.hudadd.name;
3294 e->scale = *event.hudadd.scale;
3295 e->text = *event.hudadd.text;
3296 e->number = event.hudadd.number;
3297 e->item = event.hudadd.item;
3298 e->dir = event.hudadd.dir;
3299 e->align = *event.hudadd.align;
3300 e->offset = *event.hudadd.offset;
3301 e->world_pos = *event.hudadd.world_pos;
3302 e->size = *event.hudadd.size;
3304 u32 new_id = player->addHud(e);
3305 //if this isn't true our huds aren't consistent
3306 sanity_check(new_id == id);
3308 delete event.hudadd.pos;
3309 delete event.hudadd.name;
3310 delete event.hudadd.scale;
3311 delete event.hudadd.text;
3312 delete event.hudadd.align;
3313 delete event.hudadd.offset;
3314 delete event.hudadd.world_pos;
3315 delete event.hudadd.size;
3316 } else if (event.type == CE_HUDRM) {
3317 HudElement *e = player->removeHud(event.hudrm.id);
3321 } else if (event.type == CE_HUDCHANGE) {
3322 u32 id = event.hudchange.id;
3323 HudElement *e = player->getHud(id);
3326 delete event.hudchange.v3fdata;
3327 delete event.hudchange.v2fdata;
3328 delete event.hudchange.sdata;
3329 delete event.hudchange.v2s32data;
3333 switch (event.hudchange.stat) {
3335 e->pos = *event.hudchange.v2fdata;
3339 e->name = *event.hudchange.sdata;
3342 case HUD_STAT_SCALE:
3343 e->scale = *event.hudchange.v2fdata;
3347 e->text = *event.hudchange.sdata;
3350 case HUD_STAT_NUMBER:
3351 e->number = event.hudchange.data;
3355 e->item = event.hudchange.data;
3359 e->dir = event.hudchange.data;
3362 case HUD_STAT_ALIGN:
3363 e->align = *event.hudchange.v2fdata;
3366 case HUD_STAT_OFFSET:
3367 e->offset = *event.hudchange.v2fdata;
3370 case HUD_STAT_WORLD_POS:
3371 e->world_pos = *event.hudchange.v3fdata;
3375 e->size = *event.hudchange.v2s32data;
3379 delete event.hudchange.v3fdata;
3380 delete event.hudchange.v2fdata;
3381 delete event.hudchange.sdata;
3382 delete event.hudchange.v2s32data;
3383 } else if (event.type == CE_SET_SKY) {
3384 sky->setVisible(false);
3391 // Handle according to type
3392 if (*event.set_sky.type == "regular") {
3393 sky->setVisible(true);
3394 } else if (*event.set_sky.type == "skybox" &&
3395 event.set_sky.params->size() == 6) {
3396 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3397 skybox = smgr->addSkyBoxSceneNode(
3398 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3399 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3400 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3401 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3402 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3403 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3405 // Handle everything else as plain color
3407 if (*event.set_sky.type != "plain")
3408 infostream << "Unknown sky type: "
3409 << (*event.set_sky.type) << std::endl;
3411 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3414 delete event.set_sky.bgcolor;
3415 delete event.set_sky.type;
3416 delete event.set_sky.params;
3417 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3418 bool enable = event.override_day_night_ratio.do_override;
3419 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3420 client->getEnv().setDayNightRatioOverride(enable, value);
3426 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3427 f32 dtime, float time_from_last_punch)
3429 LocalPlayer *player = client->getEnv().getLocalPlayer();
3432 For interaction purposes, get info about the held item
3434 - Is it a usable item?
3435 - Can it point to liquids?
3437 ItemStack playeritem;
3439 InventoryList *mlist = local_inventory->getList("main");
3441 if (mlist && client->getPlayerItem() < mlist->getSize())
3442 playeritem = mlist->getItem(client->getPlayerItem());
3445 ToolCapabilities playeritem_toolcap =
3446 playeritem.getToolCapabilities(itemdef_manager);
3448 v3s16 old_camera_offset = camera->getOffset();
3450 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3451 GenericCAO *playercao = player->getCAO();
3453 // If playercao not loaded, don't change camera
3454 if (playercao == NULL)
3457 camera->toggleCameraMode();
3459 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3460 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3463 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3464 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3466 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3467 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3469 camera->step(dtime);
3471 v3f camera_position = camera->getPosition();
3472 v3f camera_direction = camera->getDirection();
3473 f32 camera_fov = camera->getFovMax();
3474 v3s16 camera_offset = camera->getOffset();
3476 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3478 if (!flags->disable_camera_update) {
3479 client->getEnv().getClientMap().updateCamera(camera_position,
3480 camera_direction, camera_fov, camera_offset);
3482 if (flags->camera_offset_changed) {
3483 client->updateCameraOffset(camera_offset);
3484 client->getEnv().updateCameraOffset(camera_offset);
3487 clouds->updateCameraOffset(camera_offset);
3493 void Game::updateSound(f32 dtime)
3495 // Update sound listener
3496 v3s16 camera_offset = camera->getOffset();
3497 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3498 v3f(0, 0, 0), // velocity
3499 camera->getDirection(),
3500 camera->getCameraNode()->getUpVector());
3501 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3504 // Update sound maker
3505 soundmaker->step(dtime);
3507 LocalPlayer *player = client->getEnv().getLocalPlayer();
3509 ClientMap &map = client->getEnv().getClientMap();
3510 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3511 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3515 void Game::processPlayerInteraction(GameRunData *runData,
3516 f32 dtime, bool show_hud, bool show_debug)
3518 LocalPlayer *player = client->getEnv().getLocalPlayer();
3520 ItemStack playeritem;
3522 InventoryList *mlist = local_inventory->getList("main");
3524 if (mlist && client->getPlayerItem() < mlist->getSize())
3525 playeritem = mlist->getItem(client->getPlayerItem());
3528 const ItemDefinition &playeritem_def =
3529 playeritem.getDefinition(itemdef_manager);
3531 v3f player_position = player->getPosition();
3532 v3f camera_position = camera->getPosition();
3533 v3f camera_direction = camera->getDirection();
3534 v3s16 camera_offset = camera->getOffset();
3538 Calculate what block is the crosshair pointing to
3541 f32 d = playeritem_def.range; // max. distance
3542 f32 d_hand = itemdef_manager->get("").range;
3544 if (d < 0 && d_hand >= 0)
3549 core::line3d<f32> shootline;
3551 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3553 shootline = core::line3d<f32>(camera_position,
3554 camera_position + camera_direction * BS * (d + 1));
3557 // prevent player pointing anything in front-view
3558 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3559 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3562 #ifdef HAVE_TOUCHSCREENGUI
3564 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3565 shootline = g_touchscreengui->getShootline();
3566 shootline.start += intToFloat(camera_offset, BS);
3567 shootline.end += intToFloat(camera_offset, BS);
3572 PointedThing pointed = getPointedThing(
3574 client, hud, player_position, camera_direction,
3575 camera_position, shootline, d,
3576 playeritem_def.liquids_pointable,
3577 !runData->ldown_for_dig,
3580 runData->selected_object);
3582 if (pointed != runData->pointed_old) {
3583 infostream << "Pointing at " << pointed.dump() << std::endl;
3584 hud->updateSelectionMesh(camera_offset);
3589 - releasing left mouse button
3590 - pointing away from node
3592 if (runData->digging) {
3593 if (input->getLeftReleased()) {
3594 infostream << "Left button released"
3595 << " (stopped digging)" << std::endl;
3596 runData->digging = false;
3597 } else if (pointed != runData->pointed_old) {
3598 if (pointed.type == POINTEDTHING_NODE
3599 && runData->pointed_old.type == POINTEDTHING_NODE
3600 && pointed.node_undersurface
3601 == runData->pointed_old.node_undersurface) {
3602 // Still pointing to the same node, but a different face.
3605 infostream << "Pointing away from node"
3606 << " (stopped digging)" << std::endl;
3607 runData->digging = false;
3608 hud->updateSelectionMesh(camera_offset);
3612 if (!runData->digging) {
3613 client->interact(1, runData->pointed_old);
3614 client->setCrack(-1, v3s16(0, 0, 0));
3615 runData->dig_time = 0.0;
3619 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3620 runData->ldown_for_dig = false;
3623 runData->left_punch = false;
3625 soundmaker->m_player_leftpunch_sound.name = "";
3627 if (input->getRightState())
3628 runData->repeat_rightclick_timer += dtime;
3630 runData->repeat_rightclick_timer = 0;
3632 if (playeritem_def.usable && input->getLeftState()) {
3633 if (input->getLeftClicked())
3634 client->interact(4, pointed);
3635 } else if (pointed.type == POINTEDTHING_NODE) {
3636 ToolCapabilities playeritem_toolcap =
3637 playeritem.getToolCapabilities(itemdef_manager);
3638 handlePointingAtNode(runData, pointed, playeritem_def,
3639 playeritem_toolcap, dtime);
3640 } else if (pointed.type == POINTEDTHING_OBJECT) {
3641 handlePointingAtObject(runData, pointed, playeritem,
3642 player_position, show_debug);
3643 } else if (input->getLeftState()) {
3644 // When button is held down in air, show continuous animation
3645 runData->left_punch = true;
3646 } else if (input->getRightClicked()) {
3647 handlePointingAtNothing(runData, playeritem);
3650 runData->pointed_old = pointed;
3652 if (runData->left_punch || input->getLeftClicked())
3653 camera->setDigging(0); // left click animation
3655 input->resetLeftClicked();
3656 input->resetRightClicked();
3658 input->resetLeftReleased();
3659 input->resetRightReleased();
3663 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3665 infostream << "Right Clicked in Air" << std::endl;
3666 PointedThing fauxPointed;
3667 fauxPointed.type = POINTEDTHING_NOTHING;
3668 client->interact(5, fauxPointed);
3672 void Game::handlePointingAtNode(GameRunData *runData,
3673 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3674 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3676 v3s16 nodepos = pointed.node_undersurface;
3677 v3s16 neighbourpos = pointed.node_abovesurface;
3680 Check information text of node
3683 ClientMap &map = client->getEnv().getClientMap();
3684 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3687 infotext = utf8_to_wide(meta->getString("infotext"));
3689 MapNode n = map.getNodeNoEx(nodepos);
3691 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3692 infotext = L"Unknown node: ";
3693 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3697 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3698 && client->checkPrivilege("interact")) {
3699 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3702 if ((input->getRightClicked() ||
3703 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3704 client->checkPrivilege("interact")) {
3705 runData->repeat_rightclick_timer = 0;
3706 infostream << "Ground right-clicked" << std::endl;
3708 if (meta && meta->getString("formspec") != "" && !random_input
3709 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3710 infostream << "Launching custom inventory view" << std::endl;
3712 InventoryLocation inventoryloc;
3713 inventoryloc.setNodeMeta(nodepos);
3715 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3716 &client->getEnv().getClientMap(), nodepos);
3717 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3719 create_formspec_menu(¤t_formspec, client, gamedef,
3720 texture_src, device, fs_src, txt_dst, client);
3722 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3724 // Report right click to server
3726 camera->setDigging(1); // right click animation (always shown for feedback)
3728 // If the wielded item has node placement prediction,
3730 bool placed = nodePlacementPrediction(*client,
3732 nodepos, neighbourpos);
3736 client->interact(3, pointed);
3738 soundmaker->m_player_rightpunch_sound =
3739 playeritem_def.sound_place;
3741 soundmaker->m_player_rightpunch_sound =
3744 if (playeritem_def.node_placement_prediction == "" ||
3745 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3746 client->interact(3, pointed); // Report to server
3748 soundmaker->m_player_rightpunch_sound =
3749 playeritem_def.sound_place_failed;
3757 void Game::handlePointingAtObject(GameRunData *runData,
3758 const PointedThing &pointed,
3759 const ItemStack &playeritem,
3760 const v3f &player_position,
3763 infotext = utf8_to_wide(runData->selected_object->infoText());
3766 if (infotext != L"") {
3769 infotext += utf8_to_wide(runData->selected_object->debugInfoText());
3772 if (input->getLeftState()) {
3773 bool do_punch = false;
3774 bool do_punch_damage = false;
3776 if (runData->object_hit_delay_timer <= 0.0) {
3778 do_punch_damage = true;
3779 runData->object_hit_delay_timer = object_hit_delay;
3782 if (input->getLeftClicked())
3786 infostream << "Left-clicked object" << std::endl;
3787 runData->left_punch = true;
3790 if (do_punch_damage) {
3791 // Report direct punch
3792 v3f objpos = runData->selected_object->getPosition();
3793 v3f dir = (objpos - player_position).normalize();
3795 bool disable_send = runData->selected_object->directReportPunch(
3796 dir, &playeritem, runData->time_from_last_punch);
3797 runData->time_from_last_punch = 0;
3800 client->interact(0, pointed);
3802 } else if (input->getRightClicked()) {
3803 infostream << "Right-clicked object" << std::endl;
3804 client->interact(3, pointed); // place
3809 void Game::handleDigging(GameRunData *runData,
3810 const PointedThing &pointed, const v3s16 &nodepos,
3811 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3813 if (!runData->digging) {
3814 infostream << "Started digging" << std::endl;
3815 client->interact(0, pointed);
3816 runData->digging = true;
3817 runData->ldown_for_dig = true;
3820 LocalPlayer *player = client->getEnv().getLocalPlayer();
3821 ClientMap &map = client->getEnv().getClientMap();
3822 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3824 // NOTE: Similar piece of code exists on the server side for
3826 // Get digging parameters
3827 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3828 &playeritem_toolcap);
3830 // If can't dig, try hand
3831 if (!params.diggable) {
3832 const ItemDefinition &hand = itemdef_manager->get("");
3833 const ToolCapabilities *tp = hand.tool_capabilities;
3836 params = getDigParams(nodedef_manager->get(n).groups, tp);
3839 if (params.diggable == false) {
3840 // I guess nobody will wait for this long
3841 runData->dig_time_complete = 10000000.0;
3843 runData->dig_time_complete = params.time;
3845 if (m_cache_enable_particles) {
3846 const ContentFeatures &features =
3847 client->getNodeDefManager()->get(n);
3848 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3849 player, nodepos, features.tiles);
3853 if (runData->dig_time_complete >= 0.001) {
3854 runData->dig_index = (float)crack_animation_length
3856 / runData->dig_time_complete;
3858 // This is for torches
3859 runData->dig_index = crack_animation_length;
3862 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3864 if (sound_dig.exists() && params.diggable) {
3865 if (sound_dig.name == "__group") {
3866 if (params.main_group != "") {
3867 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3868 soundmaker->m_player_leftpunch_sound.name =
3869 std::string("default_dig_") +
3873 soundmaker->m_player_leftpunch_sound = sound_dig;
3877 // Don't show cracks if not diggable
3878 if (runData->dig_time_complete >= 100000.0) {
3879 } else if (runData->dig_index < crack_animation_length) {
3880 //TimeTaker timer("client.setTempMod");
3881 //infostream<<"dig_index="<<dig_index<<std::endl;
3882 client->setCrack(runData->dig_index, nodepos);
3884 infostream << "Digging completed" << std::endl;
3885 client->interact(2, pointed);
3886 client->setCrack(-1, v3s16(0, 0, 0));
3887 bool is_valid_position;
3888 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3889 if (is_valid_position)
3890 client->removeNode(nodepos);
3892 if (m_cache_enable_particles) {
3893 const ContentFeatures &features =
3894 client->getNodeDefManager()->get(wasnode);
3895 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3896 player, nodepos, features.tiles);
3899 runData->dig_time = 0;
3900 runData->digging = false;
3902 runData->nodig_delay_timer =
3903 runData->dig_time_complete / (float)crack_animation_length;
3905 // We don't want a corresponding delay to
3906 // very time consuming nodes
3907 if (runData->nodig_delay_timer > 0.3)
3908 runData->nodig_delay_timer = 0.3;
3910 // We want a slight delay to very little
3911 // time consuming nodes
3912 const float mindelay = 0.15;
3914 if (runData->nodig_delay_timer < mindelay)
3915 runData->nodig_delay_timer = mindelay;
3917 // Send event to trigger sound
3918 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3919 gamedef->event()->put(e);
3922 if (runData->dig_time_complete < 100000.0) {
3923 runData->dig_time += dtime;
3925 runData->dig_time = 0;
3926 client->setCrack(-1, nodepos);
3929 camera->setDigging(0); // left click animation
3933 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
3934 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
3935 const CameraOrientation &cam)
3937 LocalPlayer *player = client->getEnv().getLocalPlayer();
3943 if (draw_control->range_all) {
3944 runData->fog_range = 100000 * BS;
3946 runData->fog_range = 0.9 * draw_control->wanted_range * BS;
3950 Calculate general brightness
3952 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3953 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3954 float direct_brightness;
3957 if (g_settings->getBool("free_move")) {
3958 direct_brightness = time_brightness;
3959 sunlight_seen = true;
3961 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3962 float old_brightness = sky->getBrightness();
3963 direct_brightness = client->getEnv().getClientMap()
3964 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3965 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3969 float time_of_day = runData->time_of_day;
3970 float time_of_day_smooth = runData->time_of_day_smooth;
3972 time_of_day = client->getEnv().getTimeOfDayF();
3974 const float maxsm = 0.05;
3975 const float todsm = 0.05;
3977 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3978 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3979 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3980 time_of_day_smooth = time_of_day;
3982 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3983 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3984 + (time_of_day + 1.0) * todsm;
3986 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3987 + time_of_day * todsm;
3989 runData->time_of_day = time_of_day;
3990 runData->time_of_day_smooth = time_of_day_smooth;
3992 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3993 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3994 player->getPitch());
4000 v3f player_position = player->getPosition();
4001 if (sky->getCloudsVisible()) {
4002 clouds->setVisible(true);
4003 clouds->step(dtime);
4004 clouds->update(v2f(player_position.X, player_position.Z),
4005 sky->getCloudColor());
4007 clouds->setVisible(false);
4014 client->getParticleManager()->step(dtime);
4020 if (m_cache_enable_fog && !flags.force_fog_off) {
4023 video::EFT_FOG_LINEAR,
4024 runData->fog_range * 0.4,
4025 runData->fog_range * 1.0,
4033 video::EFT_FOG_LINEAR,
4043 Get chat messages from client
4046 v2u32 screensize = driver->getScreenSize();
4048 updateChat(*client, dtime, flags.show_debug, screensize,
4049 flags.show_chat, runData->profiler_current_page,
4050 *chat_backend, guitext_chat);
4056 if (client->getPlayerItem() != runData->new_playeritem)
4057 client->selectPlayerItem(runData->new_playeritem);
4059 // Update local inventory if it has changed
4060 if (client->getLocalInventoryUpdated()) {
4061 //infostream<<"Updating local inventory"<<std::endl;
4062 client->getLocalInventory(*local_inventory);
4063 runData->update_wielded_item_trigger = true;
4066 if (runData->update_wielded_item_trigger) {
4067 // Update wielded tool
4068 InventoryList *mlist = local_inventory->getList("main");
4070 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4071 ItemStack item = mlist->getItem(client->getPlayerItem());
4072 camera->wield(item);
4074 runData->update_wielded_item_trigger = false;
4078 Update block draw list every 200ms or when camera direction has
4081 runData->update_draw_list_timer += dtime;
4083 v3f camera_direction = camera->getDirection();
4084 if (runData->update_draw_list_timer >= 0.2
4085 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4086 || flags.camera_offset_changed) {
4087 runData->update_draw_list_timer = 0;
4088 client->getEnv().getClientMap().updateDrawList(driver);
4089 runData->update_draw_list_last_cam_dir = camera_direction;
4092 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4095 make sure menu is on top
4096 1. Delete formspec menu reference if menu was removed
4097 2. Else, make sure formspec menu is on top
4099 if (current_formspec) {
4100 if (current_formspec->getReferenceCount() == 1) {
4101 current_formspec->drop();
4102 current_formspec = NULL;
4103 } else if (!noMenuActive()) {
4104 guiroot->bringToFront(current_formspec);
4112 video::SColor skycolor = sky->getSkyColor();
4114 TimeTaker tt_draw("mainloop: draw");
4116 TimeTaker timer("beginScene");
4117 driver->beginScene(true, true, skycolor);
4118 stats->beginscenetime = timer.stop(true);
4121 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4122 guienv, screensize, skycolor, flags.show_hud,
4123 flags.show_minimap);
4128 if (flags.show_profiler_graph)
4129 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4134 if (runData->damage_flash > 0.0) {
4135 video::SColor color(std::min(runData->damage_flash, 180.0f),
4139 driver->draw2DRectangle(color,
4140 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4143 runData->damage_flash -= 100.0 * dtime;
4149 if (player->hurt_tilt_timer > 0.0) {
4150 player->hurt_tilt_timer -= dtime * 5;
4152 if (player->hurt_tilt_timer < 0)
4153 player->hurt_tilt_strength = 0;
4157 Update minimap pos and rotation
4159 if (flags.show_minimap && flags.show_hud) {
4160 mapper->setPos(floatToInt(player->getPosition(), BS));
4161 mapper->setAngle(player->getYaw());
4168 TimeTaker timer("endScene");
4170 stats->endscenetime = timer.stop(true);
4173 stats->drawtime = tt_draw.stop(true);
4174 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4178 inline static const char *yawToDirectionString(int yaw)
4180 // NOTE: TODO: This can be done mathematically without the else/else-if
4183 const char *player_direction;
4185 yaw = wrapDegrees_0_360(yaw);
4187 if (yaw >= 45 && yaw < 135)
4188 player_direction = "West [-X]";
4189 else if (yaw >= 135 && yaw < 225)
4190 player_direction = "South [-Z]";
4191 else if (yaw >= 225 && yaw < 315)
4192 player_direction = "East [+X]";
4194 player_direction = "North [+Z]";
4196 return player_direction;
4200 void Game::updateGui(float *statustext_time, const RunStats &stats,
4201 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4202 const CameraOrientation &cam)
4204 v2u32 screensize = driver->getScreenSize();
4205 LocalPlayer *player = client->getEnv().getLocalPlayer();
4206 v3f player_position = player->getPosition();
4208 if (flags.show_debug) {
4209 static float drawtime_avg = 0;
4210 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4212 u16 fps = 1.0 / stats.dtime_jitter.avg;
4213 //s32 fps = driver->getFPS();
4215 std::ostringstream os(std::ios_base::binary);
4217 << PROJECT_NAME_C " " << g_version_hash
4219 << " (R: range_all=" << draw_control->range_all << ")"
4220 << std::setprecision(0)
4221 << " drawtime = " << drawtime_avg
4222 << std::setprecision(1)
4223 << ", dtime_jitter = "
4224 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4225 << std::setprecision(1)
4226 << ", v_range = " << draw_control->wanted_range
4227 << std::setprecision(3)
4228 << ", RTT = " << client->getRTT();
4229 guitext->setText(utf8_to_wide(os.str()).c_str());
4230 guitext->setVisible(true);
4231 } else if (flags.show_hud || flags.show_chat) {
4232 std::ostringstream os(std::ios_base::binary);
4233 os << PROJECT_NAME_C " " << g_version_hash;
4234 guitext->setText(utf8_to_wide(os.str()).c_str());
4235 guitext->setVisible(true);
4237 guitext->setVisible(false);
4240 if (guitext->isVisible()) {
4241 core::rect<s32> rect(
4243 screensize.X, 5 + g_fontengine->getTextHeight()
4245 guitext->setRelativePosition(rect);
4248 if (flags.show_debug) {
4249 std::ostringstream os(std::ios_base::binary);
4250 os << std::setprecision(1) << std::fixed
4251 << "(" << (player_position.X / BS)
4252 << ", " << (player_position.Y / BS)
4253 << ", " << (player_position.Z / BS)
4254 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4255 << " " << yawToDirectionString(cam.camera_yaw)
4256 << ") (seed = " << ((u64)client->getMapSeed())
4259 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4260 ClientMap &map = client->getEnv().getClientMap();
4261 const INodeDefManager *nodedef = client->getNodeDefManager();
4262 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4263 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4264 const ContentFeatures &features = nodedef->get(n);
4265 os << " (pointing_at = " << nodedef->get(n).name
4266 << " - " << features.tiledef[0].name.c_str()
4271 guitext2->setText(utf8_to_wide(os.str()).c_str());
4272 guitext2->setVisible(true);
4274 core::rect<s32> rect(
4275 5, 5 + g_fontengine->getTextHeight(),
4276 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4278 guitext2->setRelativePosition(rect);
4280 guitext2->setVisible(false);
4283 guitext_info->setText(infotext.c_str());
4284 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4286 float statustext_time_max = 1.5;
4288 if (!statustext.empty()) {
4289 *statustext_time += dtime;
4291 if (*statustext_time >= statustext_time_max) {
4293 *statustext_time = 0;
4297 guitext_status->setText(statustext.c_str());
4298 guitext_status->setVisible(!statustext.empty());
4300 if (!statustext.empty()) {
4301 s32 status_width = guitext_status->getTextWidth();
4302 s32 status_height = guitext_status->getTextHeight();
4303 s32 status_y = screensize.Y - 150;
4304 s32 status_x = (screensize.X - status_width) / 2;
4305 core::rect<s32> rect(
4306 status_x , status_y - status_height,
4307 status_x + status_width, status_y
4309 guitext_status->setRelativePosition(rect);
4312 video::SColor initial_color(255, 0, 0, 0);
4314 if (guienv->getSkin())
4315 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4317 video::SColor final_color = initial_color;
4318 final_color.setAlpha(0);
4319 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4320 initial_color, final_color,
4321 pow(*statustext_time / statustext_time_max, 2.0f));
4322 guitext_status->setOverrideColor(fade_color);
4323 guitext_status->enableOverrideColor(true);
4328 /* Log times and stuff for visualization */
4329 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4331 Profiler::GraphValues values;
4332 g_profiler->graphGet(values);
4338 /****************************************************************************
4340 ****************************************************************************/
4342 /* On some computers framerate doesn't seem to be automatically limited
4344 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4346 // not using getRealTime is necessary for wine
4347 device->getTimer()->tick(); // Maker sure device time is up-to-date
4348 u32 time = device->getTimer()->getTime();
4349 u32 last_time = fps_timings->last_time;
4351 if (time > last_time) // Make sure time hasn't overflowed
4352 fps_timings->busy_time = time - last_time;
4354 fps_timings->busy_time = 0;
4356 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4357 ? g_settings->getFloat("pause_fps_max")
4358 : g_settings->getFloat("fps_max"));
4360 if (fps_timings->busy_time < frametime_min) {
4361 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4362 device->sleep(fps_timings->sleep_time);
4364 fps_timings->sleep_time = 0;
4367 /* Get the new value of the device timer. Note that device->sleep() may
4368 * not sleep for the entire requested time as sleep may be interrupted and
4369 * therefore it is arguably more accurate to get the new time from the
4370 * device rather than calculating it by adding sleep_time to time.
4373 device->getTimer()->tick(); // Update device timer
4374 time = device->getTimer()->getTime();
4376 if (time > last_time) // Make sure last_time hasn't overflowed
4377 *dtime = (time - last_time) / 1000.0;
4381 fps_timings->last_time = time;
4384 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4385 // pass a copy of it to this function
4386 // Note: \p msg must be allocated using new (not malloc())
4387 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4388 int percent, bool draw_clouds)
4390 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4394 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4396 ((Game *)data)->readSettings();
4399 void Game::readSettings()
4401 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4402 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4403 m_cache_enable_particles = g_settings->getBool("enable_particles");
4404 m_cache_enable_fog = g_settings->getBool("enable_fog");
4405 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4406 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4408 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4411 /****************************************************************************/
4412 /****************************************************************************
4414 ****************************************************************************/
4415 /****************************************************************************/
4417 void Game::extendedResourceCleanup()
4419 // Extended resource accounting
4420 infostream << "Irrlicht resources after cleanup:" << std::endl;
4421 infostream << "\tRemaining meshes : "
4422 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4423 infostream << "\tRemaining textures : "
4424 << driver->getTextureCount() << std::endl;
4426 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4427 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4428 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4432 clearTextureNameCache();
4433 infostream << "\tRemaining materials: "
4434 << driver-> getMaterialRendererCount()
4435 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4439 /****************************************************************************/
4440 /****************************************************************************
4441 extern function for launching the game
4442 ****************************************************************************/
4443 /****************************************************************************/
4445 void the_game(bool *kill,
4447 InputHandler *input,
4448 IrrlichtDevice *device,
4450 const std::string &map_dir,
4451 const std::string &playername,
4452 const std::string &password,
4453 const std::string &address, // If empty local server is created
4456 std::string &error_message,
4457 ChatBackend &chat_backend,
4458 bool *reconnect_requested,
4459 const SubgameSpec &gamespec, // Used for local game
4460 bool simple_singleplayer_mode)
4464 /* Make a copy of the server address because if a local singleplayer server
4465 * is created then this is updated and we don't want to change the value
4466 * passed to us by the calling function
4468 std::string server_address = address;
4472 if (game.startup(kill, random_input, input, device, map_dir,
4473 playername, password, &server_address, port, error_message,
4474 reconnect_requested, &chat_backend, gamespec,
4475 simple_singleplayer_mode)) {
4480 } catch (SerializationError &e) {
4481 error_message = std::string("A serialization error occurred:\n")
4482 + e.what() + "\n\nThe server is probably "
4483 " running a different version of " PROJECT_NAME_C ".";
4484 errorstream << error_message << std::endl;
4485 } catch (ServerError &e) {
4486 error_message = e.what();
4487 errorstream << "ServerError: " << error_message << std::endl;
4488 } catch (ModError &e) {
4489 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4490 errorstream << "ModError: " << error_message << std::endl;