3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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>
28 #include "IMeshCache.h"
31 #include "guiPasswordChange.h"
32 #include "guiVolumeChange.h"
33 #include "guiFormSpecMenu.h"
34 #include "guiTextInputMenu.h"
36 #include "guiChatConsole.h"
40 #include "particles.h"
45 #include "mainmenumanager.h"
49 // Needed for determining pointing to nodes
51 #include "nodemetadata.h"
52 #include "main.h" // For g_settings
54 #include "tile.h" // For TextureSource
55 #include "shader.h" // For ShaderSource
56 #include "logoutputbuffer.h"
58 #include "quicktune_shortcutter.h"
59 #include "clientmap.h"
64 #include "sound_openal.h"
66 #include "event_manager.h"
69 #include "util/directiontables.h"
70 #include "util/pointedthing.h"
76 struct TextDestNodeMetadata : public TextDest
78 TextDestNodeMetadata(v3s16 p, Client *client)
83 // This is deprecated I guess? -celeron55
84 void gotText(std::wstring text)
86 std::string ntext = wide_to_narrow(text);
87 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
88 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
89 std::map<std::string, std::string> fields;
90 fields["text"] = ntext;
91 m_client->sendNodemetaFields(m_p, "", fields);
93 void gotText(std::map<std::string, std::string> fields)
95 m_client->sendNodemetaFields(m_p, "", fields);
102 struct TextDestPlayerInventory : public TextDest
104 TextDestPlayerInventory(Client *client)
109 TextDestPlayerInventory(Client *client, std::string formname)
112 m_formname = formname;
114 void gotText(std::map<std::string, std::string> fields)
116 m_client->sendInventoryFields(m_formname, fields);
122 struct LocalFormspecHandler : public TextDest
124 LocalFormspecHandler();
125 LocalFormspecHandler(std::string formname) :
128 m_formname = formname;
131 LocalFormspecHandler(std::string formname, Client *client) :
134 m_formname = formname;
137 void gotText(std::wstring message) {
138 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
141 void gotText(std::map<std::string, std::string> fields)
143 if (m_formname == "MT_PAUSE_MENU") {
144 if (fields.find("btn_sound") != fields.end()) {
145 g_gamecallback->changeVolume();
149 if (fields.find("btn_exit_menu") != fields.end()) {
150 g_gamecallback->disconnect();
154 if (fields.find("btn_exit_os") != fields.end()) {
155 g_gamecallback->exitToOS();
159 if (fields.find("btn_change_password") != fields.end()) {
160 g_gamecallback->changePassword();
164 if (fields.find("quit") != fields.end()) {
168 if (fields.find("btn_continue") != fields.end()) {
172 if (m_formname == "MT_CHAT_MENU") {
173 assert(m_client != 0);
174 if ((fields.find("btn_send") != fields.end()) ||
175 (fields.find("quit") != fields.end())) {
176 if (fields.find("f_text") != fields.end()) {
177 m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
183 if (m_formname == "MT_DEATH_SCREEN") {
184 assert(m_client != 0);
185 if ((fields.find("btn_respawn") != fields.end())) {
186 m_client->sendRespawn();
190 if (fields.find("quit") != fields.end()) {
191 m_client->sendRespawn();
196 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
198 for (std::map<std::string,std::string>::iterator iter = fields.begin();
199 iter != fields.end(); iter++) {
200 errorstream << "\t"<< i << ": " << iter->first << "=" << iter->second << std::endl;
208 /* Form update callback */
210 class NodeMetadataFormSource: public IFormSource
213 NodeMetadataFormSource(ClientMap *map, v3s16 p):
218 std::string getForm()
220 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
223 return meta->getString("formspec");
225 std::string resolveText(std::string str)
227 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
230 return meta->resolveString(str);
237 class PlayerInventoryFormSource: public IFormSource
240 PlayerInventoryFormSource(Client *client):
244 std::string getForm()
246 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
247 return player->inventory_formspec;
254 Check if a node is pointable
256 inline bool isPointableNode(const MapNode& n,
257 Client *client, bool liquids_pointable)
259 const ContentFeatures &features = client->getNodeDefManager()->get(n);
260 return features.pointable ||
261 (liquids_pointable && features.isLiquid());
265 Find what the player is pointing at
267 PointedThing getPointedThing(Client *client, v3f player_position,
268 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
269 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
270 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
274 hilightboxes.clear();
275 selected_object = NULL;
277 INodeDefManager *nodedef = client->getNodeDefManager();
278 ClientMap &map = client->getEnv().getClientMap();
280 f32 mindistance = BS * 1001;
282 // First try to find a pointed at active object
285 selected_object = client->getSelectedActiveObject(d*BS,
286 camera_position, shootline);
288 if(selected_object != NULL)
290 if(selected_object->doShowSelectionBox())
292 aabb3f *selection_box = selected_object->getSelectionBox();
293 // Box should exist because object was
294 // returned in the first place
295 assert(selection_box);
297 v3f pos = selected_object->getPosition();
298 hilightboxes.push_back(aabb3f(
299 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
300 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
303 mindistance = (selected_object->getPosition() - camera_position).getLength();
305 result.type = POINTEDTHING_OBJECT;
306 result.object_id = selected_object->getId();
310 // That didn't work, try to find a pointed at node
313 v3s16 pos_i = floatToInt(player_position, BS);
315 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
319 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
320 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
321 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
322 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
323 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
324 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
326 // Prevent signed number overflow
334 for(s16 y = ystart; y <= yend; y++)
335 for(s16 z = zstart; z <= zend; z++)
336 for(s16 x = xstart; x <= xend; x++)
341 n = map.getNode(v3s16(x,y,z));
343 catch(InvalidPositionException &e)
347 if(!isPointableNode(n, client, liquids_pointable))
350 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
353 v3f npf = intToFloat(np, BS);
355 for(std::vector<aabb3f>::const_iterator
357 i != boxes.end(); i++)
363 for(u16 j=0; j<6; j++)
365 v3s16 facedir = g_6dirs[j];
366 aabb3f facebox = box;
370 facebox.MinEdge.X = facebox.MaxEdge.X-d;
371 else if(facedir.X < 0)
372 facebox.MaxEdge.X = facebox.MinEdge.X+d;
373 else if(facedir.Y > 0)
374 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
375 else if(facedir.Y < 0)
376 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
377 else if(facedir.Z > 0)
378 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
379 else if(facedir.Z < 0)
380 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
382 v3f centerpoint = facebox.getCenter();
383 f32 distance = (centerpoint - camera_position).getLength();
384 if(distance >= mindistance)
386 if(!facebox.intersectsWithLine(shootline))
389 v3s16 np_above = np + facedir;
391 result.type = POINTEDTHING_NODE;
392 result.node_undersurface = np;
393 result.node_abovesurface = np_above;
394 mindistance = distance;
396 hilightboxes.clear();
397 for(std::vector<aabb3f>::const_iterator
399 i2 != boxes.end(); i2++)
402 box.MinEdge += npf + v3f(-d,-d,-d) - intToFloat(camera_offset, BS);
403 box.MaxEdge += npf + v3f(d,d,d) - intToFloat(camera_offset, BS);
404 hilightboxes.push_back(box);
414 Draws a screen with a single text on it.
415 Text will be removed when the screen is drawn the next time.
416 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
418 /*gui::IGUIStaticText **/
419 void draw_load_screen(const std::wstring &text, IrrlichtDevice* device,
420 gui::IGUIFont* font, float dtime=0 ,int percent=0, bool clouds=true)
422 video::IVideoDriver* driver = device->getVideoDriver();
423 v2u32 screensize = driver->getScreenSize();
424 const wchar_t *loadingtext = text.c_str();
425 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
426 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
427 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
428 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
430 gui::IGUIStaticText *guitext = guienv->addStaticText(
431 loadingtext, textrect, false, false);
432 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
434 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
435 if (cloud_menu_background)
437 g_menuclouds->step(dtime*3);
438 g_menuclouds->render();
439 driver->beginScene(true, true, video::SColor(255,140,186,250));
440 g_menucloudsmgr->drawAll();
443 driver->beginScene(true, true, video::SColor(255,0,0,0));
444 if (percent >= 0 && percent <= 100) // draw progress bar
446 core::vector2d<s32> barsize(256,32);
447 core::rect<s32> barrect(center-barsize/2, center+barsize/2);
448 driver->draw2DRectangle(video::SColor(255,255,255,255),barrect, NULL); // border
449 driver->draw2DRectangle(video::SColor(255,64,64,64), core::rect<s32> (
450 barrect.UpperLeftCorner+1,
451 barrect.LowerRightCorner-1), NULL); // black inside the bar
452 driver->draw2DRectangle(video::SColor(255,128,128,128), core::rect<s32> (
453 barrect.UpperLeftCorner+1,
455 barrect.LowerRightCorner.X-(barsize.X-1)+percent*(barsize.X-2)/100,
456 barrect.LowerRightCorner.Y-1)), NULL); // the actual progress
466 /* Profiler display */
468 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
469 gui::IGUIFont *font, u32 text_height, u32 show_profiler,
470 u32 show_profiler_max)
472 if(show_profiler == 0)
474 guitext_profiler->setVisible(false);
479 std::ostringstream os(std::ios_base::binary);
480 g_profiler->printPage(os, show_profiler, show_profiler_max);
481 std::wstring text = narrow_to_wide(os.str());
482 guitext_profiler->setText(text.c_str());
483 guitext_profiler->setVisible(true);
485 s32 w = font->getDimension(text.c_str()).Width;
488 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
489 8+(text_height+5)*2 +
490 font->getDimension(text.c_str()).Height);
491 guitext_profiler->setRelativePosition(rect);
492 guitext_profiler->setVisible(true);
500 Profiler::GraphValues values;
506 Meta(float initial=0, video::SColor color=
507 video::SColor(255,255,255,255)):
513 std::list<Piece> m_log;
521 void put(const Profiler::GraphValues &values)
524 piece.values = values;
525 m_log.push_back(piece);
526 while(m_log.size() > m_log_max_size)
527 m_log.erase(m_log.begin());
530 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
531 gui::IGUIFont* font) const
533 std::map<std::string, Meta> m_meta;
534 for(std::list<Piece>::const_iterator k = m_log.begin();
535 k != m_log.end(); k++)
537 const Piece &piece = *k;
538 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
539 i != piece.values.end(); i++){
540 const std::string &id = i->first;
541 const float &value = i->second;
542 std::map<std::string, Meta>::iterator j =
544 if(j == m_meta.end()){
545 m_meta[id] = Meta(value);
548 if(value < j->second.min)
549 j->second.min = value;
550 if(value > j->second.max)
551 j->second.max = value;
556 static const video::SColor usable_colors[] = {
557 video::SColor(255,255,100,100),
558 video::SColor(255,90,225,90),
559 video::SColor(255,100,100,255),
560 video::SColor(255,255,150,50),
561 video::SColor(255,220,220,100)
563 static const u32 usable_colors_count =
564 sizeof(usable_colors) / sizeof(*usable_colors);
565 u32 next_color_i = 0;
566 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
567 i != m_meta.end(); i++){
568 Meta &meta = i->second;
569 video::SColor color(255,200,200,200);
570 if(next_color_i < usable_colors_count)
571 color = usable_colors[next_color_i++];
576 s32 textx = x_left + m_log_max_size + 15;
577 s32 textx2 = textx + 200 - 15;
581 u32 num_graphs = m_meta.size();
582 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
584 video::SColor bgcolor(120,0,0,0);
585 driver->draw2DRectangle(bgcolor, rect, NULL);
589 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
590 i != m_meta.end(); i++){
591 const std::string &id = i->first;
592 const Meta &meta = i->second;
594 s32 y = y_bottom - meta_i * 50;
595 float show_min = meta.min;
596 float show_max = meta.max;
597 if(show_min >= -0.0001 && show_max >= -0.0001){
598 if(show_min <= show_max * 0.5)
603 snprintf(buf, 10, "%.3g", show_max);
604 font->draw(narrow_to_wide(buf).c_str(),
605 core::rect<s32>(textx, y - graphh,
606 textx2, y - graphh + texth),
608 snprintf(buf, 10, "%.3g", show_min);
609 font->draw(narrow_to_wide(buf).c_str(),
610 core::rect<s32>(textx, y - texth,
613 font->draw(narrow_to_wide(id).c_str(),
614 core::rect<s32>(textx, y - graphh/2 - texth/2,
615 textx2, y - graphh/2 + texth/2),
618 s32 graph1h = graphh;
619 bool relativegraph = (show_min != 0 && show_min != show_max);
620 float lastscaledvalue = 0.0;
621 bool lastscaledvalue_exists = false;
622 for(std::list<Piece>::const_iterator j = m_log.begin();
623 j != m_log.end(); j++)
625 const Piece &piece = *j;
627 bool value_exists = false;
628 Profiler::GraphValues::const_iterator k =
629 piece.values.find(id);
630 if(k != piece.values.end()){
636 lastscaledvalue_exists = false;
639 float scaledvalue = 1.0;
640 if(show_max != show_min)
641 scaledvalue = (value - show_min) / (show_max - show_min);
642 if(scaledvalue == 1.0 && value == 0){
644 lastscaledvalue_exists = false;
648 if(lastscaledvalue_exists){
649 s32 ivalue1 = lastscaledvalue * graph1h;
650 s32 ivalue2 = scaledvalue * graph1h;
651 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
652 v2s32(x, graph1y - ivalue2), meta.color);
654 lastscaledvalue = scaledvalue;
655 lastscaledvalue_exists = true;
657 s32 ivalue = scaledvalue * graph1h;
658 driver->draw2DLine(v2s32(x, graph1y),
659 v2s32(x, graph1y - ivalue), meta.color);
668 class NodeDugEvent: public MtEvent
674 NodeDugEvent(v3s16 p, MapNode n):
678 const char* getType() const
684 ISoundManager *m_sound;
685 INodeDefManager *m_ndef;
687 float m_player_step_timer;
689 SimpleSoundSpec m_player_step_sound;
690 SimpleSoundSpec m_player_leftpunch_sound;
691 SimpleSoundSpec m_player_rightpunch_sound;
693 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
696 m_player_step_timer(0)
700 void playPlayerStep()
702 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
703 m_player_step_timer = 0.03;
704 m_sound->playSound(m_player_step_sound, false);
708 static void viewBobbingStep(MtEvent *e, void *data)
710 SoundMaker *sm = (SoundMaker*)data;
711 sm->playPlayerStep();
714 static void playerRegainGround(MtEvent *e, void *data)
716 SoundMaker *sm = (SoundMaker*)data;
717 sm->playPlayerStep();
720 static void playerJump(MtEvent *e, void *data)
722 //SoundMaker *sm = (SoundMaker*)data;
725 static void cameraPunchLeft(MtEvent *e, void *data)
727 SoundMaker *sm = (SoundMaker*)data;
728 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
731 static void cameraPunchRight(MtEvent *e, void *data)
733 SoundMaker *sm = (SoundMaker*)data;
734 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
737 static void nodeDug(MtEvent *e, void *data)
739 SoundMaker *sm = (SoundMaker*)data;
740 NodeDugEvent *nde = (NodeDugEvent*)e;
741 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
744 static void playerDamage(MtEvent *e, void *data)
746 SoundMaker *sm = (SoundMaker*)data;
747 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
750 static void playerFallingDamage(MtEvent *e, void *data)
752 SoundMaker *sm = (SoundMaker*)data;
753 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
756 void registerReceiver(MtEventManager *mgr)
758 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
759 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
760 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
761 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
762 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
763 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
764 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
765 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
768 void step(float dtime)
770 m_player_step_timer -= dtime;
774 // Locally stored sounds don't need to be preloaded because of this
775 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
777 std::set<std::string> m_fetched;
780 void fetchSounds(const std::string &name,
781 std::set<std::string> &dst_paths,
782 std::set<std::string> &dst_datas)
784 if(m_fetched.count(name))
786 m_fetched.insert(name);
787 std::string base = porting::path_share + DIR_DELIM + "testsounds";
788 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
789 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
790 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
791 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
792 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
793 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
794 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
795 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
796 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
797 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
798 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
802 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
805 bool *m_force_fog_off;
810 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
811 f32 *fog_range, Client *client):
813 m_force_fog_off(force_fog_off),
814 m_fog_range(fog_range),
817 ~GameGlobalShaderConstantSetter() {}
819 virtual void onSetConstants(video::IMaterialRendererServices *services,
826 video::SColor bgcolor = m_sky->getBgColor();
827 video::SColorf bgcolorf(bgcolor);
828 float bgcolorfa[4] = {
834 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
837 float fog_distance = 10000*BS;
838 if(g_settings->getBool("enable_fog") && !*m_force_fog_off)
839 fog_distance = *m_fog_range;
840 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
843 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
844 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
845 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
847 u32 animation_timer = porting::getTimeMs() % 100000;
848 float animation_timer_f = (float)animation_timer / 100000.0;
849 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
850 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
852 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
853 v3f eye_position = player->getEyePosition();
854 services->setPixelShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
855 services->setVertexShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
857 // Uniform sampler layers
861 // before 1.8 there isn't a "integer interface", only float
862 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
863 services->setPixelShaderConstant("baseTexture" , (irr::f32*)&layer0, 1);
864 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer1, 1);
865 services->setPixelShaderConstant("useNormalmap" , (irr::f32*)&layer2, 1);
867 services->setPixelShaderConstant("baseTexture" , (irr::s32*)&layer0, 1);
868 services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer1, 1);
869 services->setPixelShaderConstant("useNormalmap" , (irr::s32*)&layer2, 1);
874 bool nodePlacementPrediction(Client &client,
875 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
877 std::string prediction = playeritem_def.node_placement_prediction;
878 INodeDefManager *nodedef = client.ndef();
879 ClientMap &map = client.getEnv().getClientMap();
881 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
883 verbosestream<<"Node placement prediction for "
884 <<playeritem_def.name<<" is "
885 <<prediction<<std::endl;
886 v3s16 p = neighbourpos;
887 // Place inside node itself if buildable_to
889 MapNode n_under = map.getNode(nodepos);
890 if(nodedef->get(n_under).buildable_to)
892 else if (!nodedef->get(map.getNode(p)).buildable_to)
894 }catch(InvalidPositionException &e){}
895 // Find id of predicted node
897 bool found = nodedef->getId(prediction, id);
899 errorstream<<"Node placement prediction failed for "
900 <<playeritem_def.name<<" (places "
902 <<") - Name not known"<<std::endl;
905 // Predict param2 for facedir and wallmounted nodes
907 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
908 v3s16 dir = nodepos - neighbourpos;
909 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
910 param2 = dir.Y < 0 ? 1 : 0;
911 } else if(abs(dir.X) > abs(dir.Z)){
912 param2 = dir.X < 0 ? 3 : 2;
914 param2 = dir.Z < 0 ? 5 : 4;
917 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
918 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
919 if(abs(dir.X) > abs(dir.Z)){
920 param2 = dir.X < 0 ? 3 : 1;
922 param2 = dir.Z < 0 ? 2 : 0;
925 assert(param2 >= 0 && param2 <= 5);
926 //Check attachment if node is in group attached_node
927 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
928 static v3s16 wallmounted_dirs[8] = {
937 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
938 pp = p + wallmounted_dirs[param2];
940 pp = p + v3s16(0,-1,0);
941 if(!nodedef->get(map.getNode(pp)).walkable)
944 // Add node to client map
945 MapNode n(id, 0, param2);
947 LocalPlayer* player = client.getEnv().getLocalPlayer();
949 // Dont place node when player would be inside new node
950 // NOTE: This is to be eventually implemented by a mod as client-side Lua
951 if (!nodedef->get(n).walkable ||
952 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
953 (nodedef->get(n).walkable &&
954 neighbourpos != player->getStandingNodePos() + v3s16(0,1,0) &&
955 neighbourpos != player->getStandingNodePos() + v3s16(0,2,0))) {
957 // This triggers the required mesh update too
958 client.addNode(p, n);
961 }catch(InvalidPositionException &e){
962 errorstream<<"Node placement prediction failed for "
963 <<playeritem_def.name<<" (places "
965 <<") - Position not loaded"<<std::endl;
971 static inline void create_formspec_menu(GUIFormSpecMenu** cur_formspec,
972 InventoryManager *invmgr, IGameDef *gamedef,
973 IWritableTextureSource* tsrc, IrrlichtDevice * device,
974 IFormSource* fs_src, TextDest* txt_dest
977 if (*cur_formspec == 0) {
978 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
979 invmgr, gamedef, tsrc, fs_src, txt_dest, cur_formspec );
980 (*cur_formspec)->doPause = false;
981 (*cur_formspec)->drop();
984 (*cur_formspec)->setFormSource(fs_src);
985 (*cur_formspec)->setTextDest(txt_dest);
989 static void show_chat_menu(GUIFormSpecMenu** cur_formspec,
990 InventoryManager *invmgr, IGameDef *gamedef,
991 IWritableTextureSource* tsrc, IrrlichtDevice * device,
992 Client* client, std::string text)
994 std::string formspec =
996 "field[3,2.35;6,0.5;f_text;;" + text + "]"
997 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
1001 /* Note: FormspecFormSource and LocalFormspecHandler
1002 * are deleted by guiFormSpecMenu */
1003 FormspecFormSource* fs_src = new FormspecFormSource(formspec);
1004 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1006 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst);
1009 static void show_deathscreen(GUIFormSpecMenu** cur_formspec,
1010 InventoryManager *invmgr, IGameDef *gamedef,
1011 IWritableTextureSource* tsrc, IrrlichtDevice * device, Client* client)
1013 std::string formspec =
1016 "bgcolor[#320000b4;true]"
1017 "label[4.85,1.35;You died.]"
1018 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1022 /* Note: FormspecFormSource and LocalFormspecHandler
1023 * are deleted by guiFormSpecMenu */
1024 FormspecFormSource* fs_src = new FormspecFormSource(formspec);
1025 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1027 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst);
1030 /******************************************************************************/
1031 static void show_pause_menu(GUIFormSpecMenu** cur_formspec,
1032 InventoryManager *invmgr, IGameDef *gamedef,
1033 IWritableTextureSource* tsrc, IrrlichtDevice * device,
1034 bool singleplayermode)
1036 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1038 "- Space: jump/climb\n"
1039 "- Shift: sneak/go down\n"
1042 "- Mouse: turn/look\n"
1043 "- Mouse left: dig/punch\n"
1044 "- Mouse right: place/use\n"
1045 "- Mouse wheel: select item\n"
1049 float ypos = singleplayermode ? 1.0 : 0.5;
1050 std::ostringstream os;
1052 os << "size[11,5.5,true]"
1053 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1054 << wide_to_narrow(wstrgettext("Continue")) << "]";
1056 if (!singleplayermode) {
1057 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1058 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1061 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1062 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1063 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1064 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1065 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1066 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1067 << "textarea[7.5,0.25;3.75,6;;" << control_text << ";]"
1068 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1069 << minetest_build_info << "\n"
1070 << "path_user = " << wrap_rows(porting::path_user, 20)
1074 /* Note: FormspecFormSource and LocalFormspecHandler *
1075 * are deleted by guiFormSpecMenu */
1076 FormspecFormSource* fs_src = new FormspecFormSource(os.str());
1077 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1079 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst);
1081 if (singleplayermode) {
1082 (*cur_formspec)->doPause = true;
1086 /******************************************************************************/
1087 void the_game(bool &kill, bool random_input, InputHandler *input,
1088 IrrlichtDevice *device, gui::IGUIFont* font, std::string map_dir,
1089 std::string playername, std::string password,
1090 std::string address /* If "", local server is used */,
1091 u16 port, std::wstring &error_message, ChatBackend &chat_backend,
1092 const SubgameSpec &gamespec /* Used for local game */,
1093 bool simple_singleplayer_mode)
1095 GUIFormSpecMenu* current_formspec = 0;
1096 video::IVideoDriver* driver = device->getVideoDriver();
1097 scene::ISceneManager* smgr = device->getSceneManager();
1099 // Calculate text height using the font
1100 u32 text_height = font->getDimension(L"Random test string").Height;
1103 Draw "Loading" screen
1107 wchar_t* text = wgettext("Loading...");
1108 draw_load_screen(text, device, font,0,0);
1112 // Create texture source
1113 IWritableTextureSource *tsrc = createTextureSource(device);
1115 // Create shader source
1116 IWritableShaderSource *shsrc = createShaderSource(device);
1118 // These will be filled by data received from the server
1119 // Create item definition manager
1120 IWritableItemDefManager *itemdef = createItemDefManager();
1121 // Create node definition manager
1122 IWritableNodeDefManager *nodedef = createNodeDefManager();
1124 // Sound fetcher (useful when testing)
1125 GameOnDemandSoundFetcher soundfetcher;
1128 ISoundManager *sound = NULL;
1129 bool sound_is_dummy = false;
1131 if(g_settings->getBool("enable_sound")){
1132 infostream<<"Attempting to use OpenAL audio"<<std::endl;
1133 sound = createOpenALSoundManager(&soundfetcher);
1135 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
1137 infostream<<"Sound disabled."<<std::endl;
1141 infostream<<"Using dummy audio."<<std::endl;
1142 sound = &dummySoundManager;
1143 sound_is_dummy = true;
1146 Server *server = NULL;
1150 EventManager eventmgr;
1153 SoundMaker soundmaker(sound, nodedef);
1154 soundmaker.registerReceiver(&eventmgr);
1156 // Add chat log output for errors to be shown in chat
1157 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1159 // Create UI for modifying quicktune values
1160 QuicktuneShortcutter quicktune;
1167 wchar_t* text = wgettext("Creating server....");
1168 draw_load_screen(text, device, font,0,25);
1170 infostream<<"Creating server"<<std::endl;
1172 std::string bind_str = g_settings->get("bind_address");
1173 Address bind_addr(0,0,0,0, port);
1175 if (g_settings->getBool("ipv6_server")) {
1176 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1179 bind_addr.Resolve(bind_str.c_str());
1181 } catch (ResolveError &e) {
1182 infostream << "Resolving bind address \"" << bind_str
1183 << "\" failed: " << e.what()
1184 << " -- Listening on all addresses." << std::endl;
1187 if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1188 error_message = L"Unable to listen on " +
1189 narrow_to_wide(bind_addr.serializeString()) +
1190 L" because IPv6 is disabled";
1191 errorstream<<wide_to_narrow(error_message)<<std::endl;
1192 // Break out of client scope
1196 server = new Server(map_dir, gamespec,
1197 simple_singleplayer_mode,
1198 bind_addr.isIPv6());
1200 server->start(bind_addr);
1203 do{ // Client scope (breakable do-while(0))
1210 wchar_t* text = wgettext("Creating client...");
1211 draw_load_screen(text, device, font,0,50);
1214 infostream<<"Creating client"<<std::endl;
1216 MapDrawControl draw_control;
1219 wchar_t* text = wgettext("Resolving address...");
1220 draw_load_screen(text, device, font,0,75);
1223 Address connect_address(0,0,0,0, port);
1225 connect_address.Resolve(address.c_str());
1226 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1227 //connect_address.Resolve("localhost");
1228 if (connect_address.isIPv6()) {
1229 IPv6AddressBytes addr_bytes;
1230 addr_bytes.bytes[15] = 1;
1231 connect_address.setAddress(&addr_bytes);
1233 connect_address.setAddress(127,0,0,1);
1237 catch(ResolveError &e) {
1238 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1239 errorstream<<wide_to_narrow(error_message)<<std::endl;
1240 // Break out of client scope
1243 if(connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1244 error_message = L"Unable to connect to " +
1245 narrow_to_wide(connect_address.serializeString()) +
1246 L" because IPv6 is disabled";
1247 errorstream<<wide_to_narrow(error_message)<<std::endl;
1248 // Break out of client scope
1255 Client client(device, playername.c_str(), password, draw_control,
1256 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1257 connect_address.isIPv6());
1259 // Client acts as our GameDef
1260 IGameDef *gamedef = &client;
1263 Attempt to connect to the server
1266 infostream<<"Connecting to server at ";
1267 connect_address.print(&infostream);
1268 infostream<<std::endl;
1269 client.connect(connect_address);
1272 Wait for server to accept connection
1274 bool could_connect = false;
1275 bool connect_aborted = false;
1277 float time_counter = 0.0;
1279 float fps_max = g_settings->getFloat("fps_max");
1280 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1281 u32 lasttime = device->getTimer()->getTime();
1282 while(device->run())
1284 f32 dtime = 0.033; // in seconds
1285 if (cloud_menu_background) {
1286 u32 time = device->getTimer()->getTime();
1288 dtime = (time - lasttime) / 1000.0;
1293 // Update client and server
1296 server->step(dtime);
1299 if(client.getState() == LC_Init){
1300 could_connect = true;
1304 if(client.accessDenied()){
1305 error_message = L"Access denied. Reason: "
1306 +client.accessDeniedReason();
1307 errorstream<<wide_to_narrow(error_message)<<std::endl;
1310 if(input->wasKeyDown(EscapeKey)){
1311 connect_aborted = true;
1312 infostream<<"Connect aborted [Escape]"<<std::endl;
1318 wchar_t* text = wgettext("Connecting to server...");
1319 draw_load_screen(text, device, font, dtime, 100);
1323 // On some computers framerate doesn't seem to be
1324 // automatically limited
1325 if (cloud_menu_background) {
1326 // Time of frame without fps limit
1329 // not using getRealTime is necessary for wine
1330 u32 time = device->getTimer()->getTime();
1332 busytime_u32 = time - lasttime;
1335 busytime = busytime_u32 / 1000.0;
1338 u32 frametime_min = 1000./fps_max;
1340 if(busytime_u32 < frametime_min) {
1341 u32 sleeptime = frametime_min - busytime_u32;
1342 device->sleep(sleeptime);
1347 time_counter += dtime;
1350 catch(con::PeerNotFoundException &e)
1354 Handle failure to connect
1357 if(error_message == L"" && !connect_aborted){
1358 error_message = L"Connection failed";
1359 errorstream<<wide_to_narrow(error_message)<<std::endl;
1361 // Break out of client scope
1366 Wait until content has been received
1368 bool got_content = false;
1369 bool content_aborted = false;
1371 float time_counter = 0.0;
1373 float fps_max = g_settings->getFloat("fps_max");
1374 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1375 u32 lasttime = device->getTimer()->getTime();
1376 while(device->run())
1378 f32 dtime = 0.033; // in seconds
1379 if (cloud_menu_background) {
1380 u32 time = device->getTimer()->getTime();
1382 dtime = (time - lasttime) / 1000.0;
1387 // Update client and server
1390 server->step(dtime);
1393 if(client.mediaReceived() &&
1394 client.itemdefReceived() &&
1395 client.nodedefReceived()){
1400 if(client.accessDenied()){
1401 error_message = L"Access denied. Reason: "
1402 +client.accessDeniedReason();
1403 errorstream<<wide_to_narrow(error_message)<<std::endl;
1406 if(client.getState() < LC_Init){
1407 error_message = L"Client disconnected";
1408 errorstream<<wide_to_narrow(error_message)<<std::endl;
1411 if(input->wasKeyDown(EscapeKey)){
1412 content_aborted = true;
1413 infostream<<"Connect aborted [Escape]"<<std::endl;
1419 if (!client.itemdefReceived())
1421 wchar_t* text = wgettext("Item definitions...");
1423 draw_load_screen(text, device, font, dtime, progress);
1426 else if (!client.nodedefReceived())
1428 wchar_t* text = wgettext("Node definitions...");
1430 draw_load_screen(text, device, font, dtime, progress);
1435 wchar_t* text = wgettext("Media...");
1436 progress = 50+client.mediaReceiveProgress()*50+0.5;
1437 draw_load_screen(text, device, font, dtime, progress);
1441 // On some computers framerate doesn't seem to be
1442 // automatically limited
1443 if (cloud_menu_background) {
1444 // Time of frame without fps limit
1447 // not using getRealTime is necessary for wine
1448 u32 time = device->getTimer()->getTime();
1450 busytime_u32 = time - lasttime;
1453 busytime = busytime_u32 / 1000.0;
1456 u32 frametime_min = 1000./fps_max;
1458 if(busytime_u32 < frametime_min) {
1459 u32 sleeptime = frametime_min - busytime_u32;
1460 device->sleep(sleeptime);
1465 time_counter += dtime;
1470 if(error_message == L"" && !content_aborted){
1471 error_message = L"Something failed";
1472 errorstream<<wide_to_narrow(error_message)<<std::endl;
1474 // Break out of client scope
1479 After all content has been received:
1480 Update cached textures, meshes and materials
1482 client.afterContentReceived(device,font);
1485 Create the camera node
1487 Camera camera(smgr, draw_control, gamedef);
1488 if (!camera.successfullyCreated(error_message))
1491 f32 camera_yaw = 0; // "right/left"
1492 f32 camera_pitch = 0; // "up/down"
1494 int current_camera_mode = CAMERA_MODE_FIRST; // start in first-person view
1500 Clouds *clouds = NULL;
1501 if(g_settings->getBool("enable_clouds"))
1503 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1511 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, client.getEnv().getLocalPlayer());
1513 scene::ISceneNode* skybox = NULL;
1516 A copy of the local inventory
1518 Inventory local_inventory(itemdef);
1521 Find out size of crack animation
1523 int crack_animation_length = 5;
1525 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1526 v2u32 size = t->getOriginalSize();
1527 crack_animation_length = size.Y / size.X;
1534 // First line of debug text
1535 gui::IGUIStaticText *guitext = guienv->addStaticText(
1537 core::rect<s32>(0, 0, 0, 0),
1539 // Second line of debug text
1540 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1542 core::rect<s32>(0, 0, 0, 0),
1544 // At the middle of the screen
1545 // Object infos are shown in this
1546 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1548 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1551 // Status text (displays info when showing and hiding GUI stuff, etc.)
1552 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1554 core::rect<s32>(0,0,0,0),
1556 guitext_status->setVisible(false);
1558 std::wstring statustext;
1559 float statustext_time = 0;
1562 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1564 core::rect<s32>(0,0,0,0),
1565 //false, false); // Disable word wrap as of now
1567 // Remove stale "recent" chat messages from previous connections
1568 chat_backend.clearRecentChat();
1569 // Chat backend and console
1570 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1572 // Profiler text (size is updated when text is updated)
1573 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1575 core::rect<s32>(0,0,0,0),
1577 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1578 guitext_profiler->setVisible(false);
1579 guitext_profiler->setWordWrap(true);
1582 Some statistics are collected in these
1585 u32 beginscenetime = 0;
1587 u32 endscenetime = 0;
1589 float recent_turn_speed = 0.0;
1591 ProfilerGraph graph;
1592 // Initially clear the profiler
1593 Profiler::GraphValues dummyvalues;
1594 g_profiler->graphGet(dummyvalues);
1596 float nodig_delay_timer = 0.0;
1597 float dig_time = 0.0;
1599 PointedThing pointed_old;
1600 bool digging = false;
1601 bool ldown_for_dig = false;
1603 float damage_flash = 0;
1605 float jump_timer = 0;
1606 bool reset_jump_timer = false;
1608 const float object_hit_delay = 0.2;
1609 float object_hit_delay_timer = 0.0;
1610 float time_from_last_punch = 10;
1612 float update_draw_list_timer = 0.0;
1613 v3f update_draw_list_last_cam_dir;
1615 bool invert_mouse = g_settings->getBool("invert_mouse");
1617 bool update_wielded_item_trigger = true;
1619 bool show_hud = true;
1620 bool show_chat = true;
1621 bool force_fog_off = false;
1622 f32 fog_range = 100*BS;
1623 bool disable_camera_update = false;
1624 bool show_debug = g_settings->getBool("show_debug");
1625 bool show_profiler_graph = false;
1626 u32 show_profiler = 0;
1627 u32 show_profiler_max = 3; // Number of pages
1629 float time_of_day = 0;
1630 float time_of_day_smooth = 0;
1632 float repeat_rightclick_timer = 0;
1637 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1638 sky, &force_fog_off, &fog_range, &client));
1644 bool first_loop_after_window_activation = true;
1646 // TODO: Convert the static interval timers to these
1647 // Interval limiter for profiler
1648 IntervalLimiter m_profiler_interval;
1650 // Time is in milliseconds
1651 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1652 // NOTE: So we have to use getTime() and call run()s between them
1653 u32 lasttime = device->getTimer()->getTime();
1655 LocalPlayer* player = client.getEnv().getLocalPlayer();
1656 player->hurt_tilt_timer = 0;
1657 player->hurt_tilt_strength = 0;
1662 Hud hud(driver, smgr, guienv, font, text_height,
1663 gamedef, player, &local_inventory);
1665 core::stringw str = L"Minetest [";
1666 str += driver->getName();
1668 device->setWindowCaption(str.c_str());
1671 std::wstring infotext;
1675 if(device->run() == false || kill == true)
1678 v2u32 screensize = driver->getScreenSize();
1680 // Time of frame without fps limit
1684 // not using getRealTime is necessary for wine
1685 u32 time = device->getTimer()->getTime();
1687 busytime_u32 = time - lasttime;
1690 busytime = busytime_u32 / 1000.0;
1693 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1695 // Necessary for device->getTimer()->getTime()
1703 float fps_max = g_menumgr.pausesGame() ?
1704 g_settings->getFloat("pause_fps_max") :
1705 g_settings->getFloat("fps_max");
1706 u32 frametime_min = 1000./fps_max;
1708 if(busytime_u32 < frametime_min)
1710 u32 sleeptime = frametime_min - busytime_u32;
1711 device->sleep(sleeptime);
1712 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1716 // Necessary for device->getTimer()->getTime()
1720 Time difference calculation
1722 f32 dtime; // in seconds
1724 u32 time = device->getTimer()->getTime();
1726 dtime = (time - lasttime) / 1000.0;
1731 g_profiler->graphAdd("mainloop_dtime", dtime);
1735 if(nodig_delay_timer >= 0)
1736 nodig_delay_timer -= dtime;
1737 if(object_hit_delay_timer >= 0)
1738 object_hit_delay_timer -= dtime;
1739 time_from_last_punch += dtime;
1741 g_profiler->add("Elapsed time", dtime);
1742 g_profiler->avg("FPS", 1./dtime);
1745 Time average and jitter calculation
1748 static f32 dtime_avg1 = 0.0;
1749 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1750 f32 dtime_jitter1 = dtime - dtime_avg1;
1752 static f32 dtime_jitter1_max_sample = 0.0;
1753 static f32 dtime_jitter1_max_fraction = 0.0;
1755 static f32 jitter1_max = 0.0;
1756 static f32 counter = 0.0;
1757 if(dtime_jitter1 > jitter1_max)
1758 jitter1_max = dtime_jitter1;
1763 dtime_jitter1_max_sample = jitter1_max;
1764 dtime_jitter1_max_fraction
1765 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1771 Busytime average and jitter calculation
1774 static f32 busytime_avg1 = 0.0;
1775 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1776 f32 busytime_jitter1 = busytime - busytime_avg1;
1778 static f32 busytime_jitter1_max_sample = 0.0;
1779 static f32 busytime_jitter1_min_sample = 0.0;
1781 static f32 jitter1_max = 0.0;
1782 static f32 jitter1_min = 0.0;
1783 static f32 counter = 0.0;
1784 if(busytime_jitter1 > jitter1_max)
1785 jitter1_max = busytime_jitter1;
1786 if(busytime_jitter1 < jitter1_min)
1787 jitter1_min = busytime_jitter1;
1791 busytime_jitter1_max_sample = jitter1_max;
1792 busytime_jitter1_min_sample = jitter1_min;
1799 Handle miscellaneous stuff
1802 if(client.accessDenied())
1804 error_message = L"Access denied. Reason: "
1805 +client.accessDeniedReason();
1806 errorstream<<wide_to_narrow(error_message)<<std::endl;
1810 if(g_gamecallback->disconnect_requested)
1812 g_gamecallback->disconnect_requested = false;
1816 if(g_gamecallback->changepassword_requested)
1818 (new GUIPasswordChange(guienv, guiroot, -1,
1819 &g_menumgr, &client))->drop();
1820 g_gamecallback->changepassword_requested = false;
1823 if(g_gamecallback->changevolume_requested)
1825 (new GUIVolumeChange(guienv, guiroot, -1,
1826 &g_menumgr, &client))->drop();
1827 g_gamecallback->changevolume_requested = false;
1830 /* Process TextureSource's queue */
1831 tsrc->processQueue();
1833 /* Process ItemDefManager's queue */
1834 itemdef->processQueue(gamedef);
1837 Process ShaderSource's queue
1839 shsrc->processQueue();
1846 // Hilight boxes collected during the loop and displayed
1847 std::vector<aabb3f> hilightboxes;
1849 /* reset infotext */
1854 float profiler_print_interval =
1855 g_settings->getFloat("profiler_print_interval");
1856 bool print_to_log = true;
1857 if(profiler_print_interval == 0){
1858 print_to_log = false;
1859 profiler_print_interval = 5;
1861 if(m_profiler_interval.step(dtime, profiler_print_interval))
1864 infostream<<"Profiler:"<<std::endl;
1865 g_profiler->print(infostream);
1868 update_profiler_gui(guitext_profiler, font, text_height,
1869 show_profiler, show_profiler_max);
1871 g_profiler->clear();
1875 Direct handling of user input
1878 // Reset input if window not active or some menu is active
1879 if(device->isWindowActive() == false
1880 || noMenuActive() == false
1881 || guienv->hasFocus(gui_chat_console))
1885 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1887 gui_chat_console->closeConsoleAtOnce();
1890 // Input handler step() (used by the random input generator)
1893 // Increase timer for doubleclick of "jump"
1894 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1895 jump_timer += dtime;
1898 Launch menus and trigger stuff according to keys
1900 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1902 // drop selected item
1903 IDropAction *a = new IDropAction();
1905 a->from_inv.setCurrentPlayer();
1906 a->from_list = "main";
1907 a->from_i = client.getPlayerItem();
1908 client.inventoryAction(a);
1910 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1912 infostream<<"the_game: "
1913 <<"Launching inventory"<<std::endl;
1915 PlayerInventoryFormSource* fs_src = new PlayerInventoryFormSource(&client);
1916 TextDest* txt_dst = new TextDestPlayerInventory(&client);
1918 create_formspec_menu(¤t_formspec, &client, gamedef, tsrc, device, fs_src, txt_dst);
1920 InventoryLocation inventoryloc;
1921 inventoryloc.setCurrentPlayer();
1922 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
1924 else if(input->wasKeyDown(EscapeKey))
1926 show_pause_menu(¤t_formspec, &client, gamedef, tsrc, device,
1927 simple_singleplayer_mode);
1929 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1931 show_chat_menu(¤t_formspec, &client, gamedef, tsrc, device,
1934 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1936 show_chat_menu(¤t_formspec, &client, gamedef, tsrc, device,
1939 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1941 if (!gui_chat_console->isOpenInhibited())
1943 // Open up to over half of the screen
1944 gui_chat_console->openConsole(0.6);
1945 guienv->setFocus(gui_chat_console);
1948 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1950 if(g_settings->getBool("free_move"))
1952 g_settings->set("free_move","false");
1953 statustext = L"free_move disabled";
1954 statustext_time = 0;
1958 g_settings->set("free_move","true");
1959 statustext = L"free_move enabled";
1960 statustext_time = 0;
1961 if(!client.checkPrivilege("fly"))
1962 statustext += L" (note: no 'fly' privilege)";
1965 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1967 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1969 if(g_settings->getBool("free_move"))
1971 g_settings->set("free_move","false");
1972 statustext = L"free_move disabled";
1973 statustext_time = 0;
1977 g_settings->set("free_move","true");
1978 statustext = L"free_move enabled";
1979 statustext_time = 0;
1980 if(!client.checkPrivilege("fly"))
1981 statustext += L" (note: no 'fly' privilege)";
1984 reset_jump_timer = true;
1986 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1988 if(g_settings->getBool("fast_move"))
1990 g_settings->set("fast_move","false");
1991 statustext = L"fast_move disabled";
1992 statustext_time = 0;
1996 g_settings->set("fast_move","true");
1997 statustext = L"fast_move enabled";
1998 statustext_time = 0;
1999 if(!client.checkPrivilege("fast"))
2000 statustext += L" (note: no 'fast' privilege)";
2003 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
2005 if(g_settings->getBool("noclip"))
2007 g_settings->set("noclip","false");
2008 statustext = L"noclip disabled";
2009 statustext_time = 0;
2013 g_settings->set("noclip","true");
2014 statustext = L"noclip enabled";
2015 statustext_time = 0;
2016 if(!client.checkPrivilege("noclip"))
2017 statustext += L" (note: no 'noclip' privilege)";
2020 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
2022 irr::video::IImage* const image = driver->createScreenShot();
2024 irr::c8 filename[256];
2025 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
2026 g_settings->get("screenshot_path").c_str(),
2027 device->getTimer()->getRealTime());
2028 if (driver->writeImageToFile(image, filename)) {
2029 std::wstringstream sstr;
2030 sstr<<"Saved screenshot to '"<<filename<<"'";
2031 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
2032 statustext = sstr.str();
2033 statustext_time = 0;
2035 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
2040 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
2042 show_hud = !show_hud;
2044 statustext = L"HUD shown";
2046 statustext = L"HUD hidden";
2047 statustext_time = 0;
2049 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
2051 show_chat = !show_chat;
2053 statustext = L"Chat shown";
2055 statustext = L"Chat hidden";
2056 statustext_time = 0;
2058 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
2060 force_fog_off = !force_fog_off;
2062 statustext = L"Fog disabled";
2064 statustext = L"Fog enabled";
2065 statustext_time = 0;
2067 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
2069 disable_camera_update = !disable_camera_update;
2070 if(disable_camera_update)
2071 statustext = L"Camera update disabled";
2073 statustext = L"Camera update enabled";
2074 statustext_time = 0;
2076 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
2078 // Initial / 3x toggle: Chat only
2079 // 1x toggle: Debug text with chat
2080 // 2x toggle: Debug text with profiler graph
2084 show_profiler_graph = false;
2085 statustext = L"Debug info shown";
2086 statustext_time = 0;
2088 else if(show_profiler_graph)
2091 show_profiler_graph = false;
2092 statustext = L"Debug info and profiler graph hidden";
2093 statustext_time = 0;
2097 show_profiler_graph = true;
2098 statustext = L"Profiler graph shown";
2099 statustext_time = 0;
2102 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2104 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2106 // FIXME: This updates the profiler with incomplete values
2107 update_profiler_gui(guitext_profiler, font, text_height,
2108 show_profiler, show_profiler_max);
2110 if(show_profiler != 0)
2112 std::wstringstream sstr;
2113 sstr<<"Profiler shown (page "<<show_profiler
2114 <<" of "<<show_profiler_max<<")";
2115 statustext = sstr.str();
2116 statustext_time = 0;
2120 statustext = L"Profiler hidden";
2121 statustext_time = 0;
2124 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2126 s16 range = g_settings->getS16("viewing_range_nodes_min");
2127 s16 range_new = range + 10;
2128 g_settings->set("viewing_range_nodes_min", itos(range_new));
2129 statustext = narrow_to_wide(
2130 "Minimum viewing range changed to "
2132 statustext_time = 0;
2134 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2136 s16 range = g_settings->getS16("viewing_range_nodes_min");
2137 s16 range_new = range - 10;
2140 g_settings->set("viewing_range_nodes_min",
2142 statustext = narrow_to_wide(
2143 "Minimum viewing range changed to "
2145 statustext_time = 0;
2149 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2151 reset_jump_timer = false;
2155 // Handle QuicktuneShortcutter
2156 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2158 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2160 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2162 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2165 std::string msg = quicktune.getMessage();
2167 statustext = narrow_to_wide(msg);
2168 statustext_time = 0;
2172 // Item selection with mouse wheel
2173 u16 new_playeritem = client.getPlayerItem();
2175 s32 wheel = input->getMouseWheel();
2176 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2177 player->hud_hotbar_itemcount-1);
2181 if(new_playeritem < max_item)
2188 if(new_playeritem > 0)
2191 new_playeritem = max_item;
2196 for(u16 i=0; i<10; i++)
2198 const KeyPress *kp = NumberKey + (i + 1) % 10;
2199 if(input->wasKeyDown(*kp))
2201 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2205 infostream<<"Selected item: "
2206 <<new_playeritem<<std::endl;
2211 // Viewing range selection
2212 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2214 draw_control.range_all = !draw_control.range_all;
2215 if(draw_control.range_all)
2217 infostream<<"Enabled full viewing range"<<std::endl;
2218 statustext = L"Enabled full viewing range";
2219 statustext_time = 0;
2223 infostream<<"Disabled full viewing range"<<std::endl;
2224 statustext = L"Disabled full viewing range";
2225 statustext_time = 0;
2229 // Print debug stacks
2230 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2232 dstream<<"-----------------------------------------"
2234 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2235 dstream<<"-----------------------------------------"
2237 debug_stacks_print();
2241 Mouse and camera control
2242 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2245 float turn_amount = 0;
2246 if((device->isWindowActive() && noMenuActive()) || random_input)
2250 // Mac OSX gets upset if this is set every frame
2251 if(device->getCursorControl()->isVisible())
2252 device->getCursorControl()->setVisible(false);
2255 if(first_loop_after_window_activation){
2256 //infostream<<"window active, first loop"<<std::endl;
2257 first_loop_after_window_activation = false;
2260 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width/2);
2261 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height/2);
2262 if(invert_mouse || player->camera_mode == CAMERA_MODE_THIRD_FRONT) {
2265 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2267 /*const float keyspeed = 500;
2268 if(input->isKeyDown(irr::KEY_UP))
2269 dy -= dtime * keyspeed;
2270 if(input->isKeyDown(irr::KEY_DOWN))
2271 dy += dtime * keyspeed;
2272 if(input->isKeyDown(irr::KEY_LEFT))
2273 dx -= dtime * keyspeed;
2274 if(input->isKeyDown(irr::KEY_RIGHT))
2275 dx += dtime * keyspeed;*/
2277 float d = g_settings->getFloat("mouse_sensitivity");
2278 d = rangelim(d, 0.01, 100.0);
2280 camera_pitch += dy*d;
2281 if(camera_pitch < -89.5) camera_pitch = -89.5;
2282 if(camera_pitch > 89.5) camera_pitch = 89.5;
2284 turn_amount = v2f(dx, dy).getLength() * d;
2286 input->setMousePos((driver->getScreenSize().Width/2),
2287 (driver->getScreenSize().Height/2));
2290 // Mac OSX gets upset if this is set every frame
2291 if(device->getCursorControl()->isVisible() == false)
2292 device->getCursorControl()->setVisible(true);
2294 //infostream<<"window inactive"<<std::endl;
2295 first_loop_after_window_activation = true;
2297 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2298 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2301 Player speed control
2315 PlayerControl control(
2316 input->isKeyDown(getKeySetting("keymap_forward")),
2317 input->isKeyDown(getKeySetting("keymap_backward")),
2318 input->isKeyDown(getKeySetting("keymap_left")),
2319 input->isKeyDown(getKeySetting("keymap_right")),
2320 input->isKeyDown(getKeySetting("keymap_jump")),
2321 input->isKeyDown(getKeySetting("keymap_special1")),
2322 input->isKeyDown(getKeySetting("keymap_sneak")),
2323 input->getLeftState(),
2324 input->getRightState(),
2328 client.setPlayerControl(control);
2329 LocalPlayer* player = client.getEnv().getLocalPlayer();
2331 (((int)input->isKeyDown(getKeySetting("keymap_forward")) & 0x1) << 0) |
2332 (((int)input->isKeyDown(getKeySetting("keymap_backward")) & 0x1) << 1) |
2333 (((int)input->isKeyDown(getKeySetting("keymap_left")) & 0x1) << 2) |
2334 (((int)input->isKeyDown(getKeySetting("keymap_right")) & 0x1) << 3) |
2335 (((int)input->isKeyDown(getKeySetting("keymap_jump")) & 0x1) << 4) |
2336 (((int)input->isKeyDown(getKeySetting("keymap_special1")) & 0x1) << 5) |
2337 (((int)input->isKeyDown(getKeySetting("keymap_sneak")) & 0x1) << 6) |
2338 (((int)input->getLeftState() & 0x1) << 7) |
2339 (((int)input->getRightState() & 0x1) << 8);
2343 Run server, client (and process environments)
2345 bool can_be_and_is_paused =
2346 (simple_singleplayer_mode && g_menumgr.pausesGame());
2347 if(can_be_and_is_paused)
2356 //TimeTaker timer("server->step(dtime)");
2357 server->step(dtime);
2360 //TimeTaker timer("client.step(dtime)");
2366 // Read client events
2369 ClientEvent event = client.getClientEvent();
2370 if(event.type == CE_NONE)
2374 else if(event.type == CE_PLAYER_DAMAGE &&
2375 client.getHP() != 0)
2377 //u16 damage = event.player_damage.amount;
2378 //infostream<<"Player damage: "<<damage<<std::endl;
2380 damage_flash += 100.0;
2381 damage_flash += 8.0 * event.player_damage.amount;
2383 player->hurt_tilt_timer = 1.5;
2384 player->hurt_tilt_strength = event.player_damage.amount/2;
2385 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2387 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2388 gamedef->event()->put(e);
2390 else if(event.type == CE_PLAYER_FORCE_MOVE)
2392 camera_yaw = event.player_force_move.yaw;
2393 camera_pitch = event.player_force_move.pitch;
2395 else if(event.type == CE_DEATHSCREEN)
2397 show_deathscreen(¤t_formspec, &client, gamedef, tsrc,
2400 chat_backend.addMessage(L"", L"You died.");
2402 /* Handle visualization */
2405 LocalPlayer* player = client.getEnv().getLocalPlayer();
2406 player->hurt_tilt_timer = 0;
2407 player->hurt_tilt_strength = 0;
2410 else if (event.type == CE_SHOW_FORMSPEC)
2412 FormspecFormSource* fs_src =
2413 new FormspecFormSource(*(event.show_formspec.formspec));
2414 TextDestPlayerInventory* txt_dst =
2415 new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2417 create_formspec_menu(¤t_formspec, &client, gamedef,
2418 tsrc, device, fs_src, txt_dst);
2420 delete(event.show_formspec.formspec);
2421 delete(event.show_formspec.formname);
2423 else if(event.type == CE_SPAWN_PARTICLE)
2425 LocalPlayer* player = client.getEnv().getLocalPlayer();
2426 video::ITexture *texture =
2427 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2429 new Particle(gamedef, smgr, player, client.getEnv(),
2430 *event.spawn_particle.pos,
2431 *event.spawn_particle.vel,
2432 *event.spawn_particle.acc,
2433 event.spawn_particle.expirationtime,
2434 event.spawn_particle.size,
2435 event.spawn_particle.collisiondetection,
2436 event.spawn_particle.vertical,
2441 else if(event.type == CE_ADD_PARTICLESPAWNER)
2443 LocalPlayer* player = client.getEnv().getLocalPlayer();
2444 video::ITexture *texture =
2445 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2447 new ParticleSpawner(gamedef, smgr, player,
2448 event.add_particlespawner.amount,
2449 event.add_particlespawner.spawntime,
2450 *event.add_particlespawner.minpos,
2451 *event.add_particlespawner.maxpos,
2452 *event.add_particlespawner.minvel,
2453 *event.add_particlespawner.maxvel,
2454 *event.add_particlespawner.minacc,
2455 *event.add_particlespawner.maxacc,
2456 event.add_particlespawner.minexptime,
2457 event.add_particlespawner.maxexptime,
2458 event.add_particlespawner.minsize,
2459 event.add_particlespawner.maxsize,
2460 event.add_particlespawner.collisiondetection,
2461 event.add_particlespawner.vertical,
2463 event.add_particlespawner.id);
2465 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2467 delete_particlespawner (event.delete_particlespawner.id);
2469 else if (event.type == CE_HUDADD)
2471 u32 id = event.hudadd.id;
2472 size_t nhudelem = player->hud.size();
2473 if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2474 delete event.hudadd.pos;
2475 delete event.hudadd.name;
2476 delete event.hudadd.scale;
2477 delete event.hudadd.text;
2478 delete event.hudadd.align;
2479 delete event.hudadd.offset;
2480 delete event.hudadd.world_pos;
2484 HudElement *e = new HudElement;
2485 e->type = (HudElementType)event.hudadd.type;
2486 e->pos = *event.hudadd.pos;
2487 e->name = *event.hudadd.name;
2488 e->scale = *event.hudadd.scale;
2489 e->text = *event.hudadd.text;
2490 e->number = event.hudadd.number;
2491 e->item = event.hudadd.item;
2492 e->dir = event.hudadd.dir;
2493 e->align = *event.hudadd.align;
2494 e->offset = *event.hudadd.offset;
2495 e->world_pos = *event.hudadd.world_pos;
2498 player->hud.push_back(e);
2500 player->hud[id] = e;
2502 delete event.hudadd.pos;
2503 delete event.hudadd.name;
2504 delete event.hudadd.scale;
2505 delete event.hudadd.text;
2506 delete event.hudadd.align;
2507 delete event.hudadd.offset;
2508 delete event.hudadd.world_pos;
2510 else if (event.type == CE_HUDRM)
2512 u32 id = event.hudrm.id;
2513 if (id < player->hud.size() && player->hud[id]) {
2514 delete player->hud[id];
2515 player->hud[id] = NULL;
2518 else if (event.type == CE_HUDCHANGE)
2520 u32 id = event.hudchange.id;
2521 if (id >= player->hud.size() || !player->hud[id]) {
2522 delete event.hudchange.v3fdata;
2523 delete event.hudchange.v2fdata;
2524 delete event.hudchange.sdata;
2528 HudElement* e = player->hud[id];
2529 switch (event.hudchange.stat) {
2531 e->pos = *event.hudchange.v2fdata;
2534 e->name = *event.hudchange.sdata;
2536 case HUD_STAT_SCALE:
2537 e->scale = *event.hudchange.v2fdata;
2540 e->text = *event.hudchange.sdata;
2542 case HUD_STAT_NUMBER:
2543 e->number = event.hudchange.data;
2546 e->item = event.hudchange.data;
2549 e->dir = event.hudchange.data;
2551 case HUD_STAT_ALIGN:
2552 e->align = *event.hudchange.v2fdata;
2554 case HUD_STAT_OFFSET:
2555 e->offset = *event.hudchange.v2fdata;
2557 case HUD_STAT_WORLD_POS:
2558 e->world_pos = *event.hudchange.v3fdata;
2562 delete event.hudchange.v3fdata;
2563 delete event.hudchange.v2fdata;
2564 delete event.hudchange.sdata;
2566 else if (event.type == CE_SET_SKY)
2568 sky->setVisible(false);
2573 // Handle according to type
2574 if(*event.set_sky.type == "regular"){
2575 sky->setVisible(true);
2577 else if(*event.set_sky.type == "skybox" &&
2578 event.set_sky.params->size() == 6){
2579 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2580 skybox = smgr->addSkyBoxSceneNode(
2581 tsrc->getTexture((*event.set_sky.params)[0]),
2582 tsrc->getTexture((*event.set_sky.params)[1]),
2583 tsrc->getTexture((*event.set_sky.params)[2]),
2584 tsrc->getTexture((*event.set_sky.params)[3]),
2585 tsrc->getTexture((*event.set_sky.params)[4]),
2586 tsrc->getTexture((*event.set_sky.params)[5]));
2588 // Handle everything else as plain color
2590 if(*event.set_sky.type != "plain")
2591 infostream<<"Unknown sky type: "
2592 <<(*event.set_sky.type)<<std::endl;
2593 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2596 delete event.set_sky.bgcolor;
2597 delete event.set_sky.type;
2598 delete event.set_sky.params;
2600 else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO)
2602 bool enable = event.override_day_night_ratio.do_override;
2603 u32 value = event.override_day_night_ratio.ratio_f * 1000;
2604 client.getEnv().setDayNightRatioOverride(enable, value);
2609 //TimeTaker //timer2("//timer2");
2612 For interaction purposes, get info about the held item
2614 - Is it a usable item?
2615 - Can it point to liquids?
2617 ItemStack playeritem;
2619 InventoryList *mlist = local_inventory.getList("main");
2622 playeritem = mlist->getItem(client.getPlayerItem());
2625 const ItemDefinition &playeritem_def =
2626 playeritem.getDefinition(itemdef);
2627 ToolCapabilities playeritem_toolcap =
2628 playeritem.getToolCapabilities(itemdef);
2634 v3s16 old_camera_offset = camera.getOffset();
2636 LocalPlayer* player = client.getEnv().getLocalPlayer();
2637 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2638 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2640 if(input->wasKeyDown(getKeySetting("keymap_camera_mode"))) {
2642 if (current_camera_mode == CAMERA_MODE_FIRST)
2643 current_camera_mode = CAMERA_MODE_THIRD;
2644 else if (current_camera_mode == CAMERA_MODE_THIRD)
2645 current_camera_mode = CAMERA_MODE_THIRD_FRONT;
2647 current_camera_mode = CAMERA_MODE_FIRST;
2650 player->camera_mode = current_camera_mode;
2651 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2652 camera.update(player, dtime, busytime, tool_reload_ratio,
2653 current_camera_mode, client.getEnv());
2656 v3f player_position = player->getPosition();
2657 v3f camera_position = camera.getPosition();
2658 v3f camera_direction = camera.getDirection();
2659 f32 camera_fov = camera.getFovMax();
2660 v3s16 camera_offset = camera.getOffset();
2662 bool camera_offset_changed = (camera_offset != old_camera_offset);
2664 if(!disable_camera_update){
2665 client.getEnv().getClientMap().updateCamera(camera_position,
2666 camera_direction, camera_fov, camera_offset);
2667 if (camera_offset_changed){
2668 client.updateCameraOffset(camera_offset);
2669 client.getEnv().updateCameraOffset(camera_offset);
2671 clouds->updateCameraOffset(camera_offset);
2675 // Update sound listener
2676 sound->updateListener(camera.getCameraNode()->getPosition()+intToFloat(camera_offset, BS),
2677 v3f(0,0,0), // velocity
2678 camera.getDirection(),
2679 camera.getCameraNode()->getUpVector());
2680 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2686 soundmaker.step(dtime);
2688 ClientMap &map = client.getEnv().getClientMap();
2689 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2690 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2694 Calculate what block is the crosshair pointing to
2697 //u32 t1 = device->getTimer()->getRealTime();
2699 f32 d = playeritem_def.range; // max. distance
2700 f32 d_hand = itemdef->get("").range;
2701 if(d < 0 && d_hand >= 0)
2705 core::line3d<f32> shootline(camera_position,
2706 camera_position + camera_direction * BS * (d+1));
2708 // prevent player pointing anything in front-view
2709 if (current_camera_mode == CAMERA_MODE_THIRD_FRONT)
2710 shootline = core::line3d<f32>(0,0,0,0,0,0);
2712 ClientActiveObject *selected_object = NULL;
2714 PointedThing pointed = getPointedThing(
2716 &client, player_position, camera_direction,
2717 camera_position, shootline, d,
2718 playeritem_def.liquids_pointable, !ldown_for_dig,
2724 if(pointed != pointed_old)
2726 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2727 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2732 - releasing left mouse button
2733 - pointing away from node
2737 if(input->getLeftReleased())
2739 infostream<<"Left button released"
2740 <<" (stopped digging)"<<std::endl;
2743 else if(pointed != pointed_old)
2745 if (pointed.type == POINTEDTHING_NODE
2746 && pointed_old.type == POINTEDTHING_NODE
2747 && pointed.node_undersurface == pointed_old.node_undersurface)
2749 // Still pointing to the same node,
2750 // but a different face. Don't reset.
2754 infostream<<"Pointing away from node"
2755 <<" (stopped digging)"<<std::endl;
2761 client.interact(1, pointed_old);
2762 client.setCrack(-1, v3s16(0,0,0));
2766 if(!digging && ldown_for_dig && !input->getLeftState())
2768 ldown_for_dig = false;
2771 bool left_punch = false;
2772 soundmaker.m_player_leftpunch_sound.name = "";
2774 if(input->getRightState())
2775 repeat_rightclick_timer += dtime;
2777 repeat_rightclick_timer = 0;
2779 if(playeritem_def.usable && input->getLeftState())
2781 if(input->getLeftClicked())
2782 client.interact(4, pointed);
2784 else if(pointed.type == POINTEDTHING_NODE)
2786 v3s16 nodepos = pointed.node_undersurface;
2787 v3s16 neighbourpos = pointed.node_abovesurface;
2790 Check information text of node
2793 ClientMap &map = client.getEnv().getClientMap();
2794 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2796 infotext = narrow_to_wide(meta->getString("infotext"));
2798 MapNode n = map.getNode(nodepos);
2799 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2800 infotext = L"Unknown node: ";
2801 infotext += narrow_to_wide(nodedef->get(n).name);
2809 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2810 && client.checkPrivilege("interact"))
2814 infostream<<"Started digging"<<std::endl;
2815 client.interact(0, pointed);
2817 ldown_for_dig = true;
2819 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2821 // NOTE: Similar piece of code exists on the server side for
2823 // Get digging parameters
2824 DigParams params = getDigParams(nodedef->get(n).groups,
2825 &playeritem_toolcap);
2826 // If can't dig, try hand
2827 if(!params.diggable){
2828 const ItemDefinition &hand = itemdef->get("");
2829 const ToolCapabilities *tp = hand.tool_capabilities;
2831 params = getDigParams(nodedef->get(n).groups, tp);
2834 float dig_time_complete = 0.0;
2836 if(params.diggable == false)
2838 // I guess nobody will wait for this long
2839 dig_time_complete = 10000000.0;
2843 dig_time_complete = params.time;
2844 if (g_settings->getBool("enable_particles"))
2846 const ContentFeatures &features =
2847 client.getNodeDefManager()->get(n);
2848 addPunchingParticles
2849 (gamedef, smgr, player, client.getEnv(),
2850 nodepos, features.tiles);
2854 if(dig_time_complete >= 0.001)
2856 dig_index = (u16)((float)crack_animation_length
2857 * dig_time/dig_time_complete);
2859 // This is for torches
2862 dig_index = crack_animation_length;
2865 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2866 if(sound_dig.exists() && params.diggable){
2867 if(sound_dig.name == "__group"){
2868 if(params.main_group != ""){
2869 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2870 soundmaker.m_player_leftpunch_sound.name =
2871 std::string("default_dig_") +
2875 soundmaker.m_player_leftpunch_sound = sound_dig;
2879 // Don't show cracks if not diggable
2880 if(dig_time_complete >= 100000.0)
2883 else if(dig_index < crack_animation_length)
2885 //TimeTaker timer("client.setTempMod");
2886 //infostream<<"dig_index="<<dig_index<<std::endl;
2887 client.setCrack(dig_index, nodepos);
2891 infostream<<"Digging completed"<<std::endl;
2892 client.interact(2, pointed);
2893 client.setCrack(-1, v3s16(0,0,0));
2894 MapNode wasnode = map.getNode(nodepos);
2895 client.removeNode(nodepos);
2897 if (g_settings->getBool("enable_particles"))
2899 const ContentFeatures &features =
2900 client.getNodeDefManager()->get(wasnode);
2902 (gamedef, smgr, player, client.getEnv(),
2903 nodepos, features.tiles);
2909 nodig_delay_timer = dig_time_complete
2910 / (float)crack_animation_length;
2912 // We don't want a corresponding delay to
2913 // very time consuming nodes
2914 if(nodig_delay_timer > 0.3)
2915 nodig_delay_timer = 0.3;
2916 // We want a slight delay to very little
2917 // time consuming nodes
2918 float mindelay = 0.15;
2919 if(nodig_delay_timer < mindelay)
2920 nodig_delay_timer = mindelay;
2922 // Send event to trigger sound
2923 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2924 gamedef->event()->put(e);
2927 if(dig_time_complete < 100000.0)
2931 client.setCrack(-1, nodepos);
2934 camera.setDigging(0); // left click animation
2937 if((input->getRightClicked() ||
2938 repeat_rightclick_timer >=
2939 g_settings->getFloat("repeat_rightclick_time")) &&
2940 client.checkPrivilege("interact"))
2942 repeat_rightclick_timer = 0;
2943 infostream<<"Ground right-clicked"<<std::endl;
2945 // Sign special case, at least until formspec is properly implemented.
2947 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2949 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2951 infostream<<"Launching metadata text input"<<std::endl;
2953 // Get a new text for it
2955 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2957 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2959 (new GUITextInputMenu(guienv, guiroot, -1,
2963 // If metadata provides an inventory view, activate it
2964 else if(meta && meta->getString("formspec") != "" && !random_input
2965 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2967 infostream<<"Launching custom inventory view"<<std::endl;
2969 InventoryLocation inventoryloc;
2970 inventoryloc.setNodeMeta(nodepos);
2972 NodeMetadataFormSource* fs_src = new NodeMetadataFormSource(
2973 &client.getEnv().getClientMap(), nodepos);
2974 TextDest* txt_dst = new TextDestNodeMetadata(nodepos, &client);
2976 create_formspec_menu(¤t_formspec, &client, gamedef,
2977 tsrc, device, fs_src, txt_dst);
2979 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
2981 // Otherwise report right click to server
2984 camera.setDigging(1); // right click animation (always shown for feedback)
2986 // If the wielded item has node placement prediction,
2988 bool placed = nodePlacementPrediction(client,
2990 nodepos, neighbourpos);
2994 client.interact(3, pointed);
2996 soundmaker.m_player_rightpunch_sound =
2997 playeritem_def.sound_place;
2999 soundmaker.m_player_rightpunch_sound =
3003 if (playeritem_def.node_placement_prediction == "" ||
3004 nodedef->get(map.getNode(nodepos)).rightclickable)
3005 client.interact(3, pointed); // Report to server
3009 else if(pointed.type == POINTEDTHING_OBJECT)
3011 infotext = narrow_to_wide(selected_object->infoText());
3013 if(infotext == L"" && show_debug){
3014 infotext = narrow_to_wide(selected_object->debugInfoText());
3017 //if(input->getLeftClicked())
3018 if(input->getLeftState())
3020 bool do_punch = false;
3021 bool do_punch_damage = false;
3022 if(object_hit_delay_timer <= 0.0){
3024 do_punch_damage = true;
3025 object_hit_delay_timer = object_hit_delay;
3027 if(input->getLeftClicked()){
3031 infostream<<"Left-clicked object"<<std::endl;
3034 if(do_punch_damage){
3035 // Report direct punch
3036 v3f objpos = selected_object->getPosition();
3037 v3f dir = (objpos - player_position).normalize();
3039 bool disable_send = selected_object->directReportPunch(
3040 dir, &playeritem, time_from_last_punch);
3041 time_from_last_punch = 0;
3043 client.interact(0, pointed);
3046 else if(input->getRightClicked())
3048 infostream<<"Right-clicked object"<<std::endl;
3049 client.interact(3, pointed); // place
3052 else if(input->getLeftState())
3054 // When button is held down in air, show continuous animation
3058 pointed_old = pointed;
3060 if(left_punch || input->getLeftClicked())
3062 camera.setDigging(0); // left click animation
3065 input->resetLeftClicked();
3066 input->resetRightClicked();
3068 input->resetLeftReleased();
3069 input->resetRightReleased();
3072 Calculate stuff for drawing
3079 if(draw_control.range_all)
3080 fog_range = 100000*BS;
3082 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
3083 fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
3088 Calculate general brightness
3090 u32 daynight_ratio = client.getEnv().getDayNightRatio();
3091 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
3092 float direct_brightness = 0;
3093 bool sunlight_seen = false;
3094 if(g_settings->getBool("free_move")){
3095 direct_brightness = time_brightness;
3096 sunlight_seen = true;
3098 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3099 float old_brightness = sky->getBrightness();
3100 direct_brightness = (float)client.getEnv().getClientMap()
3101 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
3102 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
3106 time_of_day = client.getEnv().getTimeOfDayF();
3108 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
3109 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3110 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3111 time_of_day_smooth = time_of_day;
3113 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
3114 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3115 + (time_of_day+1.0) * todsm;
3117 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3118 + time_of_day * todsm;
3120 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3123 video::SColor bgcolor = sky->getBgColor();
3124 video::SColor skycolor = sky->getSkyColor();
3130 if(sky->getCloudsVisible()){
3131 clouds->setVisible(true);
3132 clouds->step(dtime);
3133 clouds->update(v2f(player_position.X, player_position.Z),
3134 sky->getCloudColor());
3136 clouds->setVisible(false);
3144 allparticles_step(dtime);
3145 allparticlespawners_step(dtime, client.getEnv());
3151 if(g_settings->getBool("enable_fog") && !force_fog_off)
3155 video::EFT_FOG_LINEAR,
3167 video::EFT_FOG_LINEAR,
3177 Update gui stuff (0ms)
3180 //TimeTaker guiupdatetimer("Gui updating");
3184 static float drawtime_avg = 0;
3185 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3186 /*static float beginscenetime_avg = 0;
3187 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3188 static float scenetime_avg = 0;
3189 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3190 static float endscenetime_avg = 0;
3191 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3193 u16 fps = (1.0/dtime_avg1);
3195 std::ostringstream os(std::ios_base::binary);
3197 <<"Minetest "<<minetest_version_hash
3199 <<" (R: range_all="<<draw_control.range_all<<")"
3200 <<std::setprecision(0)
3201 <<" drawtime = "<<drawtime_avg
3202 <<std::setprecision(1)
3203 <<", dtime_jitter = "
3204 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3205 <<std::setprecision(1)
3206 <<", v_range = "<<draw_control.wanted_range
3207 <<std::setprecision(3)
3208 <<", RTT = "<<client.getRTT();
3209 guitext->setText(narrow_to_wide(os.str()).c_str());
3210 guitext->setVisible(true);
3212 else if(show_hud || show_chat)
3214 std::ostringstream os(std::ios_base::binary);
3215 os<<"Minetest "<<minetest_version_hash;
3216 guitext->setText(narrow_to_wide(os.str()).c_str());
3217 guitext->setVisible(true);
3221 guitext->setVisible(false);
3224 if (guitext->isVisible())
3226 core::rect<s32> rect(
3232 guitext->setRelativePosition(rect);
3237 std::ostringstream os(std::ios_base::binary);
3238 os<<std::setprecision(1)<<std::fixed
3239 <<"(" <<(player_position.X/BS)
3240 <<", "<<(player_position.Y/BS)
3241 <<", "<<(player_position.Z/BS)
3242 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3243 <<") (seed = "<<((u64)client.getMapSeed())
3245 guitext2->setText(narrow_to_wide(os.str()).c_str());
3246 guitext2->setVisible(true);
3248 core::rect<s32> rect(
3252 5 + (text_height * 2)
3254 guitext2->setRelativePosition(rect);
3258 guitext2->setVisible(false);
3262 guitext_info->setText(infotext.c_str());
3263 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3267 float statustext_time_max = 1.5;
3268 if(!statustext.empty())
3270 statustext_time += dtime;
3271 if(statustext_time >= statustext_time_max)
3274 statustext_time = 0;
3277 guitext_status->setText(statustext.c_str());
3278 guitext_status->setVisible(!statustext.empty());
3280 if(!statustext.empty())
3282 s32 status_y = screensize.Y - 130;
3283 core::rect<s32> rect(
3285 status_y - guitext_status->getTextHeight(),
3289 guitext_status->setRelativePosition(rect);
3292 video::SColor initial_color(255,0,0,0);
3293 if(guienv->getSkin())
3294 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3295 video::SColor final_color = initial_color;
3296 final_color.setAlpha(0);
3297 video::SColor fade_color =
3298 initial_color.getInterpolated_quadratic(
3301 pow(statustext_time / (float)statustext_time_max, 2.0f));
3302 guitext_status->setOverrideColor(fade_color);
3303 guitext_status->enableOverrideColor(true);
3308 Get chat messages from client
3311 // Get new messages from error log buffer
3312 while(!chat_log_error_buf.empty())
3314 chat_backend.addMessage(L"", narrow_to_wide(
3315 chat_log_error_buf.get()));
3317 // Get new messages from client
3318 std::wstring message;
3319 while(client.getChatMessage(message))
3321 chat_backend.addUnparsedMessage(message);
3323 // Remove old messages
3324 chat_backend.step(dtime);
3326 // Display all messages in a static text element
3327 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3328 std::wstring recent_chat = chat_backend.getRecentChat();
3329 guitext_chat->setText(recent_chat.c_str());
3331 // Update gui element size and position
3332 s32 chat_y = 5+(text_height+5);
3334 chat_y += (text_height+5);
3335 core::rect<s32> rect(
3339 chat_y + guitext_chat->getTextHeight()
3341 guitext_chat->setRelativePosition(rect);
3343 // Don't show chat if disabled or empty or profiler is enabled
3344 guitext_chat->setVisible(show_chat && recent_chat_count != 0
3352 if(client.getPlayerItem() != new_playeritem)
3354 client.selectPlayerItem(new_playeritem);
3356 if(client.getLocalInventoryUpdated())
3358 //infostream<<"Updating local inventory"<<std::endl;
3359 client.getLocalInventory(local_inventory);
3361 update_wielded_item_trigger = true;
3363 if(update_wielded_item_trigger)
3365 update_wielded_item_trigger = false;
3366 // Update wielded tool
3367 InventoryList *mlist = local_inventory.getList("main");
3370 item = mlist->getItem(client.getPlayerItem());
3371 camera.wield(item, client.getPlayerItem());
3375 Update block draw list every 200ms or when camera direction has
3378 update_draw_list_timer += dtime;
3379 if(update_draw_list_timer >= 0.2 ||
3380 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 ||
3381 camera_offset_changed){
3382 update_draw_list_timer = 0;
3383 client.getEnv().getClientMap().updateDrawList(driver);
3384 update_draw_list_last_cam_dir = camera_direction;
3391 TimeTaker tt_draw("mainloop: draw");
3394 TimeTaker timer("beginScene");
3395 //driver->beginScene(false, true, bgcolor);
3396 //driver->beginScene(true, true, bgcolor);
3397 driver->beginScene(true, true, skycolor);
3398 beginscenetime = timer.stop(true);
3403 //infostream<<"smgr->drawAll()"<<std::endl;
3405 TimeTaker timer("smgr");
3408 if(g_settings->getBool("anaglyph"))
3410 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3411 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
3413 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
3415 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
3416 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3417 camera.getCameraNode()->getAbsolutePosition() ;
3420 irr::core::vector3df leftEye;
3421 irr::core::matrix4 leftMove;
3423 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3424 leftEye=(startMatrix*leftMove).getTranslation();
3426 //clear the depth buffer, and color
3427 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3429 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3430 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3431 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3432 irr::scene::ESNRP_SOLID +
3433 irr::scene::ESNRP_TRANSPARENT +
3434 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3435 irr::scene::ESNRP_SHADOW;
3437 camera.getCameraNode()->setPosition( leftEye );
3438 camera.getCameraNode()->setTarget( focusPoint );
3440 smgr->drawAll(); // 'smgr->drawAll();' may go here
3442 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3445 hud.drawSelectionBoxes(hilightboxes);
3449 irr::core::vector3df rightEye;
3450 irr::core::matrix4 rightMove;
3452 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3453 rightEye=(startMatrix*rightMove).getTranslation();
3455 //clear the depth buffer
3456 driver->clearZBuffer();
3458 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3459 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3460 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3461 irr::scene::ESNRP_SOLID +
3462 irr::scene::ESNRP_TRANSPARENT +
3463 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3464 irr::scene::ESNRP_SHADOW;
3466 camera.getCameraNode()->setPosition( rightEye );
3467 camera.getCameraNode()->setTarget( focusPoint );
3469 smgr->drawAll(); // 'smgr->drawAll();' may go here
3471 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3474 hud.drawSelectionBoxes(hilightboxes);
3477 //driver->endScene();
3479 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3480 driver->getOverrideMaterial().EnableFlags=0;
3481 driver->getOverrideMaterial().EnablePasses=0;
3483 camera.getCameraNode()->setPosition( oldPosition );
3484 camera.getCameraNode()->setTarget( oldTarget );
3487 scenetime = timer.stop(true);
3491 //TimeTaker timer9("auxiliary drawings");
3495 //TimeTaker //timer10("//timer10");
3501 driver->setMaterial(m);
3503 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3504 if((!g_settings->getBool("anaglyph")) && (show_hud))
3506 hud.drawSelectionBoxes(hilightboxes);
3513 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3514 current_camera_mode < CAMERA_MODE_THIRD)
3516 // Warning: This clears the Z buffer.
3517 camera.drawWieldedTool();
3524 client.getEnv().getClientMap().renderPostFx();
3530 if(show_profiler_graph)
3532 graph.draw(10, screensize.Y - 10, driver, font);
3539 hud.drawCrosshair();
3544 //TimeTaker //timer11("//timer11");
3552 hud.drawHotbar(client.getHP(), client.getPlayerItem(),
3553 client.getBreath());
3559 if(damage_flash > 0.0)
3561 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3562 driver->draw2DRectangle(color,
3563 core::rect<s32>(0,0,screensize.X,screensize.Y),
3566 damage_flash -= 100.0*dtime;
3572 if(player->hurt_tilt_timer > 0.0)
3574 player->hurt_tilt_timer -= dtime*5;
3575 if(player->hurt_tilt_timer < 0)
3576 player->hurt_tilt_strength = 0;
3583 hud.drawLuaElements();
3595 TimeTaker timer("endScene");
3597 endscenetime = timer.stop(true);
3600 drawtime = tt_draw.stop(true);
3601 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3608 Log times and stuff for visualization
3610 Profiler::GraphValues values;
3611 g_profiler->graphGet(values);
3620 if (gui_chat_console)
3621 gui_chat_console->drop();
3627 Draw a "shutting down" screen, which will be shown while the map
3628 generator and other stuff quits
3631 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3632 wchar_t* text = wgettext("Shutting down stuff...");
3633 draw_load_screen(text, device, font, 0, -1, false);
3635 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3638 gui_shuttingdowntext->remove();*/
3641 chat_backend.addMessage(L"", L"# Disconnected.");
3642 chat_backend.addMessage(L"", L"");
3646 //force answer all texture and shader jobs (TODO return empty values)
3648 while(!client.isShutdown()) {
3649 tsrc->processQueue();
3650 shsrc->processQueue();
3654 // Client scope (client is destructed before destructing *def and tsrc)
3657 catch(SerializationError &e)
3659 error_message = L"A serialization error occurred:\n"
3660 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3661 L" running a different version of Minetest.";
3662 errorstream<<wide_to_narrow(error_message)<<std::endl;
3664 catch(ServerError &e) {
3665 error_message = narrow_to_wide(e.what());
3666 errorstream << "ServerError: " << e.what() << std::endl;
3668 catch(ModError &e) {
3669 errorstream << "ModError: " << e.what() << std::endl;
3670 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3678 //has to be deleted first to stop all server threads
3686 //extended resource accounting
3687 infostream << "Irrlicht resources after cleanup:" << std::endl;
3688 infostream << "\tRemaining meshes : "
3689 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3690 infostream << "\tRemaining textures : "
3691 << driver->getTextureCount() << std::endl;
3692 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3693 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3694 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3697 clearTextureNameCache();
3698 infostream << "\tRemaining materials: "
3699 << driver-> getMaterialRendererCount ()
3700 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;