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;
198 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
200 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
201 Inventory *inventory, s32 halfheartcount, u16 playeritem)
203 InventoryList *mainlist = inventory->getList("main");
206 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
210 s32 padding = imgsize/12;
211 //s32 height = imgsize + padding*2;
212 s32 width = itemcount*(imgsize+padding*2);
214 // Position of upper left corner of bar
215 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
217 // Draw background color
218 /*core::rect<s32> barrect(0,0,width,height);
220 video::SColor bgcolor(255,128,128,128);
221 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
223 core::rect<s32> imgrect(0,0,imgsize,imgsize);
225 for(s32 i=0; i<itemcount; i++)
227 const ItemStack &item = mainlist->getItem(i);
229 core::rect<s32> rect = imgrect + pos
230 + v2s32(padding+i*(imgsize+padding*2), padding);
234 video::SColor c_outside(255,255,0,0);
235 //video::SColor c_outside(255,0,0,0);
236 //video::SColor c_inside(255,192,192,192);
237 s32 x1 = rect.UpperLeftCorner.X;
238 s32 y1 = rect.UpperLeftCorner.Y;
239 s32 x2 = rect.LowerRightCorner.X;
240 s32 y2 = rect.LowerRightCorner.Y;
241 // Black base borders
242 driver->draw2DRectangle(c_outside,
244 v2s32(x1 - padding, y1 - padding),
245 v2s32(x2 + padding, y1)
247 driver->draw2DRectangle(c_outside,
249 v2s32(x1 - padding, y2),
250 v2s32(x2 + padding, y2 + padding)
252 driver->draw2DRectangle(c_outside,
254 v2s32(x1 - padding, y1),
257 driver->draw2DRectangle(c_outside,
260 v2s32(x2 + padding, y2)
262 /*// Light inside borders
263 driver->draw2DRectangle(c_inside,
265 v2s32(x1 - padding/2, y1 - padding/2),
266 v2s32(x2 + padding/2, y1)
268 driver->draw2DRectangle(c_inside,
270 v2s32(x1 - padding/2, y2),
271 v2s32(x2 + padding/2, y2 + padding/2)
273 driver->draw2DRectangle(c_inside,
275 v2s32(x1 - padding/2, y1),
278 driver->draw2DRectangle(c_inside,
281 v2s32(x2 + padding/2, y2)
286 video::SColor bgcolor2(128,0,0,0);
287 driver->draw2DRectangle(bgcolor2, rect, NULL);
288 drawItemStack(driver, font, item, rect, NULL, gamedef);
294 video::ITexture *heart_texture =
295 gamedef->getTextureSource()->getTextureRaw("heart.png");
298 v2s32 p = pos + v2s32(0, -20);
299 for(s32 i=0; i<halfheartcount/2; i++)
301 const video::SColor color(255,255,255,255);
302 const video::SColor colors[] = {color,color,color,color};
303 core::rect<s32> rect(0,0,16,16);
305 driver->draw2DImage(heart_texture, rect,
306 core::rect<s32>(core::position2d<s32>(0,0),
307 core::dimension2di(heart_texture->getOriginalSize())),
311 if(halfheartcount % 2 == 1)
313 const video::SColor color(255,255,255,255);
314 const video::SColor colors[] = {color,color,color,color};
315 core::rect<s32> rect(0,0,16/2,16);
317 core::dimension2di srcd(heart_texture->getOriginalSize());
319 driver->draw2DImage(heart_texture, rect,
320 core::rect<s32>(core::position2d<s32>(0,0), srcd),
328 Check if a node is pointable
330 inline bool isPointableNode(const MapNode& n,
331 Client *client, bool liquids_pointable)
333 const ContentFeatures &features = client->getNodeDefManager()->get(n);
334 return features.pointable ||
335 (liquids_pointable && features.isLiquid());
339 Find what the player is pointing at
341 PointedThing getPointedThing(Client *client, v3f player_position,
342 v3f camera_direction, v3f camera_position,
343 core::line3d<f32> shootline, f32 d,
344 bool liquids_pointable,
345 bool look_for_object,
346 std::vector<aabb3f> &hilightboxes,
347 ClientActiveObject *&selected_object)
351 hilightboxes.clear();
352 selected_object = NULL;
354 INodeDefManager *nodedef = client->getNodeDefManager();
355 ClientMap &map = client->getEnv().getClientMap();
357 // First try to find a pointed at active object
360 selected_object = client->getSelectedActiveObject(d*BS,
361 camera_position, shootline);
363 if(selected_object != NULL)
365 if(selected_object->doShowSelectionBox())
367 aabb3f *selection_box = selected_object->getSelectionBox();
368 // Box should exist because object was
369 // returned in the first place
370 assert(selection_box);
372 v3f pos = selected_object->getPosition();
373 hilightboxes.push_back(aabb3f(
374 selection_box->MinEdge + pos,
375 selection_box->MaxEdge + pos));
379 result.type = POINTEDTHING_OBJECT;
380 result.object_id = selected_object->getId();
385 // That didn't work, try to find a pointed at node
387 f32 mindistance = BS * 1001;
389 v3s16 pos_i = floatToInt(player_position, BS);
391 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
395 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
396 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
397 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
398 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
399 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
400 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
402 // Prevent signed number overflow
410 for(s16 y = ystart; y <= yend; y++)
411 for(s16 z = zstart; z <= zend; z++)
412 for(s16 x = xstart; x <= xend; x++)
417 n = map.getNode(v3s16(x,y,z));
419 catch(InvalidPositionException &e)
423 if(!isPointableNode(n, client, liquids_pointable))
426 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
429 v3f npf = intToFloat(np, BS);
431 for(std::vector<aabb3f>::const_iterator
433 i != boxes.end(); i++)
439 for(u16 j=0; j<6; j++)
441 v3s16 facedir = g_6dirs[j];
442 aabb3f facebox = box;
446 facebox.MinEdge.X = facebox.MaxEdge.X-d;
447 else if(facedir.X < 0)
448 facebox.MaxEdge.X = facebox.MinEdge.X+d;
449 else if(facedir.Y > 0)
450 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
451 else if(facedir.Y < 0)
452 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
453 else if(facedir.Z > 0)
454 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
455 else if(facedir.Z < 0)
456 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
458 v3f centerpoint = facebox.getCenter();
459 f32 distance = (centerpoint - camera_position).getLength();
460 if(distance >= mindistance)
462 if(!facebox.intersectsWithLine(shootline))
465 v3s16 np_above = np + facedir;
467 result.type = POINTEDTHING_NODE;
468 result.node_undersurface = np;
469 result.node_abovesurface = np_above;
470 mindistance = distance;
472 hilightboxes.clear();
473 for(std::vector<aabb3f>::const_iterator
475 i2 != boxes.end(); i2++)
478 box.MinEdge += npf + v3f(-d,-d,-d);
479 box.MaxEdge += npf + v3f(d,d,d);
480 hilightboxes.push_back(box);
490 Draws a screen with a single text on it.
491 Text will be removed when the screen is drawn the next time.
493 /*gui::IGUIStaticText **/
494 void draw_load_screen(const std::wstring &text,
495 video::IVideoDriver* driver, gui::IGUIFont* font)
497 v2u32 screensize = driver->getScreenSize();
498 const wchar_t *loadingtext = text.c_str();
499 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
500 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
501 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
502 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
504 gui::IGUIStaticText *guitext = guienv->addStaticText(
505 loadingtext, textrect, false, false);
506 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
508 driver->beginScene(true, true, video::SColor(255,0,0,0));
517 /* Profiler display */
519 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
520 gui::IGUIFont *font, u32 text_height,
521 u32 show_profiler, u32 show_profiler_max)
523 if(show_profiler == 0)
525 guitext_profiler->setVisible(false);
530 std::ostringstream os(std::ios_base::binary);
531 g_profiler->printPage(os, show_profiler, show_profiler_max);
532 std::wstring text = narrow_to_wide(os.str());
533 guitext_profiler->setText(text.c_str());
534 guitext_profiler->setVisible(true);
536 s32 w = font->getDimension(text.c_str()).Width;
539 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
540 8+(text_height+5)*2 +
541 font->getDimension(text.c_str()).Height);
542 guitext_profiler->setRelativePosition(rect);
543 guitext_profiler->setVisible(true);
551 Profiler::GraphValues values;
557 Meta(float initial=0, video::SColor color=
558 video::SColor(255,255,255,255)):
564 std::list<Piece> m_log;
572 void put(const Profiler::GraphValues &values)
575 piece.values = values;
576 m_log.push_back(piece);
577 while(m_log.size() > m_log_max_size)
578 m_log.erase(m_log.begin());
581 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
582 gui::IGUIFont* font) const
584 std::map<std::string, Meta> m_meta;
585 for(std::list<Piece>::const_iterator k = m_log.begin();
586 k != m_log.end(); k++)
588 const Piece &piece = *k;
589 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
590 i != piece.values.end(); i++){
591 const std::string &id = i->first;
592 const float &value = i->second;
593 std::map<std::string, Meta>::iterator j =
595 if(j == m_meta.end()){
596 m_meta[id] = Meta(value);
599 if(value < j->second.min)
600 j->second.min = value;
601 if(value > j->second.max)
602 j->second.max = value;
607 static const video::SColor usable_colors[] = {
608 video::SColor(255,255,100,100),
609 video::SColor(255,90,225,90),
610 video::SColor(255,100,100,255),
611 video::SColor(255,255,150,50),
612 video::SColor(255,220,220,100)
614 static const u32 usable_colors_count =
615 sizeof(usable_colors) / sizeof(*usable_colors);
616 u32 next_color_i = 0;
617 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
618 i != m_meta.end(); i++){
619 Meta &meta = i->second;
620 video::SColor color(255,200,200,200);
621 if(next_color_i < usable_colors_count)
622 color = usable_colors[next_color_i++];
627 s32 textx = x_left + m_log_max_size + 15;
628 s32 textx2 = textx + 200 - 15;
632 u32 num_graphs = m_meta.size();
633 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
635 video::SColor bgcolor(120,0,0,0);
636 driver->draw2DRectangle(bgcolor, rect, NULL);
640 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
641 i != m_meta.end(); i++){
642 const std::string &id = i->first;
643 const Meta &meta = i->second;
645 s32 y = y_bottom - meta_i * 50;
646 float show_min = meta.min;
647 float show_max = meta.max;
648 if(show_min >= -0.0001 && show_max >= -0.0001){
649 if(show_min <= show_max * 0.5)
654 snprintf(buf, 10, "%.3g", show_max);
655 font->draw(narrow_to_wide(buf).c_str(),
656 core::rect<s32>(textx, y - graphh,
657 textx2, y - graphh + texth),
659 snprintf(buf, 10, "%.3g", show_min);
660 font->draw(narrow_to_wide(buf).c_str(),
661 core::rect<s32>(textx, y - texth,
664 font->draw(narrow_to_wide(id).c_str(),
665 core::rect<s32>(textx, y - graphh/2 - texth/2,
666 textx2, y - graphh/2 + texth/2),
669 s32 graph1h = graphh;
670 bool relativegraph = (show_min != 0 && show_min != show_max);
671 float lastscaledvalue = 0.0;
672 bool lastscaledvalue_exists = false;
673 for(std::list<Piece>::const_iterator j = m_log.begin();
674 j != m_log.end(); j++)
676 const Piece &piece = *j;
678 bool value_exists = false;
679 Profiler::GraphValues::const_iterator k =
680 piece.values.find(id);
681 if(k != piece.values.end()){
687 lastscaledvalue_exists = false;
690 float scaledvalue = 1.0;
691 if(show_max != show_min)
692 scaledvalue = (value - show_min) / (show_max - show_min);
693 if(scaledvalue == 1.0 && value == 0){
695 lastscaledvalue_exists = false;
699 if(lastscaledvalue_exists){
700 s32 ivalue1 = lastscaledvalue * graph1h;
701 s32 ivalue2 = scaledvalue * graph1h;
702 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
703 v2s32(x, graph1y - ivalue2), meta.color);
705 lastscaledvalue = scaledvalue;
706 lastscaledvalue_exists = true;
708 s32 ivalue = scaledvalue * graph1h;
709 driver->draw2DLine(v2s32(x, graph1y),
710 v2s32(x, graph1y - ivalue), meta.color);
719 class NodeDugEvent: public MtEvent
725 NodeDugEvent(v3s16 p, MapNode n):
729 const char* getType() const
735 ISoundManager *m_sound;
736 INodeDefManager *m_ndef;
738 float m_player_step_timer;
740 SimpleSoundSpec m_player_step_sound;
741 SimpleSoundSpec m_player_leftpunch_sound;
742 SimpleSoundSpec m_player_rightpunch_sound;
744 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
747 m_player_step_timer(0)
751 void playPlayerStep()
753 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
754 m_player_step_timer = 0.03;
755 m_sound->playSound(m_player_step_sound, false);
759 static void viewBobbingStep(MtEvent *e, void *data)
761 SoundMaker *sm = (SoundMaker*)data;
762 sm->playPlayerStep();
765 static void playerRegainGround(MtEvent *e, void *data)
767 SoundMaker *sm = (SoundMaker*)data;
768 sm->playPlayerStep();
771 static void playerJump(MtEvent *e, void *data)
773 //SoundMaker *sm = (SoundMaker*)data;
776 static void cameraPunchLeft(MtEvent *e, void *data)
778 SoundMaker *sm = (SoundMaker*)data;
779 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
782 static void cameraPunchRight(MtEvent *e, void *data)
784 SoundMaker *sm = (SoundMaker*)data;
785 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
788 static void nodeDug(MtEvent *e, void *data)
790 SoundMaker *sm = (SoundMaker*)data;
791 NodeDugEvent *nde = (NodeDugEvent*)e;
792 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
795 void registerReceiver(MtEventManager *mgr)
797 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
798 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
799 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
800 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
801 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
802 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
805 void step(float dtime)
807 m_player_step_timer -= dtime;
811 // Locally stored sounds don't need to be preloaded because of this
812 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
814 std::set<std::string> m_fetched;
817 void fetchSounds(const std::string &name,
818 std::set<std::string> &dst_paths,
819 std::set<std::string> &dst_datas)
821 if(m_fetched.count(name))
823 m_fetched.insert(name);
824 std::string base = porting::path_share + DIR_DELIM + "testsounds";
825 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
826 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
827 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
828 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
829 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
830 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
831 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
832 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
833 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
834 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
835 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
839 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
842 bool *m_force_fog_off;
847 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
848 f32 *fog_range, Client *client):
850 m_force_fog_off(force_fog_off),
851 m_fog_range(fog_range),
854 ~GameGlobalShaderConstantSetter() {}
856 virtual void onSetConstants(video::IMaterialRendererServices *services,
863 video::SColor bgcolor = m_sky->getBgColor();
864 video::SColorf bgcolorf(bgcolor);
865 float bgcolorfa[4] = {
871 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
874 float fog_distance = *m_fog_range;
876 fog_distance = 10000*BS;
877 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
880 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
881 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
882 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
890 IrrlichtDevice *device,
893 std::string playername,
894 std::string password,
895 std::string address, // If "", local server is used
897 std::wstring &error_message,
898 std::string configpath,
899 ChatBackend &chat_backend,
900 const SubgameSpec &gamespec, // Used for local game,
901 bool simple_singleplayer_mode
904 video::IVideoDriver* driver = device->getVideoDriver();
905 scene::ISceneManager* smgr = device->getSceneManager();
907 // Calculate text height using the font
908 u32 text_height = font->getDimension(L"Random test string").Height;
910 v2u32 screensize(0,0);
911 v2u32 last_screensize(0,0);
912 screensize = driver->getScreenSize();
914 const s32 hotbar_itemcount = 8;
915 //const s32 hotbar_imagesize = 36;
916 //const s32 hotbar_imagesize = 64;
917 s32 hotbar_imagesize = 48;
920 Draw "Loading" screen
923 draw_load_screen(L"Loading...", driver, font);
925 // Create texture source
926 IWritableTextureSource *tsrc = createTextureSource(device);
928 // Create shader source
929 IWritableShaderSource *shsrc = createShaderSource(device);
931 // These will be filled by data received from the server
932 // Create item definition manager
933 IWritableItemDefManager *itemdef = createItemDefManager();
934 // Create node definition manager
935 IWritableNodeDefManager *nodedef = createNodeDefManager();
937 // Sound fetcher (useful when testing)
938 GameOnDemandSoundFetcher soundfetcher;
941 ISoundManager *sound = NULL;
942 bool sound_is_dummy = false;
944 if(g_settings->getBool("enable_sound")){
945 infostream<<"Attempting to use OpenAL audio"<<std::endl;
946 sound = createOpenALSoundManager(&soundfetcher);
948 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
950 infostream<<"Sound disabled."<<std::endl;
954 infostream<<"Using dummy audio."<<std::endl;
955 sound = &dummySoundManager;
956 sound_is_dummy = true;
960 EventManager eventmgr;
963 SoundMaker soundmaker(sound, nodedef);
964 soundmaker.registerReceiver(&eventmgr);
966 // Add chat log output for errors to be shown in chat
967 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
969 // Create UI for modifying quicktune values
970 QuicktuneShortcutter quicktune;
974 SharedPtr will delete it when it goes out of scope.
976 SharedPtr<Server> server;
978 draw_load_screen(L"Creating server...", driver, font);
979 infostream<<"Creating server"<<std::endl;
980 server = new Server(map_dir, configpath, gamespec,
981 simple_singleplayer_mode);
986 do{ // Client scope (breakable do-while(0))
992 draw_load_screen(L"Creating client...", driver, font);
993 infostream<<"Creating client"<<std::endl;
995 MapDrawControl draw_control;
997 Client client(device, playername.c_str(), password, draw_control,
998 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr);
1000 // Client acts as our GameDef
1001 IGameDef *gamedef = &client;
1003 draw_load_screen(L"Resolving address...", driver, font);
1004 Address connect_address(0,0,0,0, port);
1007 //connect_address.Resolve("localhost");
1008 connect_address.setAddress(127,0,0,1);
1010 connect_address.Resolve(address.c_str());
1012 catch(ResolveError &e)
1014 error_message = L"Couldn't resolve address";
1015 errorstream<<wide_to_narrow(error_message)<<std::endl;
1016 // Break out of client scope
1021 Attempt to connect to the server
1024 infostream<<"Connecting to server at ";
1025 connect_address.print(&infostream);
1026 infostream<<std::endl;
1027 client.connect(connect_address);
1030 Wait for server to accept connection
1032 bool could_connect = false;
1033 bool connect_aborted = false;
1035 float frametime = 0.033;
1036 float time_counter = 0.0;
1038 while(device->run())
1040 // Update client and server
1041 client.step(frametime);
1043 server->step(frametime);
1046 if(client.connectedAndInitialized()){
1047 could_connect = true;
1051 if(client.accessDenied()){
1052 error_message = L"Access denied. Reason: "
1053 +client.accessDeniedReason();
1054 errorstream<<wide_to_narrow(error_message)<<std::endl;
1057 if(input->wasKeyDown(EscapeKey)){
1058 connect_aborted = true;
1059 infostream<<"Connect aborted [Escape]"<<std::endl;
1064 std::wostringstream ss;
1065 ss<<L"Connecting to server... (press Escape to cancel)\n";
1066 std::wstring animation = L"/-\\|";
1067 ss<<animation[(int)(time_counter/0.2)%4];
1068 draw_load_screen(ss.str(), driver, font);
1071 sleep_ms(1000*frametime);
1072 time_counter += frametime;
1075 catch(con::PeerNotFoundException &e)
1079 Handle failure to connect
1082 if(error_message == L"" && !connect_aborted){
1083 error_message = L"Connection failed";
1084 errorstream<<wide_to_narrow(error_message)<<std::endl;
1086 // Break out of client scope
1091 Wait until content has been received
1093 bool got_content = false;
1094 bool content_aborted = false;
1096 float frametime = 0.033;
1097 float time_counter = 0.0;
1099 while(device->run())
1101 // Update client and server
1102 client.step(frametime);
1104 server->step(frametime);
1107 if(client.texturesReceived() &&
1108 client.itemdefReceived() &&
1109 client.nodedefReceived()){
1114 if(!client.connectedAndInitialized()){
1115 error_message = L"Client disconnected";
1116 errorstream<<wide_to_narrow(error_message)<<std::endl;
1119 if(input->wasKeyDown(EscapeKey)){
1120 content_aborted = true;
1121 infostream<<"Connect aborted [Escape]"<<std::endl;
1126 std::wostringstream ss;
1127 ss<<L"Waiting content... (press Escape to cancel)\n";
1129 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
1130 ss<<L" Item definitions\n";
1131 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
1132 ss<<L" Node definitions\n";
1133 ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1136 draw_load_screen(ss.str(), driver, font);
1139 sleep_ms(1000*frametime);
1140 time_counter += frametime;
1145 if(error_message == L"" && !content_aborted){
1146 error_message = L"Something failed";
1147 errorstream<<wide_to_narrow(error_message)<<std::endl;
1149 // Break out of client scope
1154 After all content has been received:
1155 Update cached textures, meshes and materials
1157 client.afterContentReceived();
1160 Create the camera node
1162 Camera camera(smgr, draw_control, gamedef);
1163 if (!camera.successfullyCreated(error_message))
1166 f32 camera_yaw = 0; // "right/left"
1167 f32 camera_pitch = 0; // "up/down"
1173 Clouds *clouds = NULL;
1174 if(g_settings->getBool("enable_clouds"))
1176 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1184 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1190 FarMesh *farmesh = NULL;
1191 if(g_settings->getBool("enable_farmesh"))
1193 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1197 A copy of the local inventory
1199 Inventory local_inventory(itemdef);
1202 Find out size of crack animation
1204 int crack_animation_length = 5;
1206 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1207 v2u32 size = t->getOriginalSize();
1208 crack_animation_length = size.Y / size.X;
1215 // First line of debug text
1216 gui::IGUIStaticText *guitext = guienv->addStaticText(
1218 core::rect<s32>(5, 5, 795, 5+text_height),
1220 // Second line of debug text
1221 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1223 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1225 // At the middle of the screen
1226 // Object infos are shown in this
1227 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1229 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1232 // Status text (displays info when showing and hiding GUI stuff, etc.)
1233 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1235 core::rect<s32>(0,0,0,0),
1237 guitext_status->setVisible(false);
1239 std::wstring statustext;
1240 float statustext_time = 0;
1243 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1245 core::rect<s32>(0,0,0,0),
1246 //false, false); // Disable word wrap as of now
1248 // Remove stale "recent" chat messages from previous connections
1249 chat_backend.clearRecentChat();
1250 // Chat backend and console
1251 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1253 // Profiler text (size is updated when text is updated)
1254 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1256 core::rect<s32>(0,0,0,0),
1258 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1259 guitext_profiler->setVisible(false);
1262 Some statistics are collected in these
1265 u32 beginscenetime = 0;
1267 u32 endscenetime = 0;
1269 float recent_turn_speed = 0.0;
1271 ProfilerGraph graph;
1272 // Initially clear the profiler
1273 Profiler::GraphValues dummyvalues;
1274 g_profiler->graphGet(dummyvalues);
1276 float nodig_delay_timer = 0.0;
1277 float dig_time = 0.0;
1279 PointedThing pointed_old;
1280 bool digging = false;
1281 bool ldown_for_dig = false;
1283 float damage_flash_timer = 0;
1284 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1286 const float object_hit_delay = 0.2;
1287 float object_hit_delay_timer = 0.0;
1288 float time_from_last_punch = 10;
1290 float update_draw_list_timer = 0.0;
1291 v3f update_draw_list_last_cam_dir;
1293 bool invert_mouse = g_settings->getBool("invert_mouse");
1295 bool respawn_menu_active = false;
1296 bool update_wielded_item_trigger = false;
1298 bool show_hud = true;
1299 bool show_chat = true;
1300 bool force_fog_off = false;
1301 f32 fog_range = 100*BS;
1302 bool disable_camera_update = false;
1303 bool show_debug = g_settings->getBool("show_debug");
1304 bool show_profiler_graph = false;
1305 u32 show_profiler = 0;
1306 u32 show_profiler_max = 3; // Number of pages
1308 float time_of_day = 0;
1309 float time_of_day_smooth = 0;
1314 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1315 sky, &force_fog_off, &fog_range, &client));
1321 bool first_loop_after_window_activation = true;
1323 // TODO: Convert the static interval timers to these
1324 // Interval limiter for profiler
1325 IntervalLimiter m_profiler_interval;
1327 // Time is in milliseconds
1328 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1329 // NOTE: So we have to use getTime() and call run()s between them
1330 u32 lasttime = device->getTimer()->getTime();
1334 if(device->run() == false || kill == true)
1337 // Time of frame without fps limit
1341 // not using getRealTime is necessary for wine
1342 u32 time = device->getTimer()->getTime();
1344 busytime_u32 = time - lasttime;
1347 busytime = busytime_u32 / 1000.0;
1350 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1352 // Necessary for device->getTimer()->getTime()
1360 float fps_max = g_settings->getFloat("fps_max");
1361 u32 frametime_min = 1000./fps_max;
1363 if(busytime_u32 < frametime_min)
1365 u32 sleeptime = frametime_min - busytime_u32;
1366 device->sleep(sleeptime);
1367 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1371 // Necessary for device->getTimer()->getTime()
1375 Time difference calculation
1377 f32 dtime; // in seconds
1379 u32 time = device->getTimer()->getTime();
1381 dtime = (time - lasttime) / 1000.0;
1386 g_profiler->graphAdd("mainloop_dtime", dtime);
1390 if(nodig_delay_timer >= 0)
1391 nodig_delay_timer -= dtime;
1392 if(object_hit_delay_timer >= 0)
1393 object_hit_delay_timer -= dtime;
1394 time_from_last_punch += dtime;
1396 g_profiler->add("Elapsed time", dtime);
1397 g_profiler->avg("FPS", 1./dtime);
1400 Time average and jitter calculation
1403 static f32 dtime_avg1 = 0.0;
1404 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1405 f32 dtime_jitter1 = dtime - dtime_avg1;
1407 static f32 dtime_jitter1_max_sample = 0.0;
1408 static f32 dtime_jitter1_max_fraction = 0.0;
1410 static f32 jitter1_max = 0.0;
1411 static f32 counter = 0.0;
1412 if(dtime_jitter1 > jitter1_max)
1413 jitter1_max = dtime_jitter1;
1418 dtime_jitter1_max_sample = jitter1_max;
1419 dtime_jitter1_max_fraction
1420 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1426 Busytime average and jitter calculation
1429 static f32 busytime_avg1 = 0.0;
1430 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1431 f32 busytime_jitter1 = busytime - busytime_avg1;
1433 static f32 busytime_jitter1_max_sample = 0.0;
1434 static f32 busytime_jitter1_min_sample = 0.0;
1436 static f32 jitter1_max = 0.0;
1437 static f32 jitter1_min = 0.0;
1438 static f32 counter = 0.0;
1439 if(busytime_jitter1 > jitter1_max)
1440 jitter1_max = busytime_jitter1;
1441 if(busytime_jitter1 < jitter1_min)
1442 jitter1_min = busytime_jitter1;
1446 busytime_jitter1_max_sample = jitter1_max;
1447 busytime_jitter1_min_sample = jitter1_min;
1454 Handle miscellaneous stuff
1457 if(client.accessDenied())
1459 error_message = L"Access denied. Reason: "
1460 +client.accessDeniedReason();
1461 errorstream<<wide_to_narrow(error_message)<<std::endl;
1465 if(g_gamecallback->disconnect_requested)
1467 g_gamecallback->disconnect_requested = false;
1471 if(g_gamecallback->changepassword_requested)
1473 (new GUIPasswordChange(guienv, guiroot, -1,
1474 &g_menumgr, &client))->drop();
1475 g_gamecallback->changepassword_requested = false;
1478 /* Process TextureSource's queue */
1479 tsrc->processQueue();
1481 /* Process ItemDefManager's queue */
1482 itemdef->processQueue(gamedef);
1485 Process ShaderSource's queue
1487 shsrc->processQueue();
1492 last_screensize = screensize;
1493 screensize = driver->getScreenSize();
1494 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1495 //bool screensize_changed = screensize != last_screensize;
1498 if(screensize.Y <= 800)
1499 hotbar_imagesize = 32;
1500 else if(screensize.Y <= 1280)
1501 hotbar_imagesize = 48;
1503 hotbar_imagesize = 64;
1505 // Hilight boxes collected during the loop and displayed
1506 std::vector<aabb3f> hilightboxes;
1509 std::wstring infotext;
1512 Debug info for client
1515 static float counter = 0.0;
1520 client.printDebugInfo(infostream);
1527 float profiler_print_interval =
1528 g_settings->getFloat("profiler_print_interval");
1529 bool print_to_log = true;
1530 if(profiler_print_interval == 0){
1531 print_to_log = false;
1532 profiler_print_interval = 5;
1534 if(m_profiler_interval.step(dtime, profiler_print_interval))
1537 infostream<<"Profiler:"<<std::endl;
1538 g_profiler->print(infostream);
1541 update_profiler_gui(guitext_profiler, font, text_height,
1542 show_profiler, show_profiler_max);
1544 g_profiler->clear();
1548 Direct handling of user input
1551 // Reset input if window not active or some menu is active
1552 if(device->isWindowActive() == false
1553 || noMenuActive() == false
1554 || guienv->hasFocus(gui_chat_console))
1559 // Input handler step() (used by the random input generator)
1563 Launch menus and trigger stuff according to keys
1565 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1567 // drop selected item
1568 IDropAction *a = new IDropAction();
1570 a->from_inv.setCurrentPlayer();
1571 a->from_list = "main";
1572 a->from_i = client.getPlayerItem();
1573 client.inventoryAction(a);
1575 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1577 infostream<<"the_game: "
1578 <<"Launching inventory"<<std::endl;
1580 GUIFormSpecMenu *menu =
1581 new GUIFormSpecMenu(device, guiroot, -1,
1585 InventoryLocation inventoryloc;
1586 inventoryloc.setCurrentPlayer();
1588 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1590 menu->setFormSpec(src->getForm(), inventoryloc);
1591 menu->setFormSource(src);
1592 menu->setTextDest(new TextDestPlayerInventory(&client));
1595 else if(input->wasKeyDown(EscapeKey))
1597 infostream<<"the_game: "
1598 <<"Launching pause menu"<<std::endl;
1599 // It will delete itself by itself
1600 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1601 &g_menumgr, simple_singleplayer_mode))->drop();
1603 // Move mouse cursor on top of the disconnect button
1604 if(simple_singleplayer_mode)
1605 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1607 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1609 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1611 TextDest *dest = new TextDestChat(&client);
1613 (new GUITextInputMenu(guienv, guiroot, -1,
1617 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1619 TextDest *dest = new TextDestChat(&client);
1621 (new GUITextInputMenu(guienv, guiroot, -1,
1625 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1627 if (!gui_chat_console->isOpenInhibited())
1629 // Open up to over half of the screen
1630 gui_chat_console->openConsole(0.6);
1631 guienv->setFocus(gui_chat_console);
1634 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1636 if(g_settings->getBool("free_move"))
1638 g_settings->set("free_move","false");
1639 statustext = L"free_move disabled";
1640 statustext_time = 0;
1644 g_settings->set("free_move","true");
1645 statustext = L"free_move enabled";
1646 statustext_time = 0;
1647 if(!client.checkPrivilege("fly"))
1648 statustext += L" (note: no 'fly' privilege)";
1651 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1653 if(g_settings->getBool("fast_move"))
1655 g_settings->set("fast_move","false");
1656 statustext = L"fast_move disabled";
1657 statustext_time = 0;
1661 g_settings->set("fast_move","true");
1662 statustext = L"fast_move enabled";
1663 statustext_time = 0;
1664 if(!client.checkPrivilege("fast"))
1665 statustext += L" (note: no 'fast' privilege)";
1668 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1670 irr::video::IImage* const image = driver->createScreenShot();
1672 irr::c8 filename[256];
1673 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1674 g_settings->get("screenshot_path").c_str(),
1675 device->getTimer()->getRealTime());
1676 if (driver->writeImageToFile(image, filename)) {
1677 std::wstringstream sstr;
1678 sstr<<"Saved screenshot to '"<<filename<<"'";
1679 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1680 statustext = sstr.str();
1681 statustext_time = 0;
1683 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1688 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1690 show_hud = !show_hud;
1692 statustext = L"HUD shown";
1694 statustext = L"HUD hidden";
1695 statustext_time = 0;
1697 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1699 show_chat = !show_chat;
1701 statustext = L"Chat shown";
1703 statustext = L"Chat hidden";
1704 statustext_time = 0;
1706 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1708 force_fog_off = !force_fog_off;
1710 statustext = L"Fog disabled";
1712 statustext = L"Fog enabled";
1713 statustext_time = 0;
1715 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1717 disable_camera_update = !disable_camera_update;
1718 if(disable_camera_update)
1719 statustext = L"Camera update disabled";
1721 statustext = L"Camera update enabled";
1722 statustext_time = 0;
1724 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1726 // Initial / 3x toggle: Chat only
1727 // 1x toggle: Debug text with chat
1728 // 2x toggle: Debug text with profiler graph
1732 show_profiler_graph = false;
1733 statustext = L"Debug info shown";
1734 statustext_time = 0;
1736 else if(show_profiler_graph)
1739 show_profiler_graph = false;
1740 statustext = L"Debug info and profiler graph hidden";
1741 statustext_time = 0;
1745 show_profiler_graph = true;
1746 statustext = L"Profiler graph shown";
1747 statustext_time = 0;
1750 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1752 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1754 // FIXME: This updates the profiler with incomplete values
1755 update_profiler_gui(guitext_profiler, font, text_height,
1756 show_profiler, show_profiler_max);
1758 if(show_profiler != 0)
1760 std::wstringstream sstr;
1761 sstr<<"Profiler shown (page "<<show_profiler
1762 <<" of "<<show_profiler_max<<")";
1763 statustext = sstr.str();
1764 statustext_time = 0;
1768 statustext = L"Profiler hidden";
1769 statustext_time = 0;
1772 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1774 s16 range = g_settings->getS16("viewing_range_nodes_min");
1775 s16 range_new = range + 10;
1776 g_settings->set("viewing_range_nodes_min", itos(range_new));
1777 statustext = narrow_to_wide(
1778 "Minimum viewing range changed to "
1780 statustext_time = 0;
1782 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1784 s16 range = g_settings->getS16("viewing_range_nodes_min");
1785 s16 range_new = range - 10;
1788 g_settings->set("viewing_range_nodes_min",
1790 statustext = narrow_to_wide(
1791 "Minimum viewing range changed to "
1793 statustext_time = 0;
1796 // Handle QuicktuneShortcutter
1797 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1799 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1801 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1803 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1806 std::string msg = quicktune.getMessage();
1808 statustext = narrow_to_wide(msg);
1809 statustext_time = 0;
1813 // Item selection with mouse wheel
1814 u16 new_playeritem = client.getPlayerItem();
1816 s32 wheel = input->getMouseWheel();
1817 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1818 hotbar_itemcount-1);
1822 if(new_playeritem < max_item)
1829 if(new_playeritem > 0)
1832 new_playeritem = max_item;
1837 for(u16 i=0; i<10; i++)
1839 const KeyPress *kp = NumberKey + (i + 1) % 10;
1840 if(input->wasKeyDown(*kp))
1842 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1846 infostream<<"Selected item: "
1847 <<new_playeritem<<std::endl;
1852 // Viewing range selection
1853 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1855 draw_control.range_all = !draw_control.range_all;
1856 if(draw_control.range_all)
1858 infostream<<"Enabled full viewing range"<<std::endl;
1859 statustext = L"Enabled full viewing range";
1860 statustext_time = 0;
1864 infostream<<"Disabled full viewing range"<<std::endl;
1865 statustext = L"Disabled full viewing range";
1866 statustext_time = 0;
1870 // Print debug stacks
1871 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1873 dstream<<"-----------------------------------------"
1875 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1876 dstream<<"-----------------------------------------"
1878 debug_stacks_print();
1882 Mouse and camera control
1883 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1886 float turn_amount = 0;
1887 if((device->isWindowActive() && noMenuActive()) || random_input)
1891 // Mac OSX gets upset if this is set every frame
1892 if(device->getCursorControl()->isVisible())
1893 device->getCursorControl()->setVisible(false);
1896 if(first_loop_after_window_activation){
1897 //infostream<<"window active, first loop"<<std::endl;
1898 first_loop_after_window_activation = false;
1901 s32 dx = input->getMousePos().X - displaycenter.X;
1902 s32 dy = input->getMousePos().Y - displaycenter.Y;
1905 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1907 /*const float keyspeed = 500;
1908 if(input->isKeyDown(irr::KEY_UP))
1909 dy -= dtime * keyspeed;
1910 if(input->isKeyDown(irr::KEY_DOWN))
1911 dy += dtime * keyspeed;
1912 if(input->isKeyDown(irr::KEY_LEFT))
1913 dx -= dtime * keyspeed;
1914 if(input->isKeyDown(irr::KEY_RIGHT))
1915 dx += dtime * keyspeed;*/
1919 camera_pitch += dy*d;
1920 if(camera_pitch < -89.5) camera_pitch = -89.5;
1921 if(camera_pitch > 89.5) camera_pitch = 89.5;
1923 turn_amount = v2f(dx, dy).getLength() * d;
1925 input->setMousePos(displaycenter.X, displaycenter.Y);
1928 // Mac OSX gets upset if this is set every frame
1929 if(device->getCursorControl()->isVisible() == false)
1930 device->getCursorControl()->setVisible(true);
1932 //infostream<<"window inactive"<<std::endl;
1933 first_loop_after_window_activation = true;
1935 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1936 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1939 Player speed control
1953 PlayerControl control(
1954 input->isKeyDown(getKeySetting("keymap_forward")),
1955 input->isKeyDown(getKeySetting("keymap_backward")),
1956 input->isKeyDown(getKeySetting("keymap_left")),
1957 input->isKeyDown(getKeySetting("keymap_right")),
1958 input->isKeyDown(getKeySetting("keymap_jump")),
1959 input->isKeyDown(getKeySetting("keymap_special1")),
1960 input->isKeyDown(getKeySetting("keymap_sneak")),
1961 input->getLeftState(),
1962 input->getRightState(),
1966 client.setPlayerControl(control);
1968 1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
1969 2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
1970 4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
1971 8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
1972 16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
1973 32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
1974 64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
1975 128*(int)input->getLeftState()+
1976 256*(int)input->getRightState();
1977 LocalPlayer* player = client.getEnv().getLocalPlayer();
1978 player->keyPressed=keyPressed;
1987 //TimeTaker timer("server->step(dtime)");
1988 server->step(dtime);
1996 //TimeTaker timer("client.step(dtime)");
1998 //client.step(dtime_avg1);
2002 // Read client events
2005 ClientEvent event = client.getClientEvent();
2006 if(event.type == CE_NONE)
2010 else if(event.type == CE_PLAYER_DAMAGE)
2012 //u16 damage = event.player_damage.amount;
2013 //infostream<<"Player damage: "<<damage<<std::endl;
2014 damage_flash_timer = 0.05;
2015 if(event.player_damage.amount >= 2){
2016 damage_flash_timer += 0.05 * event.player_damage.amount;
2019 else if(event.type == CE_PLAYER_FORCE_MOVE)
2021 camera_yaw = event.player_force_move.yaw;
2022 camera_pitch = event.player_force_move.pitch;
2024 else if(event.type == CE_DEATHSCREEN)
2026 if(respawn_menu_active)
2029 /*bool set_camera_point_target =
2030 event.deathscreen.set_camera_point_target;
2031 v3f camera_point_target;
2032 camera_point_target.X = event.deathscreen.camera_point_target_x;
2033 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2034 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2035 MainRespawnInitiator *respawner =
2036 new MainRespawnInitiator(
2037 &respawn_menu_active, &client);
2038 GUIDeathScreen *menu =
2039 new GUIDeathScreen(guienv, guiroot, -1,
2040 &g_menumgr, respawner);
2043 chat_backend.addMessage(L"", L"You died.");
2045 /* Handle visualization */
2047 damage_flash_timer = 0;
2049 /*LocalPlayer* player = client.getLocalPlayer();
2050 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2051 camera.update(player, busytime, screensize);*/
2053 else if(event.type == CE_TEXTURES_UPDATED)
2055 update_wielded_item_trigger = true;
2060 //TimeTaker //timer2("//timer2");
2063 For interaction purposes, get info about the held item
2065 - Is it a usable item?
2066 - Can it point to liquids?
2068 ItemStack playeritem;
2069 bool playeritem_usable = false;
2070 bool playeritem_liquids_pointable = false;
2072 InventoryList *mlist = local_inventory.getList("main");
2075 playeritem = mlist->getItem(client.getPlayerItem());
2076 playeritem_usable = playeritem.getDefinition(itemdef).usable;
2077 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
2080 ToolCapabilities playeritem_toolcap =
2081 playeritem.getToolCapabilities(itemdef);
2087 LocalPlayer* player = client.getEnv().getLocalPlayer();
2088 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2089 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2090 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2091 camera.update(player, busytime, screensize, tool_reload_ratio);
2094 v3f player_position = player->getPosition();
2095 v3f camera_position = camera.getPosition();
2096 v3f camera_direction = camera.getDirection();
2097 f32 camera_fov = camera.getFovMax();
2099 if(!disable_camera_update){
2100 client.getEnv().getClientMap().updateCamera(camera_position,
2101 camera_direction, camera_fov);
2104 // Update sound listener
2105 sound->updateListener(camera.getCameraNode()->getPosition(),
2106 v3f(0,0,0), // velocity
2107 camera.getDirection(),
2108 camera.getCameraNode()->getUpVector());
2109 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2115 soundmaker.step(dtime);
2117 ClientMap &map = client.getEnv().getClientMap();
2118 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2119 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2123 Calculate what block is the crosshair pointing to
2126 //u32 t1 = device->getTimer()->getRealTime();
2128 f32 d = 4; // max. distance
2129 core::line3d<f32> shootline(camera_position,
2130 camera_position + camera_direction * BS * (d+1));
2132 ClientActiveObject *selected_object = NULL;
2134 PointedThing pointed = getPointedThing(
2136 &client, player_position, camera_direction,
2137 camera_position, shootline, d,
2138 playeritem_liquids_pointable, !ldown_for_dig,
2143 if(pointed != pointed_old)
2145 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2146 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2151 - releasing left mouse button
2152 - pointing away from node
2156 if(input->getLeftReleased())
2158 infostream<<"Left button released"
2159 <<" (stopped digging)"<<std::endl;
2162 else if(pointed != pointed_old)
2164 if (pointed.type == POINTEDTHING_NODE
2165 && pointed_old.type == POINTEDTHING_NODE
2166 && pointed.node_undersurface == pointed_old.node_undersurface)
2168 // Still pointing to the same node,
2169 // but a different face. Don't reset.
2173 infostream<<"Pointing away from node"
2174 <<" (stopped digging)"<<std::endl;
2180 client.interact(1, pointed_old);
2181 client.setCrack(-1, v3s16(0,0,0));
2185 if(!digging && ldown_for_dig && !input->getLeftState())
2187 ldown_for_dig = false;
2190 bool left_punch = false;
2191 soundmaker.m_player_leftpunch_sound.name = "";
2193 if(playeritem_usable && input->getLeftState())
2195 if(input->getLeftClicked())
2196 client.interact(4, pointed);
2198 else if(pointed.type == POINTEDTHING_NODE)
2200 v3s16 nodepos = pointed.node_undersurface;
2201 v3s16 neighbourpos = pointed.node_abovesurface;
2204 Check information text of node
2207 ClientMap &map = client.getEnv().getClientMap();
2208 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2210 infotext = narrow_to_wide(meta->getString("infotext"));
2212 MapNode n = map.getNode(nodepos);
2213 if(nodedef->get(n).tiledef[0].name == "unknown_block.png"){
2214 infotext = L"Unknown node: ";
2215 infotext += narrow_to_wide(nodedef->get(n).name);
2219 // We can't actually know, but assume the sound of right-clicking
2220 // to be the sound of placing a node
2221 soundmaker.m_player_rightpunch_sound.gain = 0.5;
2222 soundmaker.m_player_rightpunch_sound.name = "default_place_node";
2228 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2232 infostream<<"Started digging"<<std::endl;
2233 client.interact(0, pointed);
2235 ldown_for_dig = true;
2237 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2239 // NOTE: Similar piece of code exists on the server side for
2241 // Get digging parameters
2242 DigParams params = getDigParams(nodedef->get(n).groups,
2243 &playeritem_toolcap);
2244 // If can't dig, try hand
2245 if(!params.diggable){
2246 const ItemDefinition &hand = itemdef->get("");
2247 const ToolCapabilities *tp = hand.tool_capabilities;
2249 params = getDigParams(nodedef->get(n).groups, tp);
2252 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2253 if(sound_dig.exists()){
2254 if(sound_dig.name == "__group"){
2255 if(params.main_group != ""){
2256 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2257 soundmaker.m_player_leftpunch_sound.name =
2258 std::string("default_dig_") +
2262 soundmaker.m_player_leftpunch_sound = sound_dig;
2266 float dig_time_complete = 0.0;
2268 if(params.diggable == false)
2270 // I guess nobody will wait for this long
2271 dig_time_complete = 10000000.0;
2275 dig_time_complete = params.time;
2278 if(dig_time_complete >= 0.001)
2280 dig_index = (u16)((float)crack_animation_length
2281 * dig_time/dig_time_complete);
2283 // This is for torches
2286 dig_index = crack_animation_length;
2289 // Don't show cracks if not diggable
2290 if(dig_time_complete >= 100000.0)
2293 else if(dig_index < crack_animation_length)
2295 //TimeTaker timer("client.setTempMod");
2296 //infostream<<"dig_index="<<dig_index<<std::endl;
2297 client.setCrack(dig_index, nodepos);
2301 infostream<<"Digging completed"<<std::endl;
2302 client.interact(2, pointed);
2303 client.setCrack(-1, v3s16(0,0,0));
2304 MapNode wasnode = map.getNode(nodepos);
2305 client.removeNode(nodepos);
2310 nodig_delay_timer = dig_time_complete
2311 / (float)crack_animation_length;
2313 // We don't want a corresponding delay to
2314 // very time consuming nodes
2315 if(nodig_delay_timer > 0.3)
2316 nodig_delay_timer = 0.3;
2317 // We want a slight delay to very little
2318 // time consuming nodes
2319 float mindelay = 0.15;
2320 if(nodig_delay_timer < mindelay)
2321 nodig_delay_timer = mindelay;
2323 // Send event to trigger sound
2324 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2325 gamedef->event()->put(e);
2330 camera.setDigging(0); // left click animation
2333 if(input->getRightClicked())
2335 infostream<<"Ground right-clicked"<<std::endl;
2337 // Sign special case, at least until formspec is properly implemented.
2339 if(meta && meta->getString("formspec") == "hack:sign_text_input" && !random_input)
2341 infostream<<"Launching metadata text input"<<std::endl;
2343 // Get a new text for it
2345 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2347 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2349 (new GUITextInputMenu(guienv, guiroot, -1,
2353 // If metadata provides an inventory view, activate it
2354 else if(meta && meta->getString("formspec") != "" && !random_input)
2356 infostream<<"Launching custom inventory view"<<std::endl;
2358 InventoryLocation inventoryloc;
2359 inventoryloc.setNodeMeta(nodepos);
2363 GUIFormSpecMenu *menu =
2364 new GUIFormSpecMenu(device, guiroot, -1,
2367 menu->setFormSpec(meta->getString("formspec"),
2369 menu->setFormSource(new NodeMetadataFormSource(
2370 &client.getEnv().getClientMap(), nodepos));
2371 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2374 // Otherwise report right click to server
2378 client.interact(3, pointed);
2379 camera.setDigging(1); // right click animation
2381 // If the wielded item has node placement prediction,
2383 const ItemDefinition &def =
2384 playeritem.getDefinition(itemdef);
2385 if(def.node_placement_prediction != "")
2387 verbosestream<<"Node placement prediction for "
2388 <<playeritem.name<<" is "
2389 <<def.node_placement_prediction<<std::endl;
2390 v3s16 p = neighbourpos;
2391 // Place inside node itself if buildable_to
2393 MapNode n_under = map.getNode(nodepos);
2394 if(nodedef->get(n_under).buildable_to)
2396 }catch(InvalidPositionException &e){}
2397 // Find id of predicted node
2400 nodedef->getId(def.node_placement_prediction, id);
2402 errorstream<<"Node placement prediction failed for "
2403 <<playeritem.name<<" (places "
2404 <<def.node_placement_prediction
2405 <<") - Name not known"<<std::endl;
2410 // This triggers the required mesh update too
2411 client.addNode(p, n);
2412 }catch(InvalidPositionException &e){
2413 errorstream<<"Node placement prediction failed for "
2414 <<playeritem.name<<" (places "
2415 <<def.node_placement_prediction
2416 <<") - Position not loaded"<<std::endl;
2422 else if(pointed.type == POINTEDTHING_OBJECT)
2424 infotext = narrow_to_wide(selected_object->infoText());
2426 if(infotext == L"" && show_debug){
2427 infotext = narrow_to_wide(selected_object->debugInfoText());
2430 //if(input->getLeftClicked())
2431 if(input->getLeftState())
2433 bool do_punch = false;
2434 bool do_punch_damage = false;
2435 if(object_hit_delay_timer <= 0.0){
2437 do_punch_damage = true;
2438 object_hit_delay_timer = object_hit_delay;
2440 if(input->getLeftClicked()){
2444 infostream<<"Left-clicked object"<<std::endl;
2447 if(do_punch_damage){
2448 // Report direct punch
2449 v3f objpos = selected_object->getPosition();
2450 v3f dir = (objpos - player_position).normalize();
2452 bool disable_send = selected_object->directReportPunch(
2453 dir, &playeritem, time_from_last_punch);
2454 time_from_last_punch = 0;
2456 client.interact(0, pointed);
2459 else if(input->getRightClicked())
2461 infostream<<"Right-clicked object"<<std::endl;
2462 client.interact(3, pointed); // place
2465 else if(input->getLeftState())
2467 // When button is held down in air, show continuous animation
2471 pointed_old = pointed;
2473 if(left_punch || input->getLeftClicked())
2475 camera.setDigging(0); // left click animation
2478 input->resetLeftClicked();
2479 input->resetRightClicked();
2481 input->resetLeftReleased();
2482 input->resetRightReleased();
2485 Calculate stuff for drawing
2494 fog_range = BS*farmesh_range;
2498 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2500 if(draw_control.range_all)
2501 fog_range = 100000*BS;
2505 Calculate general brightness
2507 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2508 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2509 float direct_brightness = 0;
2510 bool sunlight_seen = false;
2511 if(g_settings->getBool("free_move")){
2512 direct_brightness = time_brightness;
2513 sunlight_seen = true;
2515 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2516 float old_brightness = sky->getBrightness();
2517 direct_brightness = (float)client.getEnv().getClientMap()
2518 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2519 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2523 time_of_day = client.getEnv().getTimeOfDayF();
2525 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2526 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2527 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2528 time_of_day_smooth = time_of_day;
2530 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2531 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2532 + (time_of_day+1.0) * todsm;
2534 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2535 + time_of_day * todsm;
2537 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2540 float brightness = sky->getBrightness();
2541 video::SColor bgcolor = sky->getBgColor();
2542 video::SColor skycolor = sky->getSkyColor();
2548 if(sky->getCloudsVisible()){
2549 clouds->setVisible(true);
2550 clouds->step(dtime);
2551 clouds->update(v2f(player_position.X, player_position.Z),
2552 sky->getCloudColor());
2554 clouds->setVisible(false);
2563 farmesh_range = draw_control.wanted_range * 10;
2564 if(draw_control.range_all && farmesh_range < 500)
2565 farmesh_range = 500;
2566 if(farmesh_range > 1000)
2567 farmesh_range = 1000;
2569 farmesh->step(dtime);
2570 farmesh->update(v2f(player_position.X, player_position.Z),
2571 brightness, farmesh_range);
2578 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2582 video::EFT_FOG_LINEAR,
2594 video::EFT_FOG_LINEAR,
2604 Update gui stuff (0ms)
2607 //TimeTaker guiupdatetimer("Gui updating");
2609 const char program_name_and_version[] =
2610 "Minetest-c55 " VERSION_STRING;
2614 static float drawtime_avg = 0;
2615 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2616 /*static float beginscenetime_avg = 0;
2617 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2618 static float scenetime_avg = 0;
2619 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2620 static float endscenetime_avg = 0;
2621 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2624 snprintf(temptext, 300, "%s ("
2627 " drawtime=%.0f, dtime_jitter = % .1f %%"
2628 ", v_range = %.1f, RTT = %.3f",
2629 program_name_and_version,
2630 draw_control.range_all,
2632 dtime_jitter1_max_fraction * 100.0,
2633 draw_control.wanted_range,
2637 guitext->setText(narrow_to_wide(temptext).c_str());
2638 guitext->setVisible(true);
2640 else if(show_hud || show_chat)
2642 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2643 guitext->setVisible(true);
2647 guitext->setVisible(false);
2653 snprintf(temptext, 300,
2654 "(% .1f, % .1f, % .1f)"
2655 " (yaw = %.1f) (seed = %lli)",
2656 player_position.X/BS,
2657 player_position.Y/BS,
2658 player_position.Z/BS,
2659 wrapDegrees_0_360(camera_yaw),
2660 client.getMapSeed());
2662 guitext2->setText(narrow_to_wide(temptext).c_str());
2663 guitext2->setVisible(true);
2667 guitext2->setVisible(false);
2671 guitext_info->setText(infotext.c_str());
2672 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2676 float statustext_time_max = 1.5;
2677 if(!statustext.empty())
2679 statustext_time += dtime;
2680 if(statustext_time >= statustext_time_max)
2683 statustext_time = 0;
2686 guitext_status->setText(statustext.c_str());
2687 guitext_status->setVisible(!statustext.empty());
2689 if(!statustext.empty())
2691 s32 status_y = screensize.Y - 130;
2692 core::rect<s32> rect(
2694 status_y - guitext_status->getTextHeight(),
2698 guitext_status->setRelativePosition(rect);
2701 video::SColor initial_color(255,0,0,0);
2702 if(guienv->getSkin())
2703 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2704 video::SColor final_color = initial_color;
2705 final_color.setAlpha(0);
2706 video::SColor fade_color =
2707 initial_color.getInterpolated_quadratic(
2710 pow(statustext_time / (float)statustext_time_max, 2.0f));
2711 guitext_status->setOverrideColor(fade_color);
2712 guitext_status->enableOverrideColor(true);
2717 Get chat messages from client
2720 // Get new messages from error log buffer
2721 while(!chat_log_error_buf.empty())
2723 chat_backend.addMessage(L"", narrow_to_wide(
2724 chat_log_error_buf.get()));
2726 // Get new messages from client
2727 std::wstring message;
2728 while(client.getChatMessage(message))
2730 chat_backend.addUnparsedMessage(message);
2732 // Remove old messages
2733 chat_backend.step(dtime);
2735 // Display all messages in a static text element
2736 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2737 std::wstring recent_chat = chat_backend.getRecentChat();
2738 guitext_chat->setText(recent_chat.c_str());
2740 // Update gui element size and position
2741 s32 chat_y = 5+(text_height+5);
2743 chat_y += (text_height+5);
2744 core::rect<s32> rect(
2748 chat_y + guitext_chat->getTextHeight()
2750 guitext_chat->setRelativePosition(rect);
2752 // Don't show chat if disabled or empty or profiler is enabled
2753 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2761 if(client.getPlayerItem() != new_playeritem)
2763 client.selectPlayerItem(new_playeritem);
2765 if(client.getLocalInventoryUpdated())
2767 //infostream<<"Updating local inventory"<<std::endl;
2768 client.getLocalInventory(local_inventory);
2770 update_wielded_item_trigger = true;
2772 if(update_wielded_item_trigger)
2774 update_wielded_item_trigger = false;
2775 // Update wielded tool
2776 InventoryList *mlist = local_inventory.getList("main");
2779 item = mlist->getItem(client.getPlayerItem());
2784 Update block draw list every 200ms or when camera direction has
2787 update_draw_list_timer += dtime;
2788 if(update_draw_list_timer >= 0.2 ||
2789 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
2790 update_draw_list_timer = 0;
2791 client.getEnv().getClientMap().updateDrawList(driver);
2792 update_draw_list_last_cam_dir = camera_direction;
2799 TimeTaker tt_draw("mainloop: draw");
2803 TimeTaker timer("beginScene");
2804 //driver->beginScene(false, true, bgcolor);
2805 //driver->beginScene(true, true, bgcolor);
2806 driver->beginScene(true, true, skycolor);
2807 beginscenetime = timer.stop(true);
2812 //infostream<<"smgr->drawAll()"<<std::endl;
2814 TimeTaker timer("smgr");
2817 if(g_settings->getBool("anaglyph"))
2819 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
2820 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
2822 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
2824 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
2825 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
2826 camera.getCameraNode()->getAbsolutePosition() ;
2829 irr::core::vector3df leftEye;
2830 irr::core::matrix4 leftMove;
2832 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
2833 leftEye=(startMatrix*leftMove).getTranslation();
2835 //clear the depth buffer, and color
2836 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
2838 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
2839 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
2840 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
2841 irr::scene::ESNRP_SOLID +
2842 irr::scene::ESNRP_TRANSPARENT +
2843 irr::scene::ESNRP_TRANSPARENT_EFFECT +
2844 irr::scene::ESNRP_SHADOW;
2846 camera.getCameraNode()->setPosition( leftEye );
2847 camera.getCameraNode()->setTarget( focusPoint );
2849 smgr->drawAll(); // 'smgr->drawAll();' may go here
2853 irr::core::vector3df rightEye;
2854 irr::core::matrix4 rightMove;
2856 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
2857 rightEye=(startMatrix*rightMove).getTranslation();
2859 //clear the depth buffer
2860 driver->clearZBuffer();
2862 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
2863 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
2864 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
2865 irr::scene::ESNRP_SOLID +
2866 irr::scene::ESNRP_TRANSPARENT +
2867 irr::scene::ESNRP_TRANSPARENT_EFFECT +
2868 irr::scene::ESNRP_SHADOW;
2870 camera.getCameraNode()->setPosition( rightEye );
2871 camera.getCameraNode()->setTarget( focusPoint );
2873 smgr->drawAll(); // 'smgr->drawAll();' may go here
2876 //driver->endScene();
2878 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
2879 driver->getOverrideMaterial().EnableFlags=0;
2880 driver->getOverrideMaterial().EnablePasses=0;
2882 camera.getCameraNode()->setPosition( oldPosition );
2883 camera.getCameraNode()->setTarget( oldTarget );
2886 scenetime = timer.stop(true);
2890 //TimeTaker timer9("auxiliary drawings");
2894 //TimeTaker //timer10("//timer10");
2900 driver->setMaterial(m);
2902 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2906 for(std::vector<aabb3f>::const_iterator
2907 i = hilightboxes.begin();
2908 i != hilightboxes.end(); i++)
2910 /*infostream<<"hilightbox min="
2911 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2913 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2915 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2924 // Warning: This clears the Z buffer.
2925 camera.drawWieldedTool();
2932 client.getEnv().getClientMap().renderPostFx();
2938 if(show_profiler_graph)
2940 graph.draw(10, screensize.Y - 10, driver, font);
2948 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2949 displaycenter + core::vector2d<s32>(10,0),
2950 video::SColor(255,255,255,255));
2951 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2952 displaycenter + core::vector2d<s32>(0,10),
2953 video::SColor(255,255,255,255));
2959 //TimeTaker //timer11("//timer11");
2972 draw_hotbar(driver, font, gamedef,
2973 v2s32(displaycenter.X, screensize.Y),
2974 hotbar_imagesize, hotbar_itemcount, &local_inventory,
2975 client.getHP(), client.getPlayerItem());
2981 if(damage_flash_timer > 0.0)
2983 damage_flash_timer -= dtime;
2985 video::SColor color(128,255,0,0);
2986 driver->draw2DRectangle(color,
2987 core::rect<s32>(0,0,screensize.X,screensize.Y),
2995 TimeTaker timer("endScene");
2997 endscenetime = timer.stop(true);
3000 drawtime = tt_draw.stop(true);
3001 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3007 static s16 lastFPS = 0;
3008 //u16 fps = driver->getFPS();
3009 u16 fps = (1.0/dtime_avg1);
3013 core::stringw str = L"Minetest [";
3014 str += driver->getName();
3018 device->setWindowCaption(str.c_str());
3023 Log times and stuff for visualization
3025 Profiler::GraphValues values;
3026 g_profiler->graphGet(values);
3035 if(gui_chat_console)
3036 gui_chat_console->drop();
3039 Draw a "shutting down" screen, which will be shown while the map
3040 generator and other stuff quits
3043 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3044 draw_load_screen(L"Shutting down stuff...", driver, font);
3045 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3048 gui_shuttingdowntext->remove();*/
3051 chat_backend.addMessage(L"", L"# Disconnected.");
3052 chat_backend.addMessage(L"", L"");
3054 // Client scope (client is destructed before destructing *def and tsrc)
3057 catch(SerializationError &e)
3059 error_message = L"A serialization error occurred:\n"
3060 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3061 L" running a different version of Minetest.";
3062 errorstream<<wide_to_narrow(error_message)<<std::endl;