3 Copyright (C) 2010-2011 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.
21 #include "irrlichttypes_extrabloated.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
27 #include <IMaterialRendererServices.h>
30 #include "guiPauseMenu.h"
31 #include "guiPasswordChange.h"
32 #include "guiFormSpecMenu.h"
33 #include "guiTextInputMenu.h"
34 #include "guiDeathScreen.h"
36 #include "guiChatConsole.h"
44 #include "mainmenumanager.h"
48 // Needed for determining pointing to nodes
50 #include "nodemetadata.h"
51 #include "main.h" // For g_settings
53 #include "tile.h" // For TextureSource
54 #include "shader.h" // For ShaderSource
55 #include "logoutputbuffer.h"
57 #include "quicktune_shortcutter.h"
58 #include "clientmap.h"
62 #include "sound_openal.h"
64 #include "event_manager.h"
66 #include "util/directiontables.h"
72 struct TextDestChat : public TextDest
74 TextDestChat(Client *client)
78 void gotText(std::wstring text)
80 m_client->typeChatMessage(text);
82 void gotText(std::map<std::string, std::string> fields)
84 m_client->typeChatMessage(narrow_to_wide(fields["text"]));
90 struct TextDestNodeMetadata : public TextDest
92 TextDestNodeMetadata(v3s16 p, Client *client)
97 // This is deprecated I guess? -celeron55
98 void gotText(std::wstring text)
100 std::string ntext = wide_to_narrow(text);
101 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
102 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
103 std::map<std::string, std::string> fields;
104 fields["text"] = ntext;
105 m_client->sendNodemetaFields(m_p, "", fields);
107 void gotText(std::map<std::string, std::string> fields)
109 m_client->sendNodemetaFields(m_p, "", fields);
116 struct TextDestPlayerInventory : public TextDest
118 TextDestPlayerInventory(Client *client)
122 void gotText(std::map<std::string, std::string> fields)
124 m_client->sendInventoryFields("", fields);
130 /* Respawn menu callback */
132 class MainRespawnInitiator: public IRespawnInitiator
135 MainRespawnInitiator(bool *active, Client *client):
136 m_active(active), m_client(client)
143 m_client->sendRespawn();
150 /* Form update callback */
152 class NodeMetadataFormSource: public IFormSource
155 NodeMetadataFormSource(ClientMap *map, v3s16 p):
160 std::string getForm()
162 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
165 return meta->getString("formspec");
167 std::string resolveText(std::string str)
169 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
172 return meta->resolveString(str);
179 class PlayerInventoryFormSource: public IFormSource
182 PlayerInventoryFormSource(Client *client):
186 std::string getForm()
188 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
189 return player->inventory_formspec;
195 class FormspecFormSource: public IFormSource
198 FormspecFormSource(std::string formspec,FormspecFormSource** game_formspec)
200 m_formspec = formspec;
201 m_game_formspec = game_formspec;
204 ~FormspecFormSource()
206 *m_game_formspec = 0;
209 void setForm(std::string formspec) {
210 m_formspec = formspec;
213 std::string getForm()
218 std::string m_formspec;
219 FormspecFormSource** m_game_formspec;
224 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
226 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
227 Inventory *inventory, s32 halfheartcount, u16 playeritem)
229 InventoryList *mainlist = inventory->getList("main");
232 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
236 s32 padding = imgsize/12;
237 //s32 height = imgsize + padding*2;
238 s32 width = itemcount*(imgsize+padding*2);
240 // Position of upper left corner of bar
241 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
243 // Draw background color
244 /*core::rect<s32> barrect(0,0,width,height);
246 video::SColor bgcolor(255,128,128,128);
247 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
249 core::rect<s32> imgrect(0,0,imgsize,imgsize);
251 for(s32 i=0; i<itemcount; i++)
253 const ItemStack &item = mainlist->getItem(i);
255 core::rect<s32> rect = imgrect + pos
256 + v2s32(padding+i*(imgsize+padding*2), padding);
260 video::SColor c_outside(255,255,0,0);
261 //video::SColor c_outside(255,0,0,0);
262 //video::SColor c_inside(255,192,192,192);
263 s32 x1 = rect.UpperLeftCorner.X;
264 s32 y1 = rect.UpperLeftCorner.Y;
265 s32 x2 = rect.LowerRightCorner.X;
266 s32 y2 = rect.LowerRightCorner.Y;
267 // Black base borders
268 driver->draw2DRectangle(c_outside,
270 v2s32(x1 - padding, y1 - padding),
271 v2s32(x2 + padding, y1)
273 driver->draw2DRectangle(c_outside,
275 v2s32(x1 - padding, y2),
276 v2s32(x2 + padding, y2 + padding)
278 driver->draw2DRectangle(c_outside,
280 v2s32(x1 - padding, y1),
283 driver->draw2DRectangle(c_outside,
286 v2s32(x2 + padding, y2)
288 /*// Light inside borders
289 driver->draw2DRectangle(c_inside,
291 v2s32(x1 - padding/2, y1 - padding/2),
292 v2s32(x2 + padding/2, y1)
294 driver->draw2DRectangle(c_inside,
296 v2s32(x1 - padding/2, y2),
297 v2s32(x2 + padding/2, y2 + padding/2)
299 driver->draw2DRectangle(c_inside,
301 v2s32(x1 - padding/2, y1),
304 driver->draw2DRectangle(c_inside,
307 v2s32(x2 + padding/2, y2)
312 video::SColor bgcolor2(128,0,0,0);
313 driver->draw2DRectangle(bgcolor2, rect, NULL);
314 drawItemStack(driver, font, item, rect, NULL, gamedef);
320 video::ITexture *heart_texture =
321 gamedef->getTextureSource()->getTextureRaw("heart.png");
324 v2s32 p = pos + v2s32(0, -20);
325 for(s32 i=0; i<halfheartcount/2; i++)
327 const video::SColor color(255,255,255,255);
328 const video::SColor colors[] = {color,color,color,color};
329 core::rect<s32> rect(0,0,16,16);
331 driver->draw2DImage(heart_texture, rect,
332 core::rect<s32>(core::position2d<s32>(0,0),
333 core::dimension2di(heart_texture->getOriginalSize())),
337 if(halfheartcount % 2 == 1)
339 const video::SColor color(255,255,255,255);
340 const video::SColor colors[] = {color,color,color,color};
341 core::rect<s32> rect(0,0,16/2,16);
343 core::dimension2di srcd(heart_texture->getOriginalSize());
345 driver->draw2DImage(heart_texture, rect,
346 core::rect<s32>(core::position2d<s32>(0,0), srcd),
354 Check if a node is pointable
356 inline bool isPointableNode(const MapNode& n,
357 Client *client, bool liquids_pointable)
359 const ContentFeatures &features = client->getNodeDefManager()->get(n);
360 return features.pointable ||
361 (liquids_pointable && features.isLiquid());
365 Find what the player is pointing at
367 PointedThing getPointedThing(Client *client, v3f player_position,
368 v3f camera_direction, v3f camera_position,
369 core::line3d<f32> shootline, f32 d,
370 bool liquids_pointable,
371 bool look_for_object,
372 std::vector<aabb3f> &hilightboxes,
373 ClientActiveObject *&selected_object)
377 hilightboxes.clear();
378 selected_object = NULL;
380 INodeDefManager *nodedef = client->getNodeDefManager();
381 ClientMap &map = client->getEnv().getClientMap();
383 // First try to find a pointed at active object
386 selected_object = client->getSelectedActiveObject(d*BS,
387 camera_position, shootline);
389 if(selected_object != NULL)
391 if(selected_object->doShowSelectionBox())
393 aabb3f *selection_box = selected_object->getSelectionBox();
394 // Box should exist because object was
395 // returned in the first place
396 assert(selection_box);
398 v3f pos = selected_object->getPosition();
399 hilightboxes.push_back(aabb3f(
400 selection_box->MinEdge + pos,
401 selection_box->MaxEdge + pos));
405 result.type = POINTEDTHING_OBJECT;
406 result.object_id = selected_object->getId();
411 // That didn't work, try to find a pointed at node
413 f32 mindistance = BS * 1001;
415 v3s16 pos_i = floatToInt(player_position, BS);
417 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
421 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
422 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
423 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
424 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
425 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
426 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
428 // Prevent signed number overflow
436 for(s16 y = ystart; y <= yend; y++)
437 for(s16 z = zstart; z <= zend; z++)
438 for(s16 x = xstart; x <= xend; x++)
443 n = map.getNode(v3s16(x,y,z));
445 catch(InvalidPositionException &e)
449 if(!isPointableNode(n, client, liquids_pointable))
452 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
455 v3f npf = intToFloat(np, BS);
457 for(std::vector<aabb3f>::const_iterator
459 i != boxes.end(); i++)
465 for(u16 j=0; j<6; j++)
467 v3s16 facedir = g_6dirs[j];
468 aabb3f facebox = box;
472 facebox.MinEdge.X = facebox.MaxEdge.X-d;
473 else if(facedir.X < 0)
474 facebox.MaxEdge.X = facebox.MinEdge.X+d;
475 else if(facedir.Y > 0)
476 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
477 else if(facedir.Y < 0)
478 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
479 else if(facedir.Z > 0)
480 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
481 else if(facedir.Z < 0)
482 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
484 v3f centerpoint = facebox.getCenter();
485 f32 distance = (centerpoint - camera_position).getLength();
486 if(distance >= mindistance)
488 if(!facebox.intersectsWithLine(shootline))
491 v3s16 np_above = np + facedir;
493 result.type = POINTEDTHING_NODE;
494 result.node_undersurface = np;
495 result.node_abovesurface = np_above;
496 mindistance = distance;
498 hilightboxes.clear();
499 for(std::vector<aabb3f>::const_iterator
501 i2 != boxes.end(); i2++)
504 box.MinEdge += npf + v3f(-d,-d,-d);
505 box.MaxEdge += npf + v3f(d,d,d);
506 hilightboxes.push_back(box);
516 Draws a screen with a single text on it.
517 Text will be removed when the screen is drawn the next time.
519 /*gui::IGUIStaticText **/
520 void draw_load_screen(const std::wstring &text,
521 video::IVideoDriver* driver, gui::IGUIFont* font)
523 v2u32 screensize = driver->getScreenSize();
524 const wchar_t *loadingtext = text.c_str();
525 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
526 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
527 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
528 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
530 gui::IGUIStaticText *guitext = guienv->addStaticText(
531 loadingtext, textrect, false, false);
532 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
534 driver->beginScene(true, true, video::SColor(255,0,0,0));
543 /* Profiler display */
545 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
546 gui::IGUIFont *font, u32 text_height,
547 u32 show_profiler, u32 show_profiler_max)
549 if(show_profiler == 0)
551 guitext_profiler->setVisible(false);
556 std::ostringstream os(std::ios_base::binary);
557 g_profiler->printPage(os, show_profiler, show_profiler_max);
558 std::wstring text = narrow_to_wide(os.str());
559 guitext_profiler->setText(text.c_str());
560 guitext_profiler->setVisible(true);
562 s32 w = font->getDimension(text.c_str()).Width;
565 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
566 8+(text_height+5)*2 +
567 font->getDimension(text.c_str()).Height);
568 guitext_profiler->setRelativePosition(rect);
569 guitext_profiler->setVisible(true);
577 Profiler::GraphValues values;
583 Meta(float initial=0, video::SColor color=
584 video::SColor(255,255,255,255)):
590 std::list<Piece> m_log;
598 void put(const Profiler::GraphValues &values)
601 piece.values = values;
602 m_log.push_back(piece);
603 while(m_log.size() > m_log_max_size)
604 m_log.erase(m_log.begin());
607 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
608 gui::IGUIFont* font) const
610 std::map<std::string, Meta> m_meta;
611 for(std::list<Piece>::const_iterator k = m_log.begin();
612 k != m_log.end(); k++)
614 const Piece &piece = *k;
615 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
616 i != piece.values.end(); i++){
617 const std::string &id = i->first;
618 const float &value = i->second;
619 std::map<std::string, Meta>::iterator j =
621 if(j == m_meta.end()){
622 m_meta[id] = Meta(value);
625 if(value < j->second.min)
626 j->second.min = value;
627 if(value > j->second.max)
628 j->second.max = value;
633 static const video::SColor usable_colors[] = {
634 video::SColor(255,255,100,100),
635 video::SColor(255,90,225,90),
636 video::SColor(255,100,100,255),
637 video::SColor(255,255,150,50),
638 video::SColor(255,220,220,100)
640 static const u32 usable_colors_count =
641 sizeof(usable_colors) / sizeof(*usable_colors);
642 u32 next_color_i = 0;
643 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
644 i != m_meta.end(); i++){
645 Meta &meta = i->second;
646 video::SColor color(255,200,200,200);
647 if(next_color_i < usable_colors_count)
648 color = usable_colors[next_color_i++];
653 s32 textx = x_left + m_log_max_size + 15;
654 s32 textx2 = textx + 200 - 15;
658 u32 num_graphs = m_meta.size();
659 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
661 video::SColor bgcolor(120,0,0,0);
662 driver->draw2DRectangle(bgcolor, rect, NULL);
666 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
667 i != m_meta.end(); i++){
668 const std::string &id = i->first;
669 const Meta &meta = i->second;
671 s32 y = y_bottom - meta_i * 50;
672 float show_min = meta.min;
673 float show_max = meta.max;
674 if(show_min >= -0.0001 && show_max >= -0.0001){
675 if(show_min <= show_max * 0.5)
680 snprintf(buf, 10, "%.3g", show_max);
681 font->draw(narrow_to_wide(buf).c_str(),
682 core::rect<s32>(textx, y - graphh,
683 textx2, y - graphh + texth),
685 snprintf(buf, 10, "%.3g", show_min);
686 font->draw(narrow_to_wide(buf).c_str(),
687 core::rect<s32>(textx, y - texth,
690 font->draw(narrow_to_wide(id).c_str(),
691 core::rect<s32>(textx, y - graphh/2 - texth/2,
692 textx2, y - graphh/2 + texth/2),
695 s32 graph1h = graphh;
696 bool relativegraph = (show_min != 0 && show_min != show_max);
697 float lastscaledvalue = 0.0;
698 bool lastscaledvalue_exists = false;
699 for(std::list<Piece>::const_iterator j = m_log.begin();
700 j != m_log.end(); j++)
702 const Piece &piece = *j;
704 bool value_exists = false;
705 Profiler::GraphValues::const_iterator k =
706 piece.values.find(id);
707 if(k != piece.values.end()){
713 lastscaledvalue_exists = false;
716 float scaledvalue = 1.0;
717 if(show_max != show_min)
718 scaledvalue = (value - show_min) / (show_max - show_min);
719 if(scaledvalue == 1.0 && value == 0){
721 lastscaledvalue_exists = false;
725 if(lastscaledvalue_exists){
726 s32 ivalue1 = lastscaledvalue * graph1h;
727 s32 ivalue2 = scaledvalue * graph1h;
728 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
729 v2s32(x, graph1y - ivalue2), meta.color);
731 lastscaledvalue = scaledvalue;
732 lastscaledvalue_exists = true;
734 s32 ivalue = scaledvalue * graph1h;
735 driver->draw2DLine(v2s32(x, graph1y),
736 v2s32(x, graph1y - ivalue), meta.color);
745 class NodeDugEvent: public MtEvent
751 NodeDugEvent(v3s16 p, MapNode n):
755 const char* getType() const
761 ISoundManager *m_sound;
762 INodeDefManager *m_ndef;
764 float m_player_step_timer;
766 SimpleSoundSpec m_player_step_sound;
767 SimpleSoundSpec m_player_leftpunch_sound;
768 SimpleSoundSpec m_player_rightpunch_sound;
770 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
773 m_player_step_timer(0)
777 void playPlayerStep()
779 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
780 m_player_step_timer = 0.03;
781 m_sound->playSound(m_player_step_sound, false);
785 static void viewBobbingStep(MtEvent *e, void *data)
787 SoundMaker *sm = (SoundMaker*)data;
788 sm->playPlayerStep();
791 static void playerRegainGround(MtEvent *e, void *data)
793 SoundMaker *sm = (SoundMaker*)data;
794 sm->playPlayerStep();
797 static void playerJump(MtEvent *e, void *data)
799 //SoundMaker *sm = (SoundMaker*)data;
802 static void cameraPunchLeft(MtEvent *e, void *data)
804 SoundMaker *sm = (SoundMaker*)data;
805 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
808 static void cameraPunchRight(MtEvent *e, void *data)
810 SoundMaker *sm = (SoundMaker*)data;
811 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
814 static void nodeDug(MtEvent *e, void *data)
816 SoundMaker *sm = (SoundMaker*)data;
817 NodeDugEvent *nde = (NodeDugEvent*)e;
818 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
821 void registerReceiver(MtEventManager *mgr)
823 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
824 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
825 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
826 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
827 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
828 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
831 void step(float dtime)
833 m_player_step_timer -= dtime;
837 // Locally stored sounds don't need to be preloaded because of this
838 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
840 std::set<std::string> m_fetched;
843 void fetchSounds(const std::string &name,
844 std::set<std::string> &dst_paths,
845 std::set<std::string> &dst_datas)
847 if(m_fetched.count(name))
849 m_fetched.insert(name);
850 std::string base = porting::path_share + DIR_DELIM + "testsounds";
851 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
852 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
853 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
854 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
855 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
856 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
857 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
858 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
859 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
860 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
861 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
865 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
868 bool *m_force_fog_off;
873 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
874 f32 *fog_range, Client *client):
876 m_force_fog_off(force_fog_off),
877 m_fog_range(fog_range),
880 ~GameGlobalShaderConstantSetter() {}
882 virtual void onSetConstants(video::IMaterialRendererServices *services,
889 video::SColor bgcolor = m_sky->getBgColor();
890 video::SColorf bgcolorf(bgcolor);
891 float bgcolorfa[4] = {
897 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
900 float fog_distance = *m_fog_range;
902 fog_distance = 10000*BS;
903 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
906 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
907 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
908 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
916 IrrlichtDevice *device,
919 std::string playername,
920 std::string password,
921 std::string address, // If "", local server is used
923 std::wstring &error_message,
924 std::string configpath,
925 ChatBackend &chat_backend,
926 const SubgameSpec &gamespec, // Used for local game,
927 bool simple_singleplayer_mode
930 FormspecFormSource* current_formspec = 0;
931 video::IVideoDriver* driver = device->getVideoDriver();
932 scene::ISceneManager* smgr = device->getSceneManager();
934 // Calculate text height using the font
935 u32 text_height = font->getDimension(L"Random test string").Height;
937 v2u32 screensize(0,0);
938 v2u32 last_screensize(0,0);
939 screensize = driver->getScreenSize();
941 const s32 hotbar_itemcount = 8;
942 //const s32 hotbar_imagesize = 36;
943 //const s32 hotbar_imagesize = 64;
944 s32 hotbar_imagesize = 48;
947 Draw "Loading" screen
950 draw_load_screen(L"Loading...", driver, font);
952 // Create texture source
953 IWritableTextureSource *tsrc = createTextureSource(device);
955 // Create shader source
956 IWritableShaderSource *shsrc = createShaderSource(device);
958 // These will be filled by data received from the server
959 // Create item definition manager
960 IWritableItemDefManager *itemdef = createItemDefManager();
961 // Create node definition manager
962 IWritableNodeDefManager *nodedef = createNodeDefManager();
964 // Sound fetcher (useful when testing)
965 GameOnDemandSoundFetcher soundfetcher;
968 ISoundManager *sound = NULL;
969 bool sound_is_dummy = false;
971 if(g_settings->getBool("enable_sound")){
972 infostream<<"Attempting to use OpenAL audio"<<std::endl;
973 sound = createOpenALSoundManager(&soundfetcher);
975 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
977 infostream<<"Sound disabled."<<std::endl;
981 infostream<<"Using dummy audio."<<std::endl;
982 sound = &dummySoundManager;
983 sound_is_dummy = true;
987 EventManager eventmgr;
990 SoundMaker soundmaker(sound, nodedef);
991 soundmaker.registerReceiver(&eventmgr);
993 // Add chat log output for errors to be shown in chat
994 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
996 // Create UI for modifying quicktune values
997 QuicktuneShortcutter quicktune;
1001 SharedPtr will delete it when it goes out of scope.
1003 SharedPtr<Server> server;
1005 draw_load_screen(L"Creating server...", driver, font);
1006 infostream<<"Creating server"<<std::endl;
1007 server = new Server(map_dir, configpath, gamespec,
1008 simple_singleplayer_mode);
1009 server->start(port);
1013 do{ // Client scope (breakable do-while(0))
1019 draw_load_screen(L"Creating client...", driver, font);
1020 infostream<<"Creating client"<<std::endl;
1022 MapDrawControl draw_control;
1024 Client client(device, playername.c_str(), password, draw_control,
1025 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr);
1027 // Client acts as our GameDef
1028 IGameDef *gamedef = &client;
1030 draw_load_screen(L"Resolving address...", driver, font);
1031 Address connect_address(0,0,0,0, port);
1034 //connect_address.Resolve("localhost");
1035 connect_address.setAddress(127,0,0,1);
1037 connect_address.Resolve(address.c_str());
1039 catch(ResolveError &e)
1041 error_message = L"Couldn't resolve address";
1042 errorstream<<wide_to_narrow(error_message)<<std::endl;
1043 // Break out of client scope
1048 Attempt to connect to the server
1051 infostream<<"Connecting to server at ";
1052 connect_address.print(&infostream);
1053 infostream<<std::endl;
1054 client.connect(connect_address);
1057 Wait for server to accept connection
1059 bool could_connect = false;
1060 bool connect_aborted = false;
1062 float frametime = 0.033;
1063 float time_counter = 0.0;
1065 while(device->run())
1067 // Update client and server
1068 client.step(frametime);
1070 server->step(frametime);
1073 if(client.connectedAndInitialized()){
1074 could_connect = true;
1078 if(client.accessDenied()){
1079 error_message = L"Access denied. Reason: "
1080 +client.accessDeniedReason();
1081 errorstream<<wide_to_narrow(error_message)<<std::endl;
1084 if(input->wasKeyDown(EscapeKey)){
1085 connect_aborted = true;
1086 infostream<<"Connect aborted [Escape]"<<std::endl;
1091 std::wostringstream ss;
1092 ss<<L"Connecting to server... (press Escape to cancel)\n";
1093 std::wstring animation = L"/-\\|";
1094 ss<<animation[(int)(time_counter/0.2)%4];
1095 draw_load_screen(ss.str(), driver, font);
1098 sleep_ms(1000*frametime);
1099 time_counter += frametime;
1102 catch(con::PeerNotFoundException &e)
1106 Handle failure to connect
1109 if(error_message == L"" && !connect_aborted){
1110 error_message = L"Connection failed";
1111 errorstream<<wide_to_narrow(error_message)<<std::endl;
1113 // Break out of client scope
1118 Wait until content has been received
1120 bool got_content = false;
1121 bool content_aborted = false;
1123 float frametime = 0.033;
1124 float time_counter = 0.0;
1126 while(device->run())
1128 // Update client and server
1129 client.step(frametime);
1131 server->step(frametime);
1134 if(client.texturesReceived() &&
1135 client.itemdefReceived() &&
1136 client.nodedefReceived()){
1141 if(!client.connectedAndInitialized()){
1142 error_message = L"Client disconnected";
1143 errorstream<<wide_to_narrow(error_message)<<std::endl;
1146 if(input->wasKeyDown(EscapeKey)){
1147 content_aborted = true;
1148 infostream<<"Connect aborted [Escape]"<<std::endl;
1153 std::wostringstream ss;
1154 ss<<L"Waiting content... (press Escape to cancel)\n";
1156 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
1157 ss<<L" Item definitions\n";
1158 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
1159 ss<<L" Node definitions\n";
1160 ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1163 draw_load_screen(ss.str(), driver, font);
1166 sleep_ms(1000*frametime);
1167 time_counter += frametime;
1172 if(error_message == L"" && !content_aborted){
1173 error_message = L"Something failed";
1174 errorstream<<wide_to_narrow(error_message)<<std::endl;
1176 // Break out of client scope
1181 After all content has been received:
1182 Update cached textures, meshes and materials
1184 client.afterContentReceived();
1187 Create the camera node
1189 Camera camera(smgr, draw_control, gamedef);
1190 if (!camera.successfullyCreated(error_message))
1193 f32 camera_yaw = 0; // "right/left"
1194 f32 camera_pitch = 0; // "up/down"
1200 Clouds *clouds = NULL;
1201 if(g_settings->getBool("enable_clouds"))
1203 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1211 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1217 FarMesh *farmesh = NULL;
1218 if(g_settings->getBool("enable_farmesh"))
1220 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1224 A copy of the local inventory
1226 Inventory local_inventory(itemdef);
1229 Find out size of crack animation
1231 int crack_animation_length = 5;
1233 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1234 v2u32 size = t->getOriginalSize();
1235 crack_animation_length = size.Y / size.X;
1242 // First line of debug text
1243 gui::IGUIStaticText *guitext = guienv->addStaticText(
1245 core::rect<s32>(5, 5, 795, 5+text_height),
1247 // Second line of debug text
1248 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1250 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1252 // At the middle of the screen
1253 // Object infos are shown in this
1254 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1256 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1259 // Status text (displays info when showing and hiding GUI stuff, etc.)
1260 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1262 core::rect<s32>(0,0,0,0),
1264 guitext_status->setVisible(false);
1266 std::wstring statustext;
1267 float statustext_time = 0;
1270 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1272 core::rect<s32>(0,0,0,0),
1273 //false, false); // Disable word wrap as of now
1275 // Remove stale "recent" chat messages from previous connections
1276 chat_backend.clearRecentChat();
1277 // Chat backend and console
1278 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1280 // Profiler text (size is updated when text is updated)
1281 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1283 core::rect<s32>(0,0,0,0),
1285 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1286 guitext_profiler->setVisible(false);
1289 Some statistics are collected in these
1292 u32 beginscenetime = 0;
1294 u32 endscenetime = 0;
1296 float recent_turn_speed = 0.0;
1298 ProfilerGraph graph;
1299 // Initially clear the profiler
1300 Profiler::GraphValues dummyvalues;
1301 g_profiler->graphGet(dummyvalues);
1303 float nodig_delay_timer = 0.0;
1304 float dig_time = 0.0;
1306 PointedThing pointed_old;
1307 bool digging = false;
1308 bool ldown_for_dig = false;
1310 float damage_flash = 0;
1311 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1313 const float object_hit_delay = 0.2;
1314 float object_hit_delay_timer = 0.0;
1315 float time_from_last_punch = 10;
1317 float update_draw_list_timer = 0.0;
1318 v3f update_draw_list_last_cam_dir;
1320 bool invert_mouse = g_settings->getBool("invert_mouse");
1322 bool respawn_menu_active = false;
1323 bool update_wielded_item_trigger = false;
1325 bool show_hud = true;
1326 bool show_chat = true;
1327 bool force_fog_off = false;
1328 f32 fog_range = 100*BS;
1329 bool disable_camera_update = false;
1330 bool show_debug = g_settings->getBool("show_debug");
1331 bool show_profiler_graph = false;
1332 u32 show_profiler = 0;
1333 u32 show_profiler_max = 3; // Number of pages
1335 float time_of_day = 0;
1336 float time_of_day_smooth = 0;
1338 float repeat_rightclick_timer = 0;
1343 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1344 sky, &force_fog_off, &fog_range, &client));
1350 bool first_loop_after_window_activation = true;
1352 // TODO: Convert the static interval timers to these
1353 // Interval limiter for profiler
1354 IntervalLimiter m_profiler_interval;
1356 // Time is in milliseconds
1357 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1358 // NOTE: So we have to use getTime() and call run()s between them
1359 u32 lasttime = device->getTimer()->getTime();
1361 LocalPlayer* player = client.getEnv().getLocalPlayer();
1362 player->hurt_tilt_timer = 0;
1363 player->hurt_tilt_strength = 0;
1367 if(device->run() == false || kill == true)
1370 // Time of frame without fps limit
1374 // not using getRealTime is necessary for wine
1375 u32 time = device->getTimer()->getTime();
1377 busytime_u32 = time - lasttime;
1380 busytime = busytime_u32 / 1000.0;
1383 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1385 // Necessary for device->getTimer()->getTime()
1393 float fps_max = g_settings->getFloat("fps_max");
1394 u32 frametime_min = 1000./fps_max;
1396 if(busytime_u32 < frametime_min)
1398 u32 sleeptime = frametime_min - busytime_u32;
1399 device->sleep(sleeptime);
1400 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1404 // Necessary for device->getTimer()->getTime()
1408 Time difference calculation
1410 f32 dtime; // in seconds
1412 u32 time = device->getTimer()->getTime();
1414 dtime = (time - lasttime) / 1000.0;
1419 g_profiler->graphAdd("mainloop_dtime", dtime);
1423 if(nodig_delay_timer >= 0)
1424 nodig_delay_timer -= dtime;
1425 if(object_hit_delay_timer >= 0)
1426 object_hit_delay_timer -= dtime;
1427 time_from_last_punch += dtime;
1429 g_profiler->add("Elapsed time", dtime);
1430 g_profiler->avg("FPS", 1./dtime);
1433 Time average and jitter calculation
1436 static f32 dtime_avg1 = 0.0;
1437 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1438 f32 dtime_jitter1 = dtime - dtime_avg1;
1440 static f32 dtime_jitter1_max_sample = 0.0;
1441 static f32 dtime_jitter1_max_fraction = 0.0;
1443 static f32 jitter1_max = 0.0;
1444 static f32 counter = 0.0;
1445 if(dtime_jitter1 > jitter1_max)
1446 jitter1_max = dtime_jitter1;
1451 dtime_jitter1_max_sample = jitter1_max;
1452 dtime_jitter1_max_fraction
1453 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1459 Busytime average and jitter calculation
1462 static f32 busytime_avg1 = 0.0;
1463 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1464 f32 busytime_jitter1 = busytime - busytime_avg1;
1466 static f32 busytime_jitter1_max_sample = 0.0;
1467 static f32 busytime_jitter1_min_sample = 0.0;
1469 static f32 jitter1_max = 0.0;
1470 static f32 jitter1_min = 0.0;
1471 static f32 counter = 0.0;
1472 if(busytime_jitter1 > jitter1_max)
1473 jitter1_max = busytime_jitter1;
1474 if(busytime_jitter1 < jitter1_min)
1475 jitter1_min = busytime_jitter1;
1479 busytime_jitter1_max_sample = jitter1_max;
1480 busytime_jitter1_min_sample = jitter1_min;
1487 Handle miscellaneous stuff
1490 if(client.accessDenied())
1492 error_message = L"Access denied. Reason: "
1493 +client.accessDeniedReason();
1494 errorstream<<wide_to_narrow(error_message)<<std::endl;
1498 if(g_gamecallback->disconnect_requested)
1500 g_gamecallback->disconnect_requested = false;
1504 if(g_gamecallback->changepassword_requested)
1506 (new GUIPasswordChange(guienv, guiroot, -1,
1507 &g_menumgr, &client))->drop();
1508 g_gamecallback->changepassword_requested = false;
1511 /* Process TextureSource's queue */
1512 tsrc->processQueue();
1514 /* Process ItemDefManager's queue */
1515 itemdef->processQueue(gamedef);
1518 Process ShaderSource's queue
1520 shsrc->processQueue();
1525 last_screensize = screensize;
1526 screensize = driver->getScreenSize();
1527 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1528 //bool screensize_changed = screensize != last_screensize;
1531 if(screensize.Y <= 800)
1532 hotbar_imagesize = 32;
1533 else if(screensize.Y <= 1280)
1534 hotbar_imagesize = 48;
1536 hotbar_imagesize = 64;
1538 // Hilight boxes collected during the loop and displayed
1539 std::vector<aabb3f> hilightboxes;
1542 std::wstring infotext;
1545 Debug info for client
1548 static float counter = 0.0;
1553 client.printDebugInfo(infostream);
1560 float profiler_print_interval =
1561 g_settings->getFloat("profiler_print_interval");
1562 bool print_to_log = true;
1563 if(profiler_print_interval == 0){
1564 print_to_log = false;
1565 profiler_print_interval = 5;
1567 if(m_profiler_interval.step(dtime, profiler_print_interval))
1570 infostream<<"Profiler:"<<std::endl;
1571 g_profiler->print(infostream);
1574 update_profiler_gui(guitext_profiler, font, text_height,
1575 show_profiler, show_profiler_max);
1577 g_profiler->clear();
1581 Direct handling of user input
1584 // Reset input if window not active or some menu is active
1585 if(device->isWindowActive() == false
1586 || noMenuActive() == false
1587 || guienv->hasFocus(gui_chat_console))
1592 // Input handler step() (used by the random input generator)
1596 Launch menus and trigger stuff according to keys
1598 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1600 // drop selected item
1601 IDropAction *a = new IDropAction();
1603 a->from_inv.setCurrentPlayer();
1604 a->from_list = "main";
1605 a->from_i = client.getPlayerItem();
1606 client.inventoryAction(a);
1608 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1610 infostream<<"the_game: "
1611 <<"Launching inventory"<<std::endl;
1613 GUIFormSpecMenu *menu =
1614 new GUIFormSpecMenu(device, guiroot, -1,
1618 InventoryLocation inventoryloc;
1619 inventoryloc.setCurrentPlayer();
1621 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1623 menu->setFormSpec(src->getForm(), inventoryloc);
1624 menu->setFormSource(src);
1625 menu->setTextDest(new TextDestPlayerInventory(&client));
1628 else if(input->wasKeyDown(EscapeKey))
1630 infostream<<"the_game: "
1631 <<"Launching pause menu"<<std::endl;
1632 // It will delete itself by itself
1633 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1634 &g_menumgr, simple_singleplayer_mode))->drop();
1636 // Move mouse cursor on top of the disconnect button
1637 if(simple_singleplayer_mode)
1638 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1640 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1642 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1644 TextDest *dest = new TextDestChat(&client);
1646 (new GUITextInputMenu(guienv, guiroot, -1,
1650 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1652 TextDest *dest = new TextDestChat(&client);
1654 (new GUITextInputMenu(guienv, guiroot, -1,
1658 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1660 if (!gui_chat_console->isOpenInhibited())
1662 // Open up to over half of the screen
1663 gui_chat_console->openConsole(0.6);
1664 guienv->setFocus(gui_chat_console);
1667 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1669 if(g_settings->getBool("free_move"))
1671 g_settings->set("free_move","false");
1672 statustext = L"free_move disabled";
1673 statustext_time = 0;
1677 g_settings->set("free_move","true");
1678 statustext = L"free_move enabled";
1679 statustext_time = 0;
1680 if(!client.checkPrivilege("fly"))
1681 statustext += L" (note: no 'fly' privilege)";
1684 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1686 if(g_settings->getBool("fast_move"))
1688 g_settings->set("fast_move","false");
1689 statustext = L"fast_move disabled";
1690 statustext_time = 0;
1694 g_settings->set("fast_move","true");
1695 statustext = L"fast_move enabled";
1696 statustext_time = 0;
1697 if(!client.checkPrivilege("fast"))
1698 statustext += L" (note: no 'fast' privilege)";
1701 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1703 if(g_settings->getBool("noclip"))
1705 g_settings->set("noclip","false");
1706 statustext = L"noclip disabled";
1707 statustext_time = 0;
1711 g_settings->set("noclip","true");
1712 statustext = L"noclip enabled";
1713 statustext_time = 0;
1714 if(!client.checkPrivilege("noclip"))
1715 statustext += L" (note: no 'noclip' privilege)";
1718 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1720 irr::video::IImage* const image = driver->createScreenShot();
1722 irr::c8 filename[256];
1723 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1724 g_settings->get("screenshot_path").c_str(),
1725 device->getTimer()->getRealTime());
1726 if (driver->writeImageToFile(image, filename)) {
1727 std::wstringstream sstr;
1728 sstr<<"Saved screenshot to '"<<filename<<"'";
1729 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1730 statustext = sstr.str();
1731 statustext_time = 0;
1733 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1738 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1740 show_hud = !show_hud;
1742 statustext = L"HUD shown";
1744 statustext = L"HUD hidden";
1745 statustext_time = 0;
1747 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1749 show_chat = !show_chat;
1751 statustext = L"Chat shown";
1753 statustext = L"Chat hidden";
1754 statustext_time = 0;
1756 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1758 force_fog_off = !force_fog_off;
1760 statustext = L"Fog disabled";
1762 statustext = L"Fog enabled";
1763 statustext_time = 0;
1765 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1767 disable_camera_update = !disable_camera_update;
1768 if(disable_camera_update)
1769 statustext = L"Camera update disabled";
1771 statustext = L"Camera update enabled";
1772 statustext_time = 0;
1774 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1776 // Initial / 3x toggle: Chat only
1777 // 1x toggle: Debug text with chat
1778 // 2x toggle: Debug text with profiler graph
1782 show_profiler_graph = false;
1783 statustext = L"Debug info shown";
1784 statustext_time = 0;
1786 else if(show_profiler_graph)
1789 show_profiler_graph = false;
1790 statustext = L"Debug info and profiler graph hidden";
1791 statustext_time = 0;
1795 show_profiler_graph = true;
1796 statustext = L"Profiler graph shown";
1797 statustext_time = 0;
1800 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1802 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1804 // FIXME: This updates the profiler with incomplete values
1805 update_profiler_gui(guitext_profiler, font, text_height,
1806 show_profiler, show_profiler_max);
1808 if(show_profiler != 0)
1810 std::wstringstream sstr;
1811 sstr<<"Profiler shown (page "<<show_profiler
1812 <<" of "<<show_profiler_max<<")";
1813 statustext = sstr.str();
1814 statustext_time = 0;
1818 statustext = L"Profiler hidden";
1819 statustext_time = 0;
1822 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1824 s16 range = g_settings->getS16("viewing_range_nodes_min");
1825 s16 range_new = range + 10;
1826 g_settings->set("viewing_range_nodes_min", itos(range_new));
1827 statustext = narrow_to_wide(
1828 "Minimum viewing range changed to "
1830 statustext_time = 0;
1832 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1834 s16 range = g_settings->getS16("viewing_range_nodes_min");
1835 s16 range_new = range - 10;
1838 g_settings->set("viewing_range_nodes_min",
1840 statustext = narrow_to_wide(
1841 "Minimum viewing range changed to "
1843 statustext_time = 0;
1846 // Handle QuicktuneShortcutter
1847 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1849 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1851 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1853 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1856 std::string msg = quicktune.getMessage();
1858 statustext = narrow_to_wide(msg);
1859 statustext_time = 0;
1863 // Item selection with mouse wheel
1864 u16 new_playeritem = client.getPlayerItem();
1866 s32 wheel = input->getMouseWheel();
1867 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1868 hotbar_itemcount-1);
1872 if(new_playeritem < max_item)
1879 if(new_playeritem > 0)
1882 new_playeritem = max_item;
1887 for(u16 i=0; i<10; i++)
1889 const KeyPress *kp = NumberKey + (i + 1) % 10;
1890 if(input->wasKeyDown(*kp))
1892 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1896 infostream<<"Selected item: "
1897 <<new_playeritem<<std::endl;
1902 // Viewing range selection
1903 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1905 draw_control.range_all = !draw_control.range_all;
1906 if(draw_control.range_all)
1908 infostream<<"Enabled full viewing range"<<std::endl;
1909 statustext = L"Enabled full viewing range";
1910 statustext_time = 0;
1914 infostream<<"Disabled full viewing range"<<std::endl;
1915 statustext = L"Disabled full viewing range";
1916 statustext_time = 0;
1920 // Print debug stacks
1921 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1923 dstream<<"-----------------------------------------"
1925 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1926 dstream<<"-----------------------------------------"
1928 debug_stacks_print();
1932 Mouse and camera control
1933 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1936 float turn_amount = 0;
1937 if((device->isWindowActive() && noMenuActive()) || random_input)
1941 // Mac OSX gets upset if this is set every frame
1942 if(device->getCursorControl()->isVisible())
1943 device->getCursorControl()->setVisible(false);
1946 if(first_loop_after_window_activation){
1947 //infostream<<"window active, first loop"<<std::endl;
1948 first_loop_after_window_activation = false;
1951 s32 dx = input->getMousePos().X - displaycenter.X;
1952 s32 dy = input->getMousePos().Y - displaycenter.Y;
1955 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1957 /*const float keyspeed = 500;
1958 if(input->isKeyDown(irr::KEY_UP))
1959 dy -= dtime * keyspeed;
1960 if(input->isKeyDown(irr::KEY_DOWN))
1961 dy += dtime * keyspeed;
1962 if(input->isKeyDown(irr::KEY_LEFT))
1963 dx -= dtime * keyspeed;
1964 if(input->isKeyDown(irr::KEY_RIGHT))
1965 dx += dtime * keyspeed;*/
1969 camera_pitch += dy*d;
1970 if(camera_pitch < -89.5) camera_pitch = -89.5;
1971 if(camera_pitch > 89.5) camera_pitch = 89.5;
1973 turn_amount = v2f(dx, dy).getLength() * d;
1975 input->setMousePos(displaycenter.X, displaycenter.Y);
1978 // Mac OSX gets upset if this is set every frame
1979 if(device->getCursorControl()->isVisible() == false)
1980 device->getCursorControl()->setVisible(true);
1982 //infostream<<"window inactive"<<std::endl;
1983 first_loop_after_window_activation = true;
1985 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1986 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1989 Player speed control
2003 PlayerControl control(
2004 input->isKeyDown(getKeySetting("keymap_forward")),
2005 input->isKeyDown(getKeySetting("keymap_backward")),
2006 input->isKeyDown(getKeySetting("keymap_left")),
2007 input->isKeyDown(getKeySetting("keymap_right")),
2008 input->isKeyDown(getKeySetting("keymap_jump")),
2009 input->isKeyDown(getKeySetting("keymap_special1")),
2010 input->isKeyDown(getKeySetting("keymap_sneak")),
2011 input->getLeftState(),
2012 input->getRightState(),
2016 client.setPlayerControl(control);
2018 1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2019 2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2020 4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2021 8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2022 16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2023 32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2024 64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2025 128*(int)input->getLeftState()+
2026 256*(int)input->getRightState();
2027 LocalPlayer* player = client.getEnv().getLocalPlayer();
2028 player->keyPressed=keyPressed;
2037 //TimeTaker timer("server->step(dtime)");
2038 server->step(dtime);
2046 //TimeTaker timer("client.step(dtime)");
2048 //client.step(dtime_avg1);
2052 // Read client events
2055 ClientEvent event = client.getClientEvent();
2056 if(event.type == CE_NONE)
2060 else if(event.type == CE_PLAYER_DAMAGE)
2062 //u16 damage = event.player_damage.amount;
2063 //infostream<<"Player damage: "<<damage<<std::endl;
2065 damage_flash += 100.0;
2066 damage_flash += 8.0 * event.player_damage.amount;
2068 player->hurt_tilt_timer = 1.5;
2069 player->hurt_tilt_strength = event.player_damage.amount/2;
2070 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2072 else if(event.type == CE_PLAYER_FORCE_MOVE)
2074 camera_yaw = event.player_force_move.yaw;
2075 camera_pitch = event.player_force_move.pitch;
2077 else if(event.type == CE_DEATHSCREEN)
2079 if(respawn_menu_active)
2082 /*bool set_camera_point_target =
2083 event.deathscreen.set_camera_point_target;
2084 v3f camera_point_target;
2085 camera_point_target.X = event.deathscreen.camera_point_target_x;
2086 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2087 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2088 MainRespawnInitiator *respawner =
2089 new MainRespawnInitiator(
2090 &respawn_menu_active, &client);
2091 GUIDeathScreen *menu =
2092 new GUIDeathScreen(guienv, guiroot, -1,
2093 &g_menumgr, respawner);
2096 chat_backend.addMessage(L"", L"You died.");
2098 /* Handle visualization */
2102 LocalPlayer* player = client.getEnv().getLocalPlayer();
2103 player->hurt_tilt_timer = 0;
2104 player->hurt_tilt_strength = 0;
2106 /*LocalPlayer* player = client.getLocalPlayer();
2107 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2108 camera.update(player, busytime, screensize);*/
2110 else if (event.type == CE_SHOW_FORMSPEC)
2112 if (current_formspec == 0)
2115 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2117 GUIFormSpecMenu *menu =
2118 new GUIFormSpecMenu(device, guiroot, -1,
2121 menu->setFormSource(current_formspec);
2127 current_formspec->setForm(*(event.show_formspec.formspec));
2129 delete(event.show_formspec.formspec);
2131 else if(event.type == CE_TEXTURES_UPDATED)
2133 update_wielded_item_trigger = true;
2138 //TimeTaker //timer2("//timer2");
2141 For interaction purposes, get info about the held item
2143 - Is it a usable item?
2144 - Can it point to liquids?
2146 ItemStack playeritem;
2147 bool playeritem_usable = false;
2148 bool playeritem_liquids_pointable = false;
2150 InventoryList *mlist = local_inventory.getList("main");
2153 playeritem = mlist->getItem(client.getPlayerItem());
2154 playeritem_usable = playeritem.getDefinition(itemdef).usable;
2155 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
2158 ToolCapabilities playeritem_toolcap =
2159 playeritem.getToolCapabilities(itemdef);
2165 LocalPlayer* player = client.getEnv().getLocalPlayer();
2166 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2167 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2168 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2169 camera.update(player, busytime, screensize, tool_reload_ratio);
2172 v3f player_position = player->getPosition();
2173 v3f camera_position = camera.getPosition();
2174 v3f camera_direction = camera.getDirection();
2175 f32 camera_fov = camera.getFovMax();
2177 if(!disable_camera_update){
2178 client.getEnv().getClientMap().updateCamera(camera_position,
2179 camera_direction, camera_fov);
2182 // Update sound listener
2183 sound->updateListener(camera.getCameraNode()->getPosition(),
2184 v3f(0,0,0), // velocity
2185 camera.getDirection(),
2186 camera.getCameraNode()->getUpVector());
2187 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2193 soundmaker.step(dtime);
2195 ClientMap &map = client.getEnv().getClientMap();
2196 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2197 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2201 Calculate what block is the crosshair pointing to
2204 //u32 t1 = device->getTimer()->getRealTime();
2206 f32 d = 4; // max. distance
2207 core::line3d<f32> shootline(camera_position,
2208 camera_position + camera_direction * BS * (d+1));
2210 ClientActiveObject *selected_object = NULL;
2212 PointedThing pointed = getPointedThing(
2214 &client, player_position, camera_direction,
2215 camera_position, shootline, d,
2216 playeritem_liquids_pointable, !ldown_for_dig,
2221 if(pointed != pointed_old)
2223 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2224 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2229 - releasing left mouse button
2230 - pointing away from node
2234 if(input->getLeftReleased())
2236 infostream<<"Left button released"
2237 <<" (stopped digging)"<<std::endl;
2240 else if(pointed != pointed_old)
2242 if (pointed.type == POINTEDTHING_NODE
2243 && pointed_old.type == POINTEDTHING_NODE
2244 && pointed.node_undersurface == pointed_old.node_undersurface)
2246 // Still pointing to the same node,
2247 // but a different face. Don't reset.
2251 infostream<<"Pointing away from node"
2252 <<" (stopped digging)"<<std::endl;
2258 client.interact(1, pointed_old);
2259 client.setCrack(-1, v3s16(0,0,0));
2263 if(!digging && ldown_for_dig && !input->getLeftState())
2265 ldown_for_dig = false;
2268 bool left_punch = false;
2269 soundmaker.m_player_leftpunch_sound.name = "";
2271 if(input->getRightState())
2272 repeat_rightclick_timer += dtime;
2274 if(playeritem_usable && input->getLeftState())
2276 if(input->getLeftClicked())
2277 client.interact(4, pointed);
2279 else if(pointed.type == POINTEDTHING_NODE)
2281 v3s16 nodepos = pointed.node_undersurface;
2282 v3s16 neighbourpos = pointed.node_abovesurface;
2285 Check information text of node
2288 ClientMap &map = client.getEnv().getClientMap();
2289 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2291 infotext = narrow_to_wide(meta->getString("infotext"));
2293 MapNode n = map.getNode(nodepos);
2294 if(nodedef->get(n).tiledef[0].name == "unknown_block.png"){
2295 infotext = L"Unknown node: ";
2296 infotext += narrow_to_wide(nodedef->get(n).name);
2300 // We can't actually know, but assume the sound of right-clicking
2301 // to be the sound of placing a node
2302 soundmaker.m_player_rightpunch_sound.gain = 0.5;
2303 soundmaker.m_player_rightpunch_sound.name = "default_place_node";
2309 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2313 infostream<<"Started digging"<<std::endl;
2314 client.interact(0, pointed);
2316 ldown_for_dig = true;
2318 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2320 // NOTE: Similar piece of code exists on the server side for
2322 // Get digging parameters
2323 DigParams params = getDigParams(nodedef->get(n).groups,
2324 &playeritem_toolcap);
2325 // If can't dig, try hand
2326 if(!params.diggable){
2327 const ItemDefinition &hand = itemdef->get("");
2328 const ToolCapabilities *tp = hand.tool_capabilities;
2330 params = getDigParams(nodedef->get(n).groups, tp);
2333 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2334 if(sound_dig.exists()){
2335 if(sound_dig.name == "__group"){
2336 if(params.main_group != ""){
2337 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2338 soundmaker.m_player_leftpunch_sound.name =
2339 std::string("default_dig_") +
2343 soundmaker.m_player_leftpunch_sound = sound_dig;
2347 float dig_time_complete = 0.0;
2349 if(params.diggable == false)
2351 // I guess nobody will wait for this long
2352 dig_time_complete = 10000000.0;
2356 dig_time_complete = params.time;
2359 if(dig_time_complete >= 0.001)
2361 dig_index = (u16)((float)crack_animation_length
2362 * dig_time/dig_time_complete);
2364 // This is for torches
2367 dig_index = crack_animation_length;
2370 // Don't show cracks if not diggable
2371 if(dig_time_complete >= 100000.0)
2374 else if(dig_index < crack_animation_length)
2376 //TimeTaker timer("client.setTempMod");
2377 //infostream<<"dig_index="<<dig_index<<std::endl;
2378 client.setCrack(dig_index, nodepos);
2382 infostream<<"Digging completed"<<std::endl;
2383 client.interact(2, pointed);
2384 client.setCrack(-1, v3s16(0,0,0));
2385 MapNode wasnode = map.getNode(nodepos);
2386 client.removeNode(nodepos);
2391 nodig_delay_timer = dig_time_complete
2392 / (float)crack_animation_length;
2394 // We don't want a corresponding delay to
2395 // very time consuming nodes
2396 if(nodig_delay_timer > 0.3)
2397 nodig_delay_timer = 0.3;
2398 // We want a slight delay to very little
2399 // time consuming nodes
2400 float mindelay = 0.15;
2401 if(nodig_delay_timer < mindelay)
2402 nodig_delay_timer = mindelay;
2404 // Send event to trigger sound
2405 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2406 gamedef->event()->put(e);
2411 camera.setDigging(0); // left click animation
2414 if(input->getRightClicked() ||
2415 repeat_rightclick_timer >= g_settings->getFloat("repeat_rightclick_time"))
2417 repeat_rightclick_timer = 0;
2418 infostream<<"Ground right-clicked"<<std::endl;
2420 // Sign special case, at least until formspec is properly implemented.
2422 if(meta && meta->getString("formspec") == "hack:sign_text_input" && !random_input)
2424 infostream<<"Launching metadata text input"<<std::endl;
2426 // Get a new text for it
2428 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2430 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2432 (new GUITextInputMenu(guienv, guiroot, -1,
2436 // If metadata provides an inventory view, activate it
2437 else if(meta && meta->getString("formspec") != "" && !random_input)
2439 infostream<<"Launching custom inventory view"<<std::endl;
2441 InventoryLocation inventoryloc;
2442 inventoryloc.setNodeMeta(nodepos);
2446 GUIFormSpecMenu *menu =
2447 new GUIFormSpecMenu(device, guiroot, -1,
2450 menu->setFormSpec(meta->getString("formspec"),
2452 menu->setFormSource(new NodeMetadataFormSource(
2453 &client.getEnv().getClientMap(), nodepos));
2454 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2457 // Otherwise report right click to server
2461 client.interact(3, pointed);
2462 camera.setDigging(1); // right click animation
2464 // If the wielded item has node placement prediction,
2466 const ItemDefinition &def =
2467 playeritem.getDefinition(itemdef);
2468 if(def.node_placement_prediction != "")
2470 verbosestream<<"Node placement prediction for "
2471 <<playeritem.name<<" is "
2472 <<def.node_placement_prediction<<std::endl;
2473 v3s16 p = neighbourpos;
2474 // Place inside node itself if buildable_to
2476 MapNode n_under = map.getNode(nodepos);
2477 if(nodedef->get(n_under).buildable_to)
2479 }catch(InvalidPositionException &e){}
2480 // Find id of predicted node
2483 nodedef->getId(def.node_placement_prediction, id);
2485 errorstream<<"Node placement prediction failed for "
2486 <<playeritem.name<<" (places "
2487 <<def.node_placement_prediction
2488 <<") - Name not known"<<std::endl;
2493 // This triggers the required mesh update too
2494 client.addNode(p, n);
2495 }catch(InvalidPositionException &e){
2496 errorstream<<"Node placement prediction failed for "
2497 <<playeritem.name<<" (places "
2498 <<def.node_placement_prediction
2499 <<") - Position not loaded"<<std::endl;
2505 else if(pointed.type == POINTEDTHING_OBJECT)
2507 infotext = narrow_to_wide(selected_object->infoText());
2509 if(infotext == L"" && show_debug){
2510 infotext = narrow_to_wide(selected_object->debugInfoText());
2513 //if(input->getLeftClicked())
2514 if(input->getLeftState())
2516 bool do_punch = false;
2517 bool do_punch_damage = false;
2518 if(object_hit_delay_timer <= 0.0){
2520 do_punch_damage = true;
2521 object_hit_delay_timer = object_hit_delay;
2523 if(input->getLeftClicked()){
2527 infostream<<"Left-clicked object"<<std::endl;
2530 if(do_punch_damage){
2531 // Report direct punch
2532 v3f objpos = selected_object->getPosition();
2533 v3f dir = (objpos - player_position).normalize();
2535 bool disable_send = selected_object->directReportPunch(
2536 dir, &playeritem, time_from_last_punch);
2537 time_from_last_punch = 0;
2539 client.interact(0, pointed);
2542 else if(input->getRightClicked())
2544 infostream<<"Right-clicked object"<<std::endl;
2545 client.interact(3, pointed); // place
2548 else if(input->getLeftState())
2550 // When button is held down in air, show continuous animation
2554 pointed_old = pointed;
2556 if(left_punch || input->getLeftClicked())
2558 camera.setDigging(0); // left click animation
2561 input->resetLeftClicked();
2562 input->resetRightClicked();
2564 input->resetLeftReleased();
2565 input->resetRightReleased();
2568 Calculate stuff for drawing
2577 fog_range = BS*farmesh_range;
2581 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2583 if(draw_control.range_all)
2584 fog_range = 100000*BS;
2588 Calculate general brightness
2590 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2591 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2592 float direct_brightness = 0;
2593 bool sunlight_seen = false;
2594 if(g_settings->getBool("free_move")){
2595 direct_brightness = time_brightness;
2596 sunlight_seen = true;
2598 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2599 float old_brightness = sky->getBrightness();
2600 direct_brightness = (float)client.getEnv().getClientMap()
2601 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2602 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2606 time_of_day = client.getEnv().getTimeOfDayF();
2608 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2609 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2610 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2611 time_of_day_smooth = time_of_day;
2613 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2614 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2615 + (time_of_day+1.0) * todsm;
2617 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2618 + time_of_day * todsm;
2620 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2623 float brightness = sky->getBrightness();
2624 video::SColor bgcolor = sky->getBgColor();
2625 video::SColor skycolor = sky->getSkyColor();
2631 if(sky->getCloudsVisible()){
2632 clouds->setVisible(true);
2633 clouds->step(dtime);
2634 clouds->update(v2f(player_position.X, player_position.Z),
2635 sky->getCloudColor());
2637 clouds->setVisible(false);
2646 farmesh_range = draw_control.wanted_range * 10;
2647 if(draw_control.range_all && farmesh_range < 500)
2648 farmesh_range = 500;
2649 if(farmesh_range > 1000)
2650 farmesh_range = 1000;
2652 farmesh->step(dtime);
2653 farmesh->update(v2f(player_position.X, player_position.Z),
2654 brightness, farmesh_range);
2661 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2665 video::EFT_FOG_LINEAR,
2677 video::EFT_FOG_LINEAR,
2687 Update gui stuff (0ms)
2690 //TimeTaker guiupdatetimer("Gui updating");
2692 const char program_name_and_version[] =
2693 "Minetest " VERSION_STRING;
2697 static float drawtime_avg = 0;
2698 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2699 /*static float beginscenetime_avg = 0;
2700 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2701 static float scenetime_avg = 0;
2702 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2703 static float endscenetime_avg = 0;
2704 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2707 snprintf(temptext, 300, "%s ("
2710 " drawtime=%.0f, dtime_jitter = % .1f %%"
2711 ", v_range = %.1f, RTT = %.3f",
2712 program_name_and_version,
2713 draw_control.range_all,
2715 dtime_jitter1_max_fraction * 100.0,
2716 draw_control.wanted_range,
2720 guitext->setText(narrow_to_wide(temptext).c_str());
2721 guitext->setVisible(true);
2723 else if(show_hud || show_chat)
2725 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2726 guitext->setVisible(true);
2730 guitext->setVisible(false);
2736 snprintf(temptext, 300,
2737 "(% .1f, % .1f, % .1f)"
2738 " (yaw = %.1f) (seed = %lli)",
2739 player_position.X/BS,
2740 player_position.Y/BS,
2741 player_position.Z/BS,
2742 wrapDegrees_0_360(camera_yaw),
2743 client.getMapSeed());
2745 guitext2->setText(narrow_to_wide(temptext).c_str());
2746 guitext2->setVisible(true);
2750 guitext2->setVisible(false);
2754 guitext_info->setText(infotext.c_str());
2755 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2759 float statustext_time_max = 1.5;
2760 if(!statustext.empty())
2762 statustext_time += dtime;
2763 if(statustext_time >= statustext_time_max)
2766 statustext_time = 0;
2769 guitext_status->setText(statustext.c_str());
2770 guitext_status->setVisible(!statustext.empty());
2772 if(!statustext.empty())
2774 s32 status_y = screensize.Y - 130;
2775 core::rect<s32> rect(
2777 status_y - guitext_status->getTextHeight(),
2781 guitext_status->setRelativePosition(rect);
2784 video::SColor initial_color(255,0,0,0);
2785 if(guienv->getSkin())
2786 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2787 video::SColor final_color = initial_color;
2788 final_color.setAlpha(0);
2789 video::SColor fade_color =
2790 initial_color.getInterpolated_quadratic(
2793 pow(statustext_time / (float)statustext_time_max, 2.0f));
2794 guitext_status->setOverrideColor(fade_color);
2795 guitext_status->enableOverrideColor(true);
2800 Get chat messages from client
2803 // Get new messages from error log buffer
2804 while(!chat_log_error_buf.empty())
2806 chat_backend.addMessage(L"", narrow_to_wide(
2807 chat_log_error_buf.get()));
2809 // Get new messages from client
2810 std::wstring message;
2811 while(client.getChatMessage(message))
2813 chat_backend.addUnparsedMessage(message);
2815 // Remove old messages
2816 chat_backend.step(dtime);
2818 // Display all messages in a static text element
2819 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2820 std::wstring recent_chat = chat_backend.getRecentChat();
2821 guitext_chat->setText(recent_chat.c_str());
2823 // Update gui element size and position
2824 s32 chat_y = 5+(text_height+5);
2826 chat_y += (text_height+5);
2827 core::rect<s32> rect(
2831 chat_y + guitext_chat->getTextHeight()
2833 guitext_chat->setRelativePosition(rect);
2835 // Don't show chat if disabled or empty or profiler is enabled
2836 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2844 if(client.getPlayerItem() != new_playeritem)
2846 client.selectPlayerItem(new_playeritem);
2848 if(client.getLocalInventoryUpdated())
2850 //infostream<<"Updating local inventory"<<std::endl;
2851 client.getLocalInventory(local_inventory);
2853 update_wielded_item_trigger = true;
2855 if(update_wielded_item_trigger)
2857 update_wielded_item_trigger = false;
2858 // Update wielded tool
2859 InventoryList *mlist = local_inventory.getList("main");
2862 item = mlist->getItem(client.getPlayerItem());
2867 Update block draw list every 200ms or when camera direction has
2870 update_draw_list_timer += dtime;
2871 if(update_draw_list_timer >= 0.2 ||
2872 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
2873 update_draw_list_timer = 0;
2874 client.getEnv().getClientMap().updateDrawList(driver);
2875 update_draw_list_last_cam_dir = camera_direction;
2882 TimeTaker tt_draw("mainloop: draw");
2886 TimeTaker timer("beginScene");
2887 //driver->beginScene(false, true, bgcolor);
2888 //driver->beginScene(true, true, bgcolor);
2889 driver->beginScene(true, true, skycolor);
2890 beginscenetime = timer.stop(true);
2895 //infostream<<"smgr->drawAll()"<<std::endl;
2897 TimeTaker timer("smgr");
2900 if(g_settings->getBool("anaglyph"))
2902 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
2903 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
2905 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
2907 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
2908 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
2909 camera.getCameraNode()->getAbsolutePosition() ;
2912 irr::core::vector3df leftEye;
2913 irr::core::matrix4 leftMove;
2915 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
2916 leftEye=(startMatrix*leftMove).getTranslation();
2918 //clear the depth buffer, and color
2919 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
2921 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
2922 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
2923 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
2924 irr::scene::ESNRP_SOLID +
2925 irr::scene::ESNRP_TRANSPARENT +
2926 irr::scene::ESNRP_TRANSPARENT_EFFECT +
2927 irr::scene::ESNRP_SHADOW;
2929 camera.getCameraNode()->setPosition( leftEye );
2930 camera.getCameraNode()->setTarget( focusPoint );
2932 smgr->drawAll(); // 'smgr->drawAll();' may go here
2936 irr::core::vector3df rightEye;
2937 irr::core::matrix4 rightMove;
2939 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
2940 rightEye=(startMatrix*rightMove).getTranslation();
2942 //clear the depth buffer
2943 driver->clearZBuffer();
2945 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
2946 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
2947 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
2948 irr::scene::ESNRP_SOLID +
2949 irr::scene::ESNRP_TRANSPARENT +
2950 irr::scene::ESNRP_TRANSPARENT_EFFECT +
2951 irr::scene::ESNRP_SHADOW;
2953 camera.getCameraNode()->setPosition( rightEye );
2954 camera.getCameraNode()->setTarget( focusPoint );
2956 smgr->drawAll(); // 'smgr->drawAll();' may go here
2959 //driver->endScene();
2961 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
2962 driver->getOverrideMaterial().EnableFlags=0;
2963 driver->getOverrideMaterial().EnablePasses=0;
2965 camera.getCameraNode()->setPosition( oldPosition );
2966 camera.getCameraNode()->setTarget( oldTarget );
2969 scenetime = timer.stop(true);
2973 //TimeTaker timer9("auxiliary drawings");
2977 //TimeTaker //timer10("//timer10");
2983 driver->setMaterial(m);
2985 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2989 v3f selectionbox_color = g_settings->getV3F("selectionbox_color");
2990 u32 selectionbox_color_r = rangelim(myround(selectionbox_color.X), 0, 255);
2991 u32 selectionbox_color_g = rangelim(myround(selectionbox_color.Y), 0, 255);
2992 u32 selectionbox_color_b = rangelim(myround(selectionbox_color.Z), 0, 255);
2994 for(std::vector<aabb3f>::const_iterator
2995 i = hilightboxes.begin();
2996 i != hilightboxes.end(); i++)
2998 /*infostream<<"hilightbox min="
2999 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
3001 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
3003 driver->draw3DBox(*i, video::SColor(255,selectionbox_color_r,selectionbox_color_g,selectionbox_color_b));
3012 // Warning: This clears the Z buffer.
3013 camera.drawWieldedTool();
3020 client.getEnv().getClientMap().renderPostFx();
3026 if(show_profiler_graph)
3028 graph.draw(10, screensize.Y - 10, driver, font);
3036 v3f crosshair_color = g_settings->getV3F("crosshair_color");
3037 u32 crosshair_color_r = rangelim(myround(crosshair_color.X), 0, 255);
3038 u32 crosshair_color_g = rangelim(myround(crosshair_color.Y), 0, 255);
3039 u32 crosshair_color_b = rangelim(myround(crosshair_color.Z), 0, 255);
3040 u32 crosshair_alpha = rangelim(g_settings->getS32("crosshair_alpha"), 0, 255);
3042 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
3043 displaycenter + core::vector2d<s32>(10,0),
3044 video::SColor(crosshair_alpha,crosshair_color_r,crosshair_color_g,crosshair_color_b));
3045 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
3046 displaycenter + core::vector2d<s32>(0,10),
3047 video::SColor(crosshair_alpha,crosshair_color_r,crosshair_color_g,crosshair_color_b));
3053 //TimeTaker //timer11("//timer11");
3061 draw_hotbar(driver, font, gamedef,
3062 v2s32(displaycenter.X, screensize.Y),
3063 hotbar_imagesize, hotbar_itemcount, &local_inventory,
3064 client.getHP(), client.getPlayerItem());
3070 if(damage_flash > 0.0)
3072 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3073 driver->draw2DRectangle(color,
3074 core::rect<s32>(0,0,screensize.X,screensize.Y),
3077 damage_flash -= 100.0*dtime;
3083 if(player->hurt_tilt_timer > 0.0)
3085 player->hurt_tilt_timer -= dtime*5;
3086 if(player->hurt_tilt_timer < 0)
3087 player->hurt_tilt_strength = 0;
3100 TimeTaker timer("endScene");
3102 endscenetime = timer.stop(true);
3105 drawtime = tt_draw.stop(true);
3106 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3112 static s16 lastFPS = 0;
3113 //u16 fps = driver->getFPS();
3114 u16 fps = (1.0/dtime_avg1);
3118 core::stringw str = L"Minetest [";
3119 str += driver->getName();
3123 device->setWindowCaption(str.c_str());
3128 Log times and stuff for visualization
3130 Profiler::GraphValues values;
3131 g_profiler->graphGet(values);
3140 if(gui_chat_console)
3141 gui_chat_console->drop();
3144 Draw a "shutting down" screen, which will be shown while the map
3145 generator and other stuff quits
3148 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3149 draw_load_screen(L"Shutting down stuff...", driver, font);
3150 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3153 gui_shuttingdowntext->remove();*/
3156 chat_backend.addMessage(L"", L"# Disconnected.");
3157 chat_backend.addMessage(L"", L"");
3159 // Client scope (client is destructed before destructing *def and tsrc)
3162 catch(SerializationError &e)
3164 error_message = L"A serialization error occurred:\n"
3165 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3166 L" running a different version of Minetest.";
3167 errorstream<<wide_to_narrow(error_message)<<std::endl;