game.cpp 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "game.h"
  17. #include <iomanip>
  18. #include <cmath>
  19. #include "client/renderingengine.h"
  20. #include "camera.h"
  21. #include "client.h"
  22. #include "client/clientevent.h"
  23. #include "client/gameui.h"
  24. #include "client/inputhandler.h"
  25. #include "client/tile.h" // For TextureSource
  26. #include "client/keys.h"
  27. #include "client/joystick_controller.h"
  28. #include "clientmap.h"
  29. #include "clouds.h"
  30. #include "config.h"
  31. #include "content_cao.h"
  32. #include "event_manager.h"
  33. #include "fontengine.h"
  34. #include "itemdef.h"
  35. #include "log.h"
  36. #include "filesys.h"
  37. #include "gettext.h"
  38. #include "gui/guiChatConsole.h"
  39. #include "gui/guiFormSpecMenu.h"
  40. #include "gui/guiKeyChangeMenu.h"
  41. #include "gui/guiPasswordChange.h"
  42. #include "gui/guiVolumeChange.h"
  43. #include "gui/mainmenumanager.h"
  44. #include "mapblock.h"
  45. #include "minimap.h"
  46. #include "nodedef.h" // Needed for determining pointing to nodes
  47. #include "nodemetadata.h"
  48. #include "particles.h"
  49. #include "profiler.h"
  50. #include "quicktune_shortcutter.h"
  51. #include "raycast.h"
  52. #include "server.h"
  53. #include "settings.h"
  54. #include "shader.h"
  55. #include "sky.h"
  56. #include "subgame.h"
  57. #include "tool.h"
  58. #include "translation.h"
  59. #include "util/basic_macros.h"
  60. #include "util/directiontables.h"
  61. #include "util/pointedthing.h"
  62. #include "irrlicht_changes/static_text.h"
  63. #include "version.h"
  64. #include "script/scripting_client.h"
  65. #if USE_SOUND
  66. #include "sound_openal.h"
  67. #endif
  68. /*
  69. Text input system
  70. */
  71. struct TextDestNodeMetadata : public TextDest
  72. {
  73. TextDestNodeMetadata(v3s16 p, Client *client)
  74. {
  75. m_p = p;
  76. m_client = client;
  77. }
  78. // This is deprecated I guess? -celeron55
  79. void gotText(const std::wstring &text)
  80. {
  81. std::string ntext = wide_to_utf8(text);
  82. infostream << "Submitting 'text' field of node at (" << m_p.X << ","
  83. << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
  84. StringMap fields;
  85. fields["text"] = ntext;
  86. m_client->sendNodemetaFields(m_p, "", fields);
  87. }
  88. void gotText(const StringMap &fields)
  89. {
  90. m_client->sendNodemetaFields(m_p, "", fields);
  91. }
  92. v3s16 m_p;
  93. Client *m_client;
  94. };
  95. struct TextDestPlayerInventory : public TextDest
  96. {
  97. TextDestPlayerInventory(Client *client)
  98. {
  99. m_client = client;
  100. m_formname = "";
  101. }
  102. TextDestPlayerInventory(Client *client, const std::string &formname)
  103. {
  104. m_client = client;
  105. m_formname = formname;
  106. }
  107. void gotText(const StringMap &fields)
  108. {
  109. m_client->sendInventoryFields(m_formname, fields);
  110. }
  111. Client *m_client;
  112. };
  113. struct LocalFormspecHandler : public TextDest
  114. {
  115. LocalFormspecHandler(const std::string &formname)
  116. {
  117. m_formname = formname;
  118. }
  119. LocalFormspecHandler(const std::string &formname, Client *client):
  120. m_client(client)
  121. {
  122. m_formname = formname;
  123. }
  124. void gotText(const StringMap &fields)
  125. {
  126. if (m_formname == "MT_PAUSE_MENU") {
  127. if (fields.find("btn_sound") != fields.end()) {
  128. g_gamecallback->changeVolume();
  129. return;
  130. }
  131. if (fields.find("btn_key_config") != fields.end()) {
  132. g_gamecallback->keyConfig();
  133. return;
  134. }
  135. if (fields.find("btn_exit_menu") != fields.end()) {
  136. g_gamecallback->disconnect();
  137. return;
  138. }
  139. if (fields.find("btn_exit_os") != fields.end()) {
  140. g_gamecallback->exitToOS();
  141. #ifndef __ANDROID__
  142. RenderingEngine::get_raw_device()->closeDevice();
  143. #endif
  144. return;
  145. }
  146. if (fields.find("btn_change_password") != fields.end()) {
  147. g_gamecallback->changePassword();
  148. return;
  149. }
  150. if (fields.find("quit") != fields.end()) {
  151. return;
  152. }
  153. if (fields.find("btn_continue") != fields.end()) {
  154. return;
  155. }
  156. }
  157. // Don't disable this part when modding is disabled, it's used in builtin
  158. if (m_client && m_client->getScript())
  159. m_client->getScript()->on_formspec_input(m_formname, fields);
  160. }
  161. Client *m_client = nullptr;
  162. };
  163. /* Form update callback */
  164. static const std::string empty_string = "";
  165. class NodeMetadataFormSource: public IFormSource
  166. {
  167. public:
  168. NodeMetadataFormSource(ClientMap *map, v3s16 p):
  169. m_map(map),
  170. m_p(p)
  171. {
  172. }
  173. const std::string &getForm() const
  174. {
  175. NodeMetadata *meta = m_map->getNodeMetadata(m_p);
  176. if (!meta)
  177. return empty_string;
  178. return meta->getString("formspec");
  179. }
  180. virtual std::string resolveText(const std::string &str)
  181. {
  182. NodeMetadata *meta = m_map->getNodeMetadata(m_p);
  183. if (!meta)
  184. return str;
  185. return meta->resolveString(str);
  186. }
  187. ClientMap *m_map;
  188. v3s16 m_p;
  189. };
  190. class PlayerInventoryFormSource: public IFormSource
  191. {
  192. public:
  193. PlayerInventoryFormSource(Client *client):
  194. m_client(client)
  195. {
  196. }
  197. const std::string &getForm() const
  198. {
  199. LocalPlayer *player = m_client->getEnv().getLocalPlayer();
  200. return player->inventory_formspec;
  201. }
  202. Client *m_client;
  203. };
  204. /* Profiler display */
  205. class ProfilerGraph
  206. {
  207. private:
  208. struct Piece {
  209. Profiler::GraphValues values;
  210. };
  211. struct Meta {
  212. float min;
  213. float max;
  214. video::SColor color;
  215. Meta(float initial = 0,
  216. video::SColor color = video::SColor(255, 255, 255, 255)):
  217. min(initial),
  218. max(initial),
  219. color(color)
  220. {}
  221. };
  222. std::deque<Piece> m_log;
  223. public:
  224. u32 m_log_max_size = 200;
  225. ProfilerGraph() = default;
  226. void put(const Profiler::GraphValues &values)
  227. {
  228. Piece piece;
  229. piece.values = values;
  230. m_log.push_back(piece);
  231. while (m_log.size() > m_log_max_size)
  232. m_log.erase(m_log.begin());
  233. }
  234. void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
  235. gui::IGUIFont *font) const
  236. {
  237. // Do *not* use UNORDERED_MAP here as the order needs
  238. // to be the same for each call to prevent flickering
  239. std::map<std::string, Meta> m_meta;
  240. for (const Piece &piece : m_log) {
  241. for (const auto &i : piece.values) {
  242. const std::string &id = i.first;
  243. const float &value = i.second;
  244. std::map<std::string, Meta>::iterator j = m_meta.find(id);
  245. if (j == m_meta.end()) {
  246. m_meta[id] = Meta(value);
  247. continue;
  248. }
  249. if (value < j->second.min)
  250. j->second.min = value;
  251. if (value > j->second.max)
  252. j->second.max = value;
  253. }
  254. }
  255. // Assign colors
  256. static const video::SColor usable_colors[] = {
  257. video::SColor(255, 255, 100, 100),
  258. video::SColor(255, 90, 225, 90),
  259. video::SColor(255, 100, 100, 255),
  260. video::SColor(255, 255, 150, 50),
  261. video::SColor(255, 220, 220, 100)
  262. };
  263. static const u32 usable_colors_count =
  264. sizeof(usable_colors) / sizeof(*usable_colors);
  265. u32 next_color_i = 0;
  266. for (auto &i : m_meta) {
  267. Meta &meta = i.second;
  268. video::SColor color(255, 200, 200, 200);
  269. if (next_color_i < usable_colors_count)
  270. color = usable_colors[next_color_i++];
  271. meta.color = color;
  272. }
  273. s32 graphh = 50;
  274. s32 textx = x_left + m_log_max_size + 15;
  275. s32 textx2 = textx + 200 - 15;
  276. s32 meta_i = 0;
  277. for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
  278. i != m_meta.end(); ++i) {
  279. const std::string &id = i->first;
  280. const Meta &meta = i->second;
  281. s32 x = x_left;
  282. s32 y = y_bottom - meta_i * 50;
  283. float show_min = meta.min;
  284. float show_max = meta.max;
  285. if (show_min >= -0.0001 && show_max >= -0.0001) {
  286. if (show_min <= show_max * 0.5)
  287. show_min = 0;
  288. }
  289. s32 texth = 15;
  290. char buf[10];
  291. snprintf(buf, 10, "%.3g", show_max);
  292. font->draw(utf8_to_wide(buf).c_str(),
  293. core::rect<s32>(textx, y - graphh,
  294. textx2, y - graphh + texth),
  295. meta.color);
  296. snprintf(buf, 10, "%.3g", show_min);
  297. font->draw(utf8_to_wide(buf).c_str(),
  298. core::rect<s32>(textx, y - texth,
  299. textx2, y),
  300. meta.color);
  301. font->draw(utf8_to_wide(id).c_str(),
  302. core::rect<s32>(textx, y - graphh / 2 - texth / 2,
  303. textx2, y - graphh / 2 + texth / 2),
  304. meta.color);
  305. s32 graph1y = y;
  306. s32 graph1h = graphh;
  307. bool relativegraph = (show_min != 0 && show_min != show_max);
  308. float lastscaledvalue = 0.0;
  309. bool lastscaledvalue_exists = false;
  310. for (const Piece &piece : m_log) {
  311. float value = 0;
  312. bool value_exists = false;
  313. Profiler::GraphValues::const_iterator k =
  314. piece.values.find(id);
  315. if (k != piece.values.end()) {
  316. value = k->second;
  317. value_exists = true;
  318. }
  319. if (!value_exists) {
  320. x++;
  321. lastscaledvalue_exists = false;
  322. continue;
  323. }
  324. float scaledvalue = 1.0;
  325. if (show_max != show_min)
  326. scaledvalue = (value - show_min) / (show_max - show_min);
  327. if (scaledvalue == 1.0 && value == 0) {
  328. x++;
  329. lastscaledvalue_exists = false;
  330. continue;
  331. }
  332. if (relativegraph) {
  333. if (lastscaledvalue_exists) {
  334. s32 ivalue1 = lastscaledvalue * graph1h;
  335. s32 ivalue2 = scaledvalue * graph1h;
  336. driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
  337. v2s32(x, graph1y - ivalue2), meta.color);
  338. }
  339. lastscaledvalue = scaledvalue;
  340. lastscaledvalue_exists = true;
  341. } else {
  342. s32 ivalue = scaledvalue * graph1h;
  343. driver->draw2DLine(v2s32(x, graph1y),
  344. v2s32(x, graph1y - ivalue), meta.color);
  345. }
  346. x++;
  347. }
  348. meta_i++;
  349. }
  350. }
  351. };
  352. class NodeDugEvent: public MtEvent
  353. {
  354. public:
  355. v3s16 p;
  356. MapNode n;
  357. NodeDugEvent(v3s16 p, MapNode n):
  358. p(p),
  359. n(n)
  360. {}
  361. const char *getType() const
  362. {
  363. return "NodeDug";
  364. }
  365. };
  366. class SoundMaker
  367. {
  368. ISoundManager *m_sound;
  369. INodeDefManager *m_ndef;
  370. public:
  371. bool makes_footstep_sound;
  372. float m_player_step_timer;
  373. SimpleSoundSpec m_player_step_sound;
  374. SimpleSoundSpec m_player_leftpunch_sound;
  375. SimpleSoundSpec m_player_rightpunch_sound;
  376. SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
  377. m_sound(sound),
  378. m_ndef(ndef),
  379. makes_footstep_sound(true),
  380. m_player_step_timer(0)
  381. {
  382. }
  383. void playPlayerStep()
  384. {
  385. if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
  386. m_player_step_timer = 0.03;
  387. if (makes_footstep_sound)
  388. m_sound->playSound(m_player_step_sound, false);
  389. }
  390. }
  391. static void viewBobbingStep(MtEvent *e, void *data)
  392. {
  393. SoundMaker *sm = (SoundMaker *)data;
  394. sm->playPlayerStep();
  395. }
  396. static void playerRegainGround(MtEvent *e, void *data)
  397. {
  398. SoundMaker *sm = (SoundMaker *)data;
  399. sm->playPlayerStep();
  400. }
  401. static void playerJump(MtEvent *e, void *data)
  402. {
  403. //SoundMaker *sm = (SoundMaker*)data;
  404. }
  405. static void cameraPunchLeft(MtEvent *e, void *data)
  406. {
  407. SoundMaker *sm = (SoundMaker *)data;
  408. sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
  409. }
  410. static void cameraPunchRight(MtEvent *e, void *data)
  411. {
  412. SoundMaker *sm = (SoundMaker *)data;
  413. sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
  414. }
  415. static void nodeDug(MtEvent *e, void *data)
  416. {
  417. SoundMaker *sm = (SoundMaker *)data;
  418. NodeDugEvent *nde = (NodeDugEvent *)e;
  419. sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
  420. }
  421. static void playerDamage(MtEvent *e, void *data)
  422. {
  423. SoundMaker *sm = (SoundMaker *)data;
  424. sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
  425. }
  426. static void playerFallingDamage(MtEvent *e, void *data)
  427. {
  428. SoundMaker *sm = (SoundMaker *)data;
  429. sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
  430. }
  431. void registerReceiver(MtEventManager *mgr)
  432. {
  433. mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
  434. mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
  435. mgr->reg("PlayerJump", SoundMaker::playerJump, this);
  436. mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
  437. mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
  438. mgr->reg("NodeDug", SoundMaker::nodeDug, this);
  439. mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
  440. mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
  441. }
  442. void step(float dtime)
  443. {
  444. m_player_step_timer -= dtime;
  445. }
  446. };
  447. // Locally stored sounds don't need to be preloaded because of this
  448. class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
  449. {
  450. std::set<std::string> m_fetched;
  451. private:
  452. void paths_insert(std::set<std::string> &dst_paths,
  453. const std::string &base,
  454. const std::string &name)
  455. {
  456. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
  457. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
  458. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
  459. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
  460. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
  461. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
  462. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
  463. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
  464. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
  465. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
  466. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
  467. }
  468. public:
  469. void fetchSounds(const std::string &name,
  470. std::set<std::string> &dst_paths,
  471. std::set<std::string> &dst_datas)
  472. {
  473. if (m_fetched.count(name))
  474. return;
  475. m_fetched.insert(name);
  476. paths_insert(dst_paths, porting::path_share, name);
  477. paths_insert(dst_paths, porting::path_user, name);
  478. }
  479. };
  480. // before 1.8 there isn't a "integer interface", only float
  481. #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
  482. typedef f32 SamplerLayer_t;
  483. #else
  484. typedef s32 SamplerLayer_t;
  485. #endif
  486. class GameGlobalShaderConstantSetter : public IShaderConstantSetter
  487. {
  488. Sky *m_sky;
  489. bool *m_force_fog_off;
  490. f32 *m_fog_range;
  491. bool m_fog_enabled;
  492. CachedPixelShaderSetting<float, 4> m_sky_bg_color;
  493. CachedPixelShaderSetting<float> m_fog_distance;
  494. CachedVertexShaderSetting<float> m_animation_timer_vertex;
  495. CachedPixelShaderSetting<float> m_animation_timer_pixel;
  496. CachedPixelShaderSetting<float, 3> m_day_light;
  497. CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
  498. CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
  499. CachedPixelShaderSetting<float, 3> m_minimap_yaw;
  500. CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
  501. CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
  502. CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
  503. Client *m_client;
  504. public:
  505. void onSettingsChange(const std::string &name)
  506. {
  507. if (name == "enable_fog")
  508. m_fog_enabled = g_settings->getBool("enable_fog");
  509. }
  510. static void settingsCallback(const std::string &name, void *userdata)
  511. {
  512. reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
  513. }
  514. void setSky(Sky *sky) { m_sky = sky; }
  515. GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
  516. f32 *fog_range, Client *client) :
  517. m_sky(sky),
  518. m_force_fog_off(force_fog_off),
  519. m_fog_range(fog_range),
  520. m_sky_bg_color("skyBgColor"),
  521. m_fog_distance("fogDistance"),
  522. m_animation_timer_vertex("animationTimer"),
  523. m_animation_timer_pixel("animationTimer"),
  524. m_day_light("dayLight"),
  525. m_eye_position_pixel("eyePosition"),
  526. m_eye_position_vertex("eyePosition"),
  527. m_minimap_yaw("yawVec"),
  528. m_base_texture("baseTexture"),
  529. m_normal_texture("normalTexture"),
  530. m_texture_flags("textureFlags"),
  531. m_client(client)
  532. {
  533. g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
  534. m_fog_enabled = g_settings->getBool("enable_fog");
  535. }
  536. ~GameGlobalShaderConstantSetter()
  537. {
  538. g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
  539. }
  540. virtual void onSetConstants(video::IMaterialRendererServices *services,
  541. bool is_highlevel)
  542. {
  543. if (!is_highlevel)
  544. return;
  545. // Background color
  546. video::SColor bgcolor = m_sky->getBgColor();
  547. video::SColorf bgcolorf(bgcolor);
  548. float bgcolorfa[4] = {
  549. bgcolorf.r,
  550. bgcolorf.g,
  551. bgcolorf.b,
  552. bgcolorf.a,
  553. };
  554. m_sky_bg_color.set(bgcolorfa, services);
  555. // Fog distance
  556. float fog_distance = 10000 * BS;
  557. if (m_fog_enabled && !*m_force_fog_off)
  558. fog_distance = *m_fog_range;
  559. m_fog_distance.set(&fog_distance, services);
  560. u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
  561. video::SColorf sunlight;
  562. get_sunlight_color(&sunlight, daynight_ratio);
  563. float dnc[3] = {
  564. sunlight.r,
  565. sunlight.g,
  566. sunlight.b };
  567. m_day_light.set(dnc, services);
  568. u32 animation_timer = porting::getTimeMs() % 100000;
  569. float animation_timer_f = (float)animation_timer / 100000.f;
  570. m_animation_timer_vertex.set(&animation_timer_f, services);
  571. m_animation_timer_pixel.set(&animation_timer_f, services);
  572. float eye_position_array[3];
  573. v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
  574. #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
  575. eye_position_array[0] = epos.X;
  576. eye_position_array[1] = epos.Y;
  577. eye_position_array[2] = epos.Z;
  578. #else
  579. epos.getAs3Values(eye_position_array);
  580. #endif
  581. m_eye_position_pixel.set(eye_position_array, services);
  582. m_eye_position_vertex.set(eye_position_array, services);
  583. if (m_client->getMinimap()) {
  584. float minimap_yaw_array[3];
  585. v3f minimap_yaw = m_client->getMinimap()->getYawVec();
  586. #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
  587. minimap_yaw_array[0] = minimap_yaw.X;
  588. minimap_yaw_array[1] = minimap_yaw.Y;
  589. minimap_yaw_array[2] = minimap_yaw.Z;
  590. #else
  591. minimap_yaw.getAs3Values(minimap_yaw_array);
  592. #endif
  593. m_minimap_yaw.set(minimap_yaw_array, services);
  594. }
  595. SamplerLayer_t base_tex = 0,
  596. normal_tex = 1,
  597. flags_tex = 2;
  598. m_base_texture.set(&base_tex, services);
  599. m_normal_texture.set(&normal_tex, services);
  600. m_texture_flags.set(&flags_tex, services);
  601. }
  602. };
  603. class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
  604. {
  605. Sky *m_sky;
  606. bool *m_force_fog_off;
  607. f32 *m_fog_range;
  608. Client *m_client;
  609. std::vector<GameGlobalShaderConstantSetter *> created_nosky;
  610. public:
  611. GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
  612. f32 *fog_range, Client *client) :
  613. m_sky(NULL),
  614. m_force_fog_off(force_fog_off),
  615. m_fog_range(fog_range),
  616. m_client(client)
  617. {}
  618. void setSky(Sky *sky) {
  619. m_sky = sky;
  620. for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
  621. ggscs->setSky(m_sky);
  622. }
  623. created_nosky.clear();
  624. }
  625. virtual IShaderConstantSetter* create()
  626. {
  627. GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
  628. m_sky, m_force_fog_off, m_fog_range, m_client);
  629. if (!m_sky)
  630. created_nosky.push_back(scs);
  631. return scs;
  632. }
  633. };
  634. bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_def,
  635. const ItemStack &playeritem, v3s16 nodepos, v3s16 neighbourpos)
  636. {
  637. std::string prediction = playeritem_def.node_placement_prediction;
  638. INodeDefManager *nodedef = client.ndef();
  639. ClientMap &map = client.getEnv().getClientMap();
  640. MapNode node;
  641. bool is_valid_position;
  642. node = map.getNodeNoEx(nodepos, &is_valid_position);
  643. if (!is_valid_position)
  644. return false;
  645. if (!prediction.empty() && !nodedef->get(node).rightclickable) {
  646. verbosestream << "Node placement prediction for "
  647. << playeritem_def.name << " is "
  648. << prediction << std::endl;
  649. v3s16 p = neighbourpos;
  650. // Place inside node itself if buildable_to
  651. MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
  652. if (is_valid_position)
  653. {
  654. if (nodedef->get(n_under).buildable_to)
  655. p = nodepos;
  656. else {
  657. node = map.getNodeNoEx(p, &is_valid_position);
  658. if (is_valid_position &&!nodedef->get(node).buildable_to)
  659. return false;
  660. }
  661. }
  662. // Find id of predicted node
  663. content_t id;
  664. bool found = nodedef->getId(prediction, id);
  665. if (!found) {
  666. errorstream << "Node placement prediction failed for "
  667. << playeritem_def.name << " (places "
  668. << prediction
  669. << ") - Name not known" << std::endl;
  670. return false;
  671. }
  672. const ContentFeatures &predicted_f = nodedef->get(id);
  673. // Predict param2 for facedir and wallmounted nodes
  674. u8 param2 = 0;
  675. if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
  676. predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
  677. v3s16 dir = nodepos - neighbourpos;
  678. if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
  679. param2 = dir.Y < 0 ? 1 : 0;
  680. } else if (abs(dir.X) > abs(dir.Z)) {
  681. param2 = dir.X < 0 ? 3 : 2;
  682. } else {
  683. param2 = dir.Z < 0 ? 5 : 4;
  684. }
  685. }
  686. if (predicted_f.param_type_2 == CPT2_FACEDIR ||
  687. predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
  688. v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
  689. if (abs(dir.X) > abs(dir.Z)) {
  690. param2 = dir.X < 0 ? 3 : 1;
  691. } else {
  692. param2 = dir.Z < 0 ? 2 : 0;
  693. }
  694. }
  695. assert(param2 <= 5);
  696. //Check attachment if node is in group attached_node
  697. if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
  698. static v3s16 wallmounted_dirs[8] = {
  699. v3s16(0, 1, 0),
  700. v3s16(0, -1, 0),
  701. v3s16(1, 0, 0),
  702. v3s16(-1, 0, 0),
  703. v3s16(0, 0, 1),
  704. v3s16(0, 0, -1),
  705. };
  706. v3s16 pp;
  707. if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
  708. predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
  709. pp = p + wallmounted_dirs[param2];
  710. else
  711. pp = p + v3s16(0, -1, 0);
  712. if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
  713. return false;
  714. }
  715. // Apply color
  716. if ((predicted_f.param_type_2 == CPT2_COLOR
  717. || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
  718. || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
  719. const std::string &indexstr = playeritem.metadata.getString(
  720. "palette_index", 0);
  721. if (!indexstr.empty()) {
  722. s32 index = mystoi(indexstr);
  723. if (predicted_f.param_type_2 == CPT2_COLOR) {
  724. param2 = index;
  725. } else if (predicted_f.param_type_2
  726. == CPT2_COLORED_WALLMOUNTED) {
  727. // param2 = pure palette index + other
  728. param2 = (index & 0xf8) | (param2 & 0x07);
  729. } else if (predicted_f.param_type_2
  730. == CPT2_COLORED_FACEDIR) {
  731. // param2 = pure palette index + other
  732. param2 = (index & 0xe0) | (param2 & 0x1f);
  733. }
  734. }
  735. }
  736. // Add node to client map
  737. MapNode n(id, 0, param2);
  738. try {
  739. LocalPlayer *player = client.getEnv().getLocalPlayer();
  740. // Dont place node when player would be inside new node
  741. // NOTE: This is to be eventually implemented by a mod as client-side Lua
  742. if (!nodedef->get(n).walkable ||
  743. g_settings->getBool("enable_build_where_you_stand") ||
  744. (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
  745. (nodedef->get(n).walkable &&
  746. neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
  747. neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
  748. // This triggers the required mesh update too
  749. client.addNode(p, n);
  750. return true;
  751. }
  752. } catch (InvalidPositionException &e) {
  753. errorstream << "Node placement prediction failed for "
  754. << playeritem_def.name << " (places "
  755. << prediction
  756. << ") - Position not loaded" << std::endl;
  757. }
  758. }
  759. return false;
  760. }
  761. static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
  762. Client *client, JoystickController *joystick,
  763. IFormSource *fs_src, TextDest *txt_dest)
  764. {
  765. if (*cur_formspec == 0) {
  766. *cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
  767. client, client->getTextureSource(), fs_src, txt_dest);
  768. (*cur_formspec)->doPause = false;
  769. /*
  770. Caution: do not call (*cur_formspec)->drop() here --
  771. the reference might outlive the menu, so we will
  772. periodically check if *cur_formspec is the only
  773. remaining reference (i.e. the menu was removed)
  774. and delete it in that case.
  775. */
  776. } else {
  777. (*cur_formspec)->setFormSource(fs_src);
  778. (*cur_formspec)->setTextDest(txt_dest);
  779. }
  780. }
  781. #ifdef __ANDROID__
  782. #define SIZE_TAG "size[11,5.5]"
  783. #else
  784. #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
  785. #endif
  786. /****************************************************************************
  787. Fast key cache for main game loop
  788. ****************************************************************************/
  789. /* This is faster than using getKeySetting with the tradeoff that functions
  790. * using it must make sure that it's initialised before using it and there is
  791. * no error handling (for example bounds checking). This is really intended for
  792. * use only in the main running loop of the client (the_game()) where the faster
  793. * (up to 10x faster) key lookup is an asset. Other parts of the codebase
  794. * (e.g. formspecs) should continue using getKeySetting().
  795. */
  796. struct KeyCache {
  797. KeyCache()
  798. {
  799. handler = NULL;
  800. populate();
  801. populate_nonchanging();
  802. }
  803. void populate();
  804. // Keys that are not settings dependent
  805. void populate_nonchanging();
  806. KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
  807. InputHandler *handler;
  808. };
  809. void KeyCache::populate_nonchanging()
  810. {
  811. key[KeyType::ESC] = EscapeKey;
  812. }
  813. void KeyCache::populate()
  814. {
  815. key[KeyType::FORWARD] = getKeySetting("keymap_forward");
  816. key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
  817. key[KeyType::LEFT] = getKeySetting("keymap_left");
  818. key[KeyType::RIGHT] = getKeySetting("keymap_right");
  819. key[KeyType::JUMP] = getKeySetting("keymap_jump");
  820. key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
  821. key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
  822. key[KeyType::AUTOFORWARD] = getKeySetting("keymap_autoforward");
  823. key[KeyType::DROP] = getKeySetting("keymap_drop");
  824. key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
  825. key[KeyType::CHAT] = getKeySetting("keymap_chat");
  826. key[KeyType::CMD] = getKeySetting("keymap_cmd");
  827. key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
  828. key[KeyType::CONSOLE] = getKeySetting("keymap_console");
  829. key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
  830. key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
  831. key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
  832. key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
  833. key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
  834. key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
  835. key[KeyType::MUTE] = getKeySetting("keymap_mute");
  836. key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
  837. key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
  838. key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
  839. key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
  840. key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
  841. key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
  842. key[KeyType::TOGGLE_FORCE_FOG_OFF]
  843. = getKeySetting("keymap_toggle_force_fog_off");
  844. key[KeyType::TOGGLE_UPDATE_CAMERA]
  845. = getKeySetting("keymap_toggle_update_camera");
  846. key[KeyType::TOGGLE_DEBUG]
  847. = getKeySetting("keymap_toggle_debug");
  848. key[KeyType::TOGGLE_PROFILER]
  849. = getKeySetting("keymap_toggle_profiler");
  850. key[KeyType::CAMERA_MODE]
  851. = getKeySetting("keymap_camera_mode");
  852. key[KeyType::INCREASE_VIEWING_RANGE]
  853. = getKeySetting("keymap_increase_viewing_range_min");
  854. key[KeyType::DECREASE_VIEWING_RANGE]
  855. = getKeySetting("keymap_decrease_viewing_range_min");
  856. key[KeyType::RANGESELECT]
  857. = getKeySetting("keymap_rangeselect");
  858. key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
  859. key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
  860. key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
  861. key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
  862. key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
  863. for (int i = 0; i < 23; i++) {
  864. std::string slot_key_name = "keymap_slot" + std::to_string(i + 1);
  865. key[KeyType::SLOT_1 + i] = getKeySetting(slot_key_name.c_str());
  866. }
  867. if (handler) {
  868. // First clear all keys, then re-add the ones we listen for
  869. handler->dontListenForKeys();
  870. for (const KeyPress &k : key) {
  871. handler->listenForKey(k);
  872. }
  873. handler->listenForKey(EscapeKey);
  874. handler->listenForKey(CancelKey);
  875. }
  876. }
  877. /****************************************************************************
  878. ****************************************************************************/
  879. const float object_hit_delay = 0.2;
  880. struct FpsControl {
  881. u32 last_time, busy_time, sleep_time;
  882. };
  883. /* The reason the following structs are not anonymous structs within the
  884. * class is that they are not used by the majority of member functions and
  885. * many functions that do require objects of thse types do not modify them
  886. * (so they can be passed as a const qualified parameter)
  887. */
  888. struct GameRunData {
  889. u16 dig_index;
  890. u16 new_playeritem;
  891. PointedThing pointed_old;
  892. bool digging;
  893. bool ldown_for_dig;
  894. bool dig_instantly;
  895. bool digging_blocked;
  896. bool left_punch;
  897. bool update_wielded_item_trigger;
  898. bool reset_jump_timer;
  899. float nodig_delay_timer;
  900. float dig_time;
  901. float dig_time_complete;
  902. float repeat_rightclick_timer;
  903. float object_hit_delay_timer;
  904. float time_from_last_punch;
  905. ClientActiveObject *selected_object;
  906. float jump_timer;
  907. float damage_flash;
  908. float update_draw_list_timer;
  909. f32 fog_range;
  910. v3f update_draw_list_last_cam_dir;
  911. float time_of_day_smooth;
  912. };
  913. class Game;
  914. struct ClientEventHandler
  915. {
  916. void (Game::*handler)(ClientEvent *, CameraOrientation *);
  917. };
  918. /****************************************************************************
  919. THE GAME
  920. ****************************************************************************/
  921. /* This is not intended to be a public class. If a public class becomes
  922. * desirable then it may be better to create another 'wrapper' class that
  923. * hides most of the stuff in this class (nothing in this class is required
  924. * by any other file) but exposes the public methods/data only.
  925. */
  926. class Game {
  927. public:
  928. Game();
  929. ~Game();
  930. bool startup(bool *kill,
  931. bool random_input,
  932. InputHandler *input,
  933. const std::string &map_dir,
  934. const std::string &playername,
  935. const std::string &password,
  936. // If address is "", local server is used and address is updated
  937. std::string *address,
  938. u16 port,
  939. std::string &error_message,
  940. bool *reconnect,
  941. ChatBackend *chat_backend,
  942. const SubgameSpec &gamespec, // Used for local game
  943. bool simple_singleplayer_mode);
  944. void run();
  945. void shutdown();
  946. protected:
  947. void extendedResourceCleanup();
  948. // Basic initialisation
  949. bool init(const std::string &map_dir, std::string *address,
  950. u16 port,
  951. const SubgameSpec &gamespec);
  952. bool initSound();
  953. bool createSingleplayerServer(const std::string &map_dir,
  954. const SubgameSpec &gamespec, u16 port, std::string *address);
  955. // Client creation
  956. bool createClient(const std::string &playername,
  957. const std::string &password, std::string *address, u16 port);
  958. bool initGui();
  959. // Client connection
  960. bool connectToServer(const std::string &playername,
  961. const std::string &password, std::string *address, u16 port,
  962. bool *connect_ok, bool *aborted);
  963. bool getServerContent(bool *aborted);
  964. // Main loop
  965. void updateInteractTimers(f32 dtime);
  966. bool checkConnection();
  967. bool handleCallbacks();
  968. void processQueues();
  969. void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
  970. void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
  971. void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
  972. // Input related
  973. void processUserInput(f32 dtime);
  974. void processKeyInput();
  975. void processItemSelection(u16 *new_playeritem);
  976. void dropSelectedItem(bool single_item = false);
  977. void openInventory();
  978. void openConsole(float scale, const wchar_t *line=NULL);
  979. void toggleFreeMove();
  980. void toggleFreeMoveAlt();
  981. void toggleFast();
  982. void toggleNoClip();
  983. void toggleCinematic();
  984. void toggleAutoforward();
  985. void toggleMinimap(bool shift_pressed);
  986. void toggleFog();
  987. void toggleDebug();
  988. void toggleUpdateCamera();
  989. void increaseViewRange();
  990. void decreaseViewRange();
  991. void toggleFullViewRange();
  992. void checkZoomEnabled();
  993. void updateCameraDirection(CameraOrientation *cam, float dtime);
  994. void updateCameraOrientation(CameraOrientation *cam, float dtime);
  995. void updatePlayerControl(const CameraOrientation &cam);
  996. void step(f32 *dtime);
  997. void processClientEvents(CameraOrientation *cam);
  998. void updateCamera(u32 busy_time, f32 dtime);
  999. void updateSound(f32 dtime);
  1000. void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
  1001. /*!
  1002. * Returns the object or node the player is pointing at.
  1003. * Also updates the selected thing in the Hud.
  1004. *
  1005. * @param[in] shootline the shootline, starting from
  1006. * the camera position. This also gives the maximal distance
  1007. * of the search.
  1008. * @param[in] liquids_pointable if false, liquids are ignored
  1009. * @param[in] look_for_object if false, objects are ignored
  1010. * @param[in] camera_offset offset of the camera
  1011. * @param[out] selected_object the selected object or
  1012. * NULL if not found
  1013. */
  1014. PointedThing updatePointedThing(
  1015. const core::line3d<f32> &shootline, bool liquids_pointable,
  1016. bool look_for_object, const v3s16 &camera_offset);
  1017. void handlePointingAtNothing(const ItemStack &playerItem);
  1018. void handlePointingAtNode(const PointedThing &pointed,
  1019. const ItemDefinition &playeritem_def, const ItemStack &playeritem,
  1020. const ToolCapabilities &playeritem_toolcap, f32 dtime);
  1021. void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
  1022. const v3f &player_position, bool show_debug);
  1023. void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
  1024. const ToolCapabilities &playeritem_toolcap, f32 dtime);
  1025. void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
  1026. const CameraOrientation &cam);
  1027. void updateProfilerGraphs(ProfilerGraph *graph);
  1028. // Misc
  1029. void limitFps(FpsControl *fps_timings, f32 *dtime);
  1030. void showOverlayMessage(const char *msg, float dtime, int percent,
  1031. bool draw_clouds = true);
  1032. static void settingChangedCallback(const std::string &setting_name, void *data);
  1033. void readSettings();
  1034. inline bool getLeftClicked()
  1035. {
  1036. return input->getLeftClicked() ||
  1037. input->joystick.getWasKeyDown(KeyType::MOUSE_L);
  1038. }
  1039. inline bool getRightClicked()
  1040. {
  1041. return input->getRightClicked() ||
  1042. input->joystick.getWasKeyDown(KeyType::MOUSE_R);
  1043. }
  1044. inline bool isLeftPressed()
  1045. {
  1046. return input->getLeftState() ||
  1047. input->joystick.isKeyDown(KeyType::MOUSE_L);
  1048. }
  1049. inline bool isRightPressed()
  1050. {
  1051. return input->getRightState() ||
  1052. input->joystick.isKeyDown(KeyType::MOUSE_R);
  1053. }
  1054. inline bool getLeftReleased()
  1055. {
  1056. return input->getLeftReleased() ||
  1057. input->joystick.wasKeyReleased(KeyType::MOUSE_L);
  1058. }
  1059. inline bool isKeyDown(GameKeyType k)
  1060. {
  1061. return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
  1062. }
  1063. inline bool wasKeyDown(GameKeyType k)
  1064. {
  1065. return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
  1066. }
  1067. #ifdef __ANDROID__
  1068. void handleAndroidChatInput();
  1069. #endif
  1070. private:
  1071. struct Flags {
  1072. bool force_fog_off = false;
  1073. bool disable_camera_update = false;
  1074. };
  1075. void showPauseMenu();
  1076. // ClientEvent handlers
  1077. void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
  1078. void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
  1079. void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
  1080. void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
  1081. void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
  1082. void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
  1083. void handleClientEvent_HandleParticleEvent(ClientEvent *event,
  1084. CameraOrientation *cam);
  1085. void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
  1086. void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
  1087. void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
  1088. void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
  1089. void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
  1090. CameraOrientation *cam);
  1091. void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
  1092. void updateChat(f32 dtime, const v2u32 &screensize);
  1093. static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
  1094. InputHandler *input;
  1095. Client *client = nullptr;
  1096. Server *server = nullptr;
  1097. IWritableTextureSource *texture_src = nullptr;
  1098. IWritableShaderSource *shader_src = nullptr;
  1099. // When created, these will be filled with data received from the server
  1100. IWritableItemDefManager *itemdef_manager = nullptr;
  1101. IWritableNodeDefManager *nodedef_manager = nullptr;
  1102. GameOnDemandSoundFetcher soundfetcher; // useful when testing
  1103. ISoundManager *sound = nullptr;
  1104. bool sound_is_dummy = false;
  1105. SoundMaker *soundmaker = nullptr;
  1106. ChatBackend *chat_backend = nullptr;
  1107. GUIFormSpecMenu *current_formspec = nullptr;
  1108. //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
  1109. std::string cur_formname;
  1110. EventManager *eventmgr = nullptr;
  1111. QuicktuneShortcutter *quicktune = nullptr;
  1112. std::unique_ptr<GameUI> m_game_ui;
  1113. GUIChatConsole *gui_chat_console = nullptr; // Free using ->Drop()
  1114. MapDrawControl *draw_control = nullptr;
  1115. Camera *camera = nullptr;
  1116. Clouds *clouds = nullptr; // Free using ->Drop()
  1117. Sky *sky = nullptr; // Free using ->Drop()
  1118. Inventory *local_inventory = nullptr;
  1119. Hud *hud = nullptr;
  1120. Minimap *mapper = nullptr;
  1121. GameRunData runData;
  1122. Flags m_flags;
  1123. /* 'cache'
  1124. This class does take ownership/responsibily for cleaning up etc of any of
  1125. these items (e.g. device)
  1126. */
  1127. IrrlichtDevice *device;
  1128. video::IVideoDriver *driver;
  1129. scene::ISceneManager *smgr;
  1130. bool *kill;
  1131. std::string *error_message;
  1132. bool *reconnect_requested;
  1133. scene::ISceneNode *skybox;
  1134. bool random_input;
  1135. bool simple_singleplayer_mode;
  1136. /* End 'cache' */
  1137. /* Pre-calculated values
  1138. */
  1139. int crack_animation_length;
  1140. KeyCache keycache;
  1141. IntervalLimiter profiler_interval;
  1142. /*
  1143. * TODO: Local caching of settings is not optimal and should at some stage
  1144. * be updated to use a global settings object for getting thse values
  1145. * (as opposed to the this local caching). This can be addressed in
  1146. * a later release.
  1147. */
  1148. bool m_cache_doubletap_jump;
  1149. bool m_cache_enable_clouds;
  1150. bool m_cache_enable_joysticks;
  1151. bool m_cache_enable_particles;
  1152. bool m_cache_enable_fog;
  1153. bool m_cache_enable_noclip;
  1154. bool m_cache_enable_free_move;
  1155. f32 m_cache_mouse_sensitivity;
  1156. f32 m_cache_joystick_frustum_sensitivity;
  1157. f32 m_repeat_right_click_time;
  1158. f32 m_cache_cam_smoothing;
  1159. f32 m_cache_fog_start;
  1160. bool m_invert_mouse = false;
  1161. bool m_first_loop_after_window_activation = false;
  1162. bool m_camera_offset_changed = false;
  1163. bool m_does_lost_focus_pause_game = false;
  1164. #ifdef __ANDROID__
  1165. bool m_cache_hold_aux1;
  1166. bool m_android_chat_open;
  1167. #endif
  1168. };
  1169. Game::Game() :
  1170. m_game_ui(new GameUI())
  1171. {
  1172. g_settings->registerChangedCallback("doubletap_jump",
  1173. &settingChangedCallback, this);
  1174. g_settings->registerChangedCallback("enable_clouds",
  1175. &settingChangedCallback, this);
  1176. g_settings->registerChangedCallback("doubletap_joysticks",
  1177. &settingChangedCallback, this);
  1178. g_settings->registerChangedCallback("enable_particles",
  1179. &settingChangedCallback, this);
  1180. g_settings->registerChangedCallback("enable_fog",
  1181. &settingChangedCallback, this);
  1182. g_settings->registerChangedCallback("mouse_sensitivity",
  1183. &settingChangedCallback, this);
  1184. g_settings->registerChangedCallback("joystick_frustum_sensitivity",
  1185. &settingChangedCallback, this);
  1186. g_settings->registerChangedCallback("repeat_rightclick_time",
  1187. &settingChangedCallback, this);
  1188. g_settings->registerChangedCallback("noclip",
  1189. &settingChangedCallback, this);
  1190. g_settings->registerChangedCallback("free_move",
  1191. &settingChangedCallback, this);
  1192. g_settings->registerChangedCallback("cinematic",
  1193. &settingChangedCallback, this);
  1194. g_settings->registerChangedCallback("cinematic_camera_smoothing",
  1195. &settingChangedCallback, this);
  1196. g_settings->registerChangedCallback("camera_smoothing",
  1197. &settingChangedCallback, this);
  1198. readSettings();
  1199. #ifdef __ANDROID__
  1200. m_cache_hold_aux1 = false; // This is initialised properly later
  1201. #endif
  1202. }
  1203. /****************************************************************************
  1204. MinetestApp Public
  1205. ****************************************************************************/
  1206. Game::~Game()
  1207. {
  1208. delete client;
  1209. delete soundmaker;
  1210. if (!sound_is_dummy)
  1211. delete sound;
  1212. delete server; // deleted first to stop all server threads
  1213. delete hud;
  1214. delete local_inventory;
  1215. delete camera;
  1216. delete quicktune;
  1217. delete eventmgr;
  1218. delete texture_src;
  1219. delete shader_src;
  1220. delete nodedef_manager;
  1221. delete itemdef_manager;
  1222. delete draw_control;
  1223. extendedResourceCleanup();
  1224. g_settings->deregisterChangedCallback("doubletap_jump",
  1225. &settingChangedCallback, this);
  1226. g_settings->deregisterChangedCallback("enable_clouds",
  1227. &settingChangedCallback, this);
  1228. g_settings->deregisterChangedCallback("enable_particles",
  1229. &settingChangedCallback, this);
  1230. g_settings->deregisterChangedCallback("enable_fog",
  1231. &settingChangedCallback, this);
  1232. g_settings->deregisterChangedCallback("mouse_sensitivity",
  1233. &settingChangedCallback, this);
  1234. g_settings->deregisterChangedCallback("repeat_rightclick_time",
  1235. &settingChangedCallback, this);
  1236. g_settings->deregisterChangedCallback("noclip",
  1237. &settingChangedCallback, this);
  1238. g_settings->deregisterChangedCallback("free_move",
  1239. &settingChangedCallback, this);
  1240. g_settings->deregisterChangedCallback("cinematic",
  1241. &settingChangedCallback, this);
  1242. g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
  1243. &settingChangedCallback, this);
  1244. g_settings->deregisterChangedCallback("camera_smoothing",
  1245. &settingChangedCallback, this);
  1246. }
  1247. bool Game::startup(bool *kill,
  1248. bool random_input,
  1249. InputHandler *input,
  1250. const std::string &map_dir,
  1251. const std::string &playername,
  1252. const std::string &password,
  1253. std::string *address, // can change if simple_singleplayer_mode
  1254. u16 port,
  1255. std::string &error_message,
  1256. bool *reconnect,
  1257. ChatBackend *chat_backend,
  1258. const SubgameSpec &gamespec,
  1259. bool simple_singleplayer_mode)
  1260. {
  1261. // "cache"
  1262. this->device = RenderingEngine::get_raw_device();
  1263. this->kill = kill;
  1264. this->error_message = &error_message;
  1265. this->reconnect_requested = reconnect;
  1266. this->random_input = random_input;
  1267. this->input = input;
  1268. this->chat_backend = chat_backend;
  1269. this->simple_singleplayer_mode = simple_singleplayer_mode;
  1270. keycache.handler = input;
  1271. keycache.populate();
  1272. driver = device->getVideoDriver();
  1273. smgr = RenderingEngine::get_scene_manager();
  1274. RenderingEngine::get_scene_manager()->getParameters()->
  1275. setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
  1276. memset(&runData, 0, sizeof(runData));
  1277. runData.time_from_last_punch = 10.0;
  1278. runData.update_wielded_item_trigger = true;
  1279. m_game_ui->initFlags();
  1280. m_invert_mouse = g_settings->getBool("invert_mouse");
  1281. m_first_loop_after_window_activation = true;
  1282. g_translations->clear();
  1283. if (!init(map_dir, address, port, gamespec))
  1284. return false;
  1285. if (!createClient(playername, password, address, port))
  1286. return false;
  1287. RenderingEngine::initialize(client, hud);
  1288. return true;
  1289. }
  1290. void Game::run()
  1291. {
  1292. ProfilerGraph graph;
  1293. RunStats stats = { 0 };
  1294. CameraOrientation cam_view_target = { 0 };
  1295. CameraOrientation cam_view = { 0 };
  1296. FpsControl draw_times = { 0 };
  1297. f32 dtime; // in seconds
  1298. /* Clear the profiler */
  1299. Profiler::GraphValues dummyvalues;
  1300. g_profiler->graphGet(dummyvalues);
  1301. draw_times.last_time = RenderingEngine::get_timer_time();
  1302. set_light_table(g_settings->getFloat("display_gamma"));
  1303. #ifdef __ANDROID__
  1304. m_cache_hold_aux1 = g_settings->getBool("fast_move")
  1305. && client->checkPrivilege("fast");
  1306. #endif
  1307. irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
  1308. g_settings->getU16("screen_h"));
  1309. while (RenderingEngine::run()
  1310. && !(*kill || g_gamecallback->shutdown_requested
  1311. || (server && server->getShutdownRequested()))) {
  1312. const irr::core::dimension2d<u32> &current_screen_size =
  1313. RenderingEngine::get_video_driver()->getScreenSize();
  1314. // Verify if window size has changed and save it if it's the case
  1315. // Ensure evaluating settings->getBool after verifying screensize
  1316. // First condition is cheaper
  1317. if (previous_screen_size != current_screen_size &&
  1318. current_screen_size != irr::core::dimension2d<u32>(0,0) &&
  1319. g_settings->getBool("autosave_screensize")) {
  1320. g_settings->setU16("screen_w", current_screen_size.Width);
  1321. g_settings->setU16("screen_h", current_screen_size.Height);
  1322. previous_screen_size = current_screen_size;
  1323. }
  1324. /* Must be called immediately after a device->run() call because it
  1325. * uses device->getTimer()->getTime()
  1326. */
  1327. limitFps(&draw_times, &dtime);
  1328. updateStats(&stats, draw_times, dtime);
  1329. updateInteractTimers(dtime);
  1330. if (!checkConnection())
  1331. break;
  1332. if (!handleCallbacks())
  1333. break;
  1334. processQueues();
  1335. m_game_ui->clearInfoText();
  1336. hud->resizeHotbar();
  1337. updateProfilers(stats, draw_times, dtime);
  1338. processUserInput(dtime);
  1339. // Update camera before player movement to avoid camera lag of one frame
  1340. updateCameraDirection(&cam_view_target, dtime);
  1341. cam_view.camera_yaw += (cam_view_target.camera_yaw -
  1342. cam_view.camera_yaw) * m_cache_cam_smoothing;
  1343. cam_view.camera_pitch += (cam_view_target.camera_pitch -
  1344. cam_view.camera_pitch) * m_cache_cam_smoothing;
  1345. updatePlayerControl(cam_view);
  1346. step(&dtime);
  1347. processClientEvents(&cam_view_target);
  1348. updateCamera(draw_times.busy_time, dtime);
  1349. updateSound(dtime);
  1350. processPlayerInteraction(dtime, m_game_ui->m_flags.show_hud,
  1351. m_game_ui->m_flags.show_debug);
  1352. updateFrame(&graph, &stats, dtime, cam_view);
  1353. updateProfilerGraphs(&graph);
  1354. // Update if minimap has been disabled by the server
  1355. m_game_ui->m_flags.show_minimap &= client->shouldShowMinimap();
  1356. if (m_does_lost_focus_pause_game && !device->isWindowFocused() && !isMenuActive()) {
  1357. showPauseMenu();
  1358. }
  1359. }
  1360. }
  1361. void Game::shutdown()
  1362. {
  1363. RenderingEngine::finalize();
  1364. #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
  1365. if (g_settings->get("3d_mode") == "pageflip") {
  1366. driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
  1367. }
  1368. #endif
  1369. if (current_formspec)
  1370. current_formspec->quitMenu();
  1371. showOverlayMessage("Shutting down...", 0, 0, false);
  1372. if (clouds)
  1373. clouds->drop();
  1374. if (gui_chat_console)
  1375. gui_chat_console->drop();
  1376. if (sky)
  1377. sky->drop();
  1378. /* cleanup menus */
  1379. while (g_menumgr.menuCount() > 0) {
  1380. g_menumgr.m_stack.front()->setVisible(false);
  1381. g_menumgr.deletingMenu(g_menumgr.m_stack.front());
  1382. }
  1383. if (current_formspec) {
  1384. current_formspec->drop();
  1385. current_formspec = NULL;
  1386. }
  1387. chat_backend->addMessage(L"", L"# Disconnected.");
  1388. chat_backend->addMessage(L"", L"");
  1389. if (client) {
  1390. client->Stop();
  1391. while (!client->isShutdown()) {
  1392. assert(texture_src != NULL);
  1393. assert(shader_src != NULL);
  1394. texture_src->processQueue();
  1395. shader_src->processQueue();
  1396. sleep_ms(100);
  1397. }
  1398. }
  1399. }
  1400. /****************************************************************************/
  1401. /****************************************************************************
  1402. Startup
  1403. ****************************************************************************/
  1404. /****************************************************************************/
  1405. bool Game::init(
  1406. const std::string &map_dir,
  1407. std::string *address,
  1408. u16 port,
  1409. const SubgameSpec &gamespec)
  1410. {
  1411. texture_src = createTextureSource();
  1412. showOverlayMessage("Loading...", 0, 0);
  1413. shader_src = createShaderSource();
  1414. itemdef_manager = createItemDefManager();
  1415. nodedef_manager = createNodeDefManager();
  1416. eventmgr = new EventManager();
  1417. quicktune = new QuicktuneShortcutter();
  1418. if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
  1419. && eventmgr && quicktune))
  1420. return false;
  1421. if (!initSound())
  1422. return false;
  1423. // Create a server if not connecting to an existing one
  1424. if (address->empty()) {
  1425. if (!createSingleplayerServer(map_dir, gamespec, port, address))
  1426. return false;
  1427. }
  1428. return true;
  1429. }
  1430. bool Game::initSound()
  1431. {
  1432. #if USE_SOUND
  1433. if (g_settings->getBool("enable_sound")) {
  1434. infostream << "Attempting to use OpenAL audio" << std::endl;
  1435. sound = createOpenALSoundManager(&soundfetcher);
  1436. if (!sound)
  1437. infostream << "Failed to initialize OpenAL audio" << std::endl;
  1438. } else
  1439. infostream << "Sound disabled." << std::endl;
  1440. #endif
  1441. if (!sound) {
  1442. infostream << "Using dummy audio." << std::endl;
  1443. sound = &dummySoundManager;
  1444. sound_is_dummy = true;
  1445. }
  1446. soundmaker = new SoundMaker(sound, nodedef_manager);
  1447. if (!soundmaker)
  1448. return false;
  1449. soundmaker->registerReceiver(eventmgr);
  1450. return true;
  1451. }
  1452. bool Game::createSingleplayerServer(const std::string &map_dir,
  1453. const SubgameSpec &gamespec, u16 port, std::string *address)
  1454. {
  1455. showOverlayMessage("Creating server...", 0, 5);
  1456. std::string bind_str = g_settings->get("bind_address");
  1457. Address bind_addr(0, 0, 0, 0, port);
  1458. if (g_settings->getBool("ipv6_server")) {
  1459. bind_addr.setAddress((IPv6AddressBytes *) NULL);
  1460. }
  1461. try {
  1462. bind_addr.Resolve(bind_str.c_str());
  1463. } catch (ResolveError &e) {
  1464. infostream << "Resolving bind address \"" << bind_str
  1465. << "\" failed: " << e.what()
  1466. << " -- Listening on all addresses." << std::endl;
  1467. }
  1468. if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
  1469. *error_message = "Unable to listen on " +
  1470. bind_addr.serializeString() +
  1471. " because IPv6 is disabled";
  1472. errorstream << *error_message << std::endl;
  1473. return false;
  1474. }
  1475. server = new Server(map_dir, gamespec, simple_singleplayer_mode, bind_addr, false);
  1476. server->start();
  1477. return true;
  1478. }
  1479. bool Game::createClient(const std::string &playername,
  1480. const std::string &password, std::string *address, u16 port)
  1481. {
  1482. showOverlayMessage("Creating client...", 0, 10);
  1483. draw_control = new MapDrawControl;
  1484. if (!draw_control)
  1485. return false;
  1486. bool could_connect, connect_aborted;
  1487. if (!connectToServer(playername, password, address, port,
  1488. &could_connect, &connect_aborted))
  1489. return false;
  1490. if (!could_connect) {
  1491. if (error_message->empty() && !connect_aborted) {
  1492. // Should not happen if error messages are set properly
  1493. *error_message = "Connection failed for unknown reason";
  1494. errorstream << *error_message << std::endl;
  1495. }
  1496. return false;
  1497. }
  1498. if (!getServerContent(&connect_aborted)) {
  1499. if (error_message->empty() && !connect_aborted) {
  1500. // Should not happen if error messages are set properly
  1501. *error_message = "Connection failed for unknown reason";
  1502. errorstream << *error_message << std::endl;
  1503. }
  1504. return false;
  1505. }
  1506. GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
  1507. &m_flags.force_fog_off, &runData.fog_range, client);
  1508. shader_src->addShaderConstantSetterFactory(scsf);
  1509. // Update cached textures, meshes and materials
  1510. client->afterContentReceived();
  1511. /* Camera
  1512. */
  1513. camera = new Camera(*draw_control, client);
  1514. if (!camera || !camera->successfullyCreated(*error_message))
  1515. return false;
  1516. client->setCamera(camera);
  1517. /* Clouds
  1518. */
  1519. if (m_cache_enable_clouds) {
  1520. clouds = new Clouds(smgr, -1, time(0));
  1521. if (!clouds) {
  1522. *error_message = "Memory allocation error (clouds)";
  1523. errorstream << *error_message << std::endl;
  1524. return false;
  1525. }
  1526. }
  1527. /* Skybox
  1528. */
  1529. sky = new Sky(-1, texture_src);
  1530. scsf->setSky(sky);
  1531. skybox = NULL; // This is used/set later on in the main run loop
  1532. local_inventory = new Inventory(itemdef_manager);
  1533. if (!(sky && local_inventory)) {
  1534. *error_message = "Memory allocation error (sky or local inventory)";
  1535. errorstream << *error_message << std::endl;
  1536. return false;
  1537. }
  1538. /* Pre-calculated values
  1539. */
  1540. video::ITexture *t = texture_src->getTexture("crack_anylength.png");
  1541. if (t) {
  1542. v2u32 size = t->getOriginalSize();
  1543. crack_animation_length = size.Y / size.X;
  1544. } else {
  1545. crack_animation_length = 5;
  1546. }
  1547. if (!initGui())
  1548. return false;
  1549. /* Set window caption
  1550. */
  1551. std::wstring str = utf8_to_wide(PROJECT_NAME_C);
  1552. str += L" ";
  1553. str += utf8_to_wide(g_version_hash);
  1554. str += L" [";
  1555. str += driver->getName();
  1556. str += L"]";
  1557. device->setWindowCaption(str.c_str());
  1558. LocalPlayer *player = client->getEnv().getLocalPlayer();
  1559. player->hurt_tilt_timer = 0;
  1560. player->hurt_tilt_strength = 0;
  1561. hud = new Hud(guienv, client, player, local_inventory);
  1562. if (!hud) {
  1563. *error_message = "Memory error: could not create HUD";
  1564. errorstream << *error_message << std::endl;
  1565. return false;
  1566. }
  1567. mapper = client->getMinimap();
  1568. if (mapper)
  1569. mapper->setMinimapMode(MINIMAP_MODE_OFF);
  1570. return true;
  1571. }
  1572. bool Game::initGui()
  1573. {
  1574. m_game_ui->init();
  1575. // Remove stale "recent" chat messages from previous connections
  1576. chat_backend->clearRecentChat();
  1577. // Make sure the size of the recent messages buffer is right
  1578. chat_backend->applySettings();
  1579. // Chat backend and console
  1580. gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
  1581. -1, chat_backend, client, &g_menumgr);
  1582. if (!gui_chat_console) {
  1583. *error_message = "Could not allocate memory for chat console";
  1584. errorstream << *error_message << std::endl;
  1585. return false;
  1586. }
  1587. #ifdef HAVE_TOUCHSCREENGUI
  1588. if (g_touchscreengui)
  1589. g_touchscreengui->init(texture_src);
  1590. #endif
  1591. return true;
  1592. }
  1593. bool Game::connectToServer(const std::string &playername,
  1594. const std::string &password, std::string *address, u16 port,
  1595. bool *connect_ok, bool *aborted)
  1596. {
  1597. *connect_ok = false; // Let's not be overly optimistic
  1598. *aborted = false;
  1599. bool local_server_mode = false;
  1600. showOverlayMessage("Resolving address...", 0, 15);
  1601. Address connect_address(0, 0, 0, 0, port);
  1602. try {
  1603. connect_address.Resolve(address->c_str());
  1604. if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
  1605. //connect_address.Resolve("localhost");
  1606. if (connect_address.isIPv6()) {
  1607. IPv6AddressBytes addr_bytes;
  1608. addr_bytes.bytes[15] = 1;
  1609. connect_address.setAddress(&addr_bytes);
  1610. } else {
  1611. connect_address.setAddress(127, 0, 0, 1);
  1612. }
  1613. local_server_mode = true;
  1614. }
  1615. } catch (ResolveError &e) {
  1616. *error_message = std::string("Couldn't resolve address: ") + e.what();
  1617. errorstream << *error_message << std::endl;
  1618. return false;
  1619. }
  1620. if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
  1621. *error_message = "Unable to connect to " +
  1622. connect_address.serializeString() +
  1623. " because IPv6 is disabled";
  1624. errorstream << *error_message << std::endl;
  1625. return false;
  1626. }
  1627. client = new Client(playername.c_str(), password, *address,
  1628. *draw_control, texture_src, shader_src,
  1629. itemdef_manager, nodedef_manager, sound, eventmgr,
  1630. connect_address.isIPv6(), m_game_ui.get());
  1631. if (!client)
  1632. return false;
  1633. infostream << "Connecting to server at ";
  1634. connect_address.print(&infostream);
  1635. infostream << std::endl;
  1636. client->connect(connect_address,
  1637. simple_singleplayer_mode || local_server_mode);
  1638. /*
  1639. Wait for server to accept connection
  1640. */
  1641. try {
  1642. input->clear();
  1643. FpsControl fps_control = { 0 };
  1644. f32 dtime;
  1645. f32 wait_time = 0; // in seconds
  1646. fps_control.last_time = RenderingEngine::get_timer_time();
  1647. client->loadBuiltin();
  1648. while (RenderingEngine::run()) {
  1649. limitFps(&fps_control, &dtime);
  1650. // Update client and server
  1651. client->step(dtime);
  1652. if (server != NULL)
  1653. server->step(dtime);
  1654. // End condition
  1655. if (client->getState() == LC_Init) {
  1656. *connect_ok = true;
  1657. break;
  1658. }
  1659. // Break conditions
  1660. if (client->accessDenied()) {
  1661. *error_message = "Access denied. Reason: "
  1662. + client->accessDeniedReason();
  1663. *reconnect_requested = client->reconnectRequested();
  1664. errorstream << *error_message << std::endl;
  1665. break;
  1666. }
  1667. if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
  1668. *aborted = true;
  1669. infostream << "Connect aborted [Escape]" << std::endl;
  1670. break;
  1671. }
  1672. wait_time += dtime;
  1673. // Only time out if we aren't waiting for the server we started
  1674. if (!address->empty() && wait_time > 10) {
  1675. *error_message = "Connection timed out.";
  1676. errorstream << *error_message << std::endl;
  1677. break;
  1678. }
  1679. // Update status
  1680. showOverlayMessage("Connecting to server...", dtime, 20);
  1681. }
  1682. } catch (con::PeerNotFoundException &e) {
  1683. // TODO: Should something be done here? At least an info/error
  1684. // message?
  1685. return false;
  1686. }
  1687. return true;
  1688. }
  1689. bool Game::getServerContent(bool *aborted)
  1690. {
  1691. input->clear();
  1692. FpsControl fps_control = { 0 };
  1693. f32 dtime; // in seconds
  1694. fps_control.last_time = RenderingEngine::get_timer_time();
  1695. while (RenderingEngine::run()) {
  1696. limitFps(&fps_control, &dtime);
  1697. // Update client and server
  1698. client->step(dtime);
  1699. if (server != NULL)
  1700. server->step(dtime);
  1701. // End condition
  1702. if (client->mediaReceived() && client->itemdefReceived() &&
  1703. client->nodedefReceived()) {
  1704. break;
  1705. }
  1706. // Error conditions
  1707. if (!checkConnection())
  1708. return false;
  1709. if (client->getState() < LC_Init) {
  1710. *error_message = "Client disconnected";
  1711. errorstream << *error_message << std::endl;
  1712. return false;
  1713. }
  1714. if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
  1715. *aborted = true;
  1716. infostream << "Connect aborted [Escape]" << std::endl;
  1717. return false;
  1718. }
  1719. // Display status
  1720. int progress = 25;
  1721. if (!client->itemdefReceived()) {
  1722. const wchar_t *text = wgettext("Item definitions...");
  1723. progress = 25;
  1724. RenderingEngine::draw_load_screen(text, guienv, texture_src,
  1725. dtime, progress);
  1726. delete[] text;
  1727. } else if (!client->nodedefReceived()) {
  1728. const wchar_t *text = wgettext("Node definitions...");
  1729. progress = 30;
  1730. RenderingEngine::draw_load_screen(text, guienv, texture_src,
  1731. dtime, progress);
  1732. delete[] text;
  1733. } else {
  1734. std::stringstream message;
  1735. std::fixed(message);
  1736. message.precision(0);
  1737. message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
  1738. message.precision(2);
  1739. if ((USE_CURL == 0) ||
  1740. (!g_settings->getBool("enable_remote_media_server"))) {
  1741. float cur = client->getCurRate();
  1742. std::string cur_unit = gettext("KiB/s");
  1743. if (cur > 900) {
  1744. cur /= 1024.0;
  1745. cur_unit = gettext("MiB/s");
  1746. }
  1747. message << " (" << cur << ' ' << cur_unit << ")";
  1748. }
  1749. progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
  1750. RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
  1751. texture_src, dtime, progress);
  1752. }
  1753. }
  1754. return true;
  1755. }
  1756. /****************************************************************************/
  1757. /****************************************************************************
  1758. Run
  1759. ****************************************************************************/
  1760. /****************************************************************************/
  1761. inline void Game::updateInteractTimers(f32 dtime)
  1762. {
  1763. if (runData.nodig_delay_timer >= 0)
  1764. runData.nodig_delay_timer -= dtime;
  1765. if (runData.object_hit_delay_timer >= 0)
  1766. runData.object_hit_delay_timer -= dtime;
  1767. runData.time_from_last_punch += dtime;
  1768. }
  1769. /* returns false if game should exit, otherwise true
  1770. */
  1771. inline bool Game::checkConnection()
  1772. {
  1773. if (client->accessDenied()) {
  1774. *error_message = "Access denied. Reason: "
  1775. + client->accessDeniedReason();
  1776. *reconnect_requested = client->reconnectRequested();
  1777. errorstream << *error_message << std::endl;
  1778. return false;
  1779. }
  1780. return true;
  1781. }
  1782. /* returns false if game should exit, otherwise true
  1783. */
  1784. inline bool Game::handleCallbacks()
  1785. {
  1786. if (g_gamecallback->disconnect_requested) {
  1787. g_gamecallback->disconnect_requested = false;
  1788. return false;
  1789. }
  1790. if (g_gamecallback->changepassword_requested) {
  1791. (new GUIPasswordChange(guienv, guiroot, -1,
  1792. &g_menumgr, client))->drop();
  1793. g_gamecallback->changepassword_requested = false;
  1794. }
  1795. if (g_gamecallback->changevolume_requested) {
  1796. (new GUIVolumeChange(guienv, guiroot, -1,
  1797. &g_menumgr))->drop();
  1798. g_gamecallback->changevolume_requested = false;
  1799. }
  1800. if (g_gamecallback->keyconfig_requested) {
  1801. (new GUIKeyChangeMenu(guienv, guiroot, -1,
  1802. &g_menumgr))->drop();
  1803. g_gamecallback->keyconfig_requested = false;
  1804. }
  1805. if (g_gamecallback->keyconfig_changed) {
  1806. keycache.populate(); // update the cache with new settings
  1807. g_gamecallback->keyconfig_changed = false;
  1808. }
  1809. return true;
  1810. }
  1811. void Game::processQueues()
  1812. {
  1813. texture_src->processQueue();
  1814. itemdef_manager->processQueue(client);
  1815. shader_src->processQueue();
  1816. }
  1817. void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
  1818. {
  1819. float profiler_print_interval =
  1820. g_settings->getFloat("profiler_print_interval");
  1821. bool print_to_log = true;
  1822. if (profiler_print_interval == 0) {
  1823. print_to_log = false;
  1824. profiler_print_interval = 5;
  1825. }
  1826. if (profiler_interval.step(dtime, profiler_print_interval)) {
  1827. if (print_to_log) {
  1828. infostream << "Profiler:" << std::endl;
  1829. g_profiler->print(infostream);
  1830. }
  1831. m_game_ui->updateProfiler();
  1832. g_profiler->clear();
  1833. }
  1834. addProfilerGraphs(stats, draw_times, dtime);
  1835. }
  1836. void Game::addProfilerGraphs(const RunStats &stats,
  1837. const FpsControl &draw_times, f32 dtime)
  1838. {
  1839. g_profiler->graphAdd("mainloop_other",
  1840. draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
  1841. if (draw_times.sleep_time != 0)
  1842. g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
  1843. g_profiler->graphAdd("mainloop_dtime", dtime);
  1844. g_profiler->add("Elapsed time", dtime);
  1845. g_profiler->avg("FPS", 1. / dtime);
  1846. }
  1847. void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
  1848. f32 dtime)
  1849. {
  1850. f32 jitter;
  1851. Jitter *jp;
  1852. /* Time average and jitter calculation
  1853. */
  1854. jp = &stats->dtime_jitter;
  1855. jp->avg = jp->avg * 0.96 + dtime * 0.04;
  1856. jitter = dtime - jp->avg;
  1857. if (jitter > jp->max)
  1858. jp->max = jitter;
  1859. jp->counter += dtime;
  1860. if (jp->counter > 0.0) {
  1861. jp->counter -= 3.0;
  1862. jp->max_sample = jp->max;
  1863. jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
  1864. jp->max = 0.0;
  1865. }
  1866. /* Busytime average and jitter calculation
  1867. */
  1868. jp = &stats->busy_time_jitter;
  1869. jp->avg = jp->avg + draw_times.busy_time * 0.02;
  1870. jitter = draw_times.busy_time - jp->avg;
  1871. if (jitter > jp->max)
  1872. jp->max = jitter;
  1873. if (jitter < jp->min)
  1874. jp->min = jitter;
  1875. jp->counter += dtime;
  1876. if (jp->counter > 0.0) {
  1877. jp->counter -= 3.0;
  1878. jp->max_sample = jp->max;
  1879. jp->min_sample = jp->min;
  1880. jp->max = 0.0;
  1881. jp->min = 0.0;
  1882. }
  1883. }
  1884. /****************************************************************************
  1885. Input handling
  1886. ****************************************************************************/
  1887. void Game::processUserInput(f32 dtime)
  1888. {
  1889. // Reset input if window not active or some menu is active
  1890. if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
  1891. input->clear();
  1892. #ifdef HAVE_TOUCHSCREENGUI
  1893. g_touchscreengui->hide();
  1894. #endif
  1895. }
  1896. #ifdef HAVE_TOUCHSCREENGUI
  1897. else if (g_touchscreengui) {
  1898. /* on touchscreengui step may generate own input events which ain't
  1899. * what we want in case we just did clear them */
  1900. g_touchscreengui->step(dtime);
  1901. }
  1902. #endif
  1903. if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
  1904. gui_chat_console->closeConsoleAtOnce();
  1905. }
  1906. // Input handler step() (used by the random input generator)
  1907. input->step(dtime);
  1908. #ifdef __ANDROID__
  1909. if (current_formspec != NULL)
  1910. current_formspec->getAndroidUIInput();
  1911. else
  1912. handleAndroidChatInput();
  1913. #endif
  1914. // Increase timer for double tap of "keymap_jump"
  1915. if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
  1916. runData.jump_timer += dtime;
  1917. processKeyInput();
  1918. processItemSelection(&runData.new_playeritem);
  1919. }
  1920. void Game::processKeyInput()
  1921. {
  1922. if (wasKeyDown(KeyType::DROP)) {
  1923. dropSelectedItem(isKeyDown(KeyType::SNEAK));
  1924. } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
  1925. toggleAutoforward();
  1926. } else if (wasKeyDown(KeyType::INVENTORY)) {
  1927. openInventory();
  1928. } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
  1929. if (!gui_chat_console->isOpenInhibited()) {
  1930. showPauseMenu();
  1931. }
  1932. } else if (wasKeyDown(KeyType::CHAT)) {
  1933. openConsole(0.2, L"");
  1934. } else if (wasKeyDown(KeyType::CMD)) {
  1935. openConsole(0.2, L"/");
  1936. } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
  1937. openConsole(0.2, L".");
  1938. } else if (wasKeyDown(KeyType::CONSOLE)) {
  1939. openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
  1940. } else if (wasKeyDown(KeyType::FREEMOVE)) {
  1941. toggleFreeMove();
  1942. } else if (wasKeyDown(KeyType::JUMP)) {
  1943. toggleFreeMoveAlt();
  1944. } else if (wasKeyDown(KeyType::FASTMOVE)) {
  1945. toggleFast();
  1946. } else if (wasKeyDown(KeyType::NOCLIP)) {
  1947. toggleNoClip();
  1948. } else if (wasKeyDown(KeyType::MUTE)) {
  1949. bool new_mute_sound = !g_settings->getBool("mute_sound");
  1950. g_settings->setBool("mute_sound", new_mute_sound);
  1951. if (new_mute_sound)
  1952. m_game_ui->showTranslatedStatusText("Sound muted");
  1953. else
  1954. m_game_ui->showTranslatedStatusText("Sound unmuted");
  1955. } else if (wasKeyDown(KeyType::INC_VOLUME)) {
  1956. float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
  1957. wchar_t buf[100];
  1958. g_settings->setFloat("sound_volume", new_volume);
  1959. const wchar_t *str = wgettext("Volume changed to %d%%");
  1960. swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
  1961. delete[] str;
  1962. m_game_ui->showStatusText(buf);
  1963. } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
  1964. float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
  1965. wchar_t buf[100];
  1966. g_settings->setFloat("sound_volume", new_volume);
  1967. const wchar_t *str = wgettext("Volume changed to %d%%");
  1968. swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, myround(new_volume * 100));
  1969. delete[] str;
  1970. m_game_ui->showStatusText(buf);
  1971. } else if (wasKeyDown(KeyType::CINEMATIC)) {
  1972. toggleCinematic();
  1973. } else if (wasKeyDown(KeyType::SCREENSHOT)) {
  1974. client->makeScreenshot();
  1975. } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
  1976. m_game_ui->toggleHud();
  1977. } else if (wasKeyDown(KeyType::MINIMAP)) {
  1978. toggleMinimap(isKeyDown(KeyType::SNEAK));
  1979. } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
  1980. m_game_ui->toggleChat();
  1981. } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
  1982. toggleFog();
  1983. } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
  1984. toggleUpdateCamera();
  1985. } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
  1986. toggleDebug();
  1987. } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
  1988. m_game_ui->toggleProfiler();
  1989. } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
  1990. increaseViewRange();
  1991. } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
  1992. decreaseViewRange();
  1993. } else if (wasKeyDown(KeyType::RANGESELECT)) {
  1994. toggleFullViewRange();
  1995. } else if (wasKeyDown(KeyType::ZOOM)) {
  1996. checkZoomEnabled();
  1997. } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
  1998. quicktune->next();
  1999. } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
  2000. quicktune->prev();
  2001. } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
  2002. quicktune->inc();
  2003. } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
  2004. quicktune->dec();
  2005. }
  2006. if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
  2007. runData.reset_jump_timer = false;
  2008. runData.jump_timer = 0.0f;
  2009. }
  2010. if (quicktune->hasMessage()) {
  2011. m_game_ui->showStatusText(utf8_to_wide(quicktune->getMessage()));
  2012. }
  2013. }
  2014. void Game::processItemSelection(u16 *new_playeritem)
  2015. {
  2016. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2017. /* Item selection using mouse wheel
  2018. */
  2019. *new_playeritem = client->getPlayerItem();
  2020. s32 wheel = input->getMouseWheel();
  2021. u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
  2022. player->hud_hotbar_itemcount - 1);
  2023. s32 dir = wheel;
  2024. if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
  2025. wasKeyDown(KeyType::HOTBAR_NEXT)) {
  2026. dir = -1;
  2027. }
  2028. if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
  2029. wasKeyDown(KeyType::HOTBAR_PREV)) {
  2030. dir = 1;
  2031. }
  2032. if (dir < 0)
  2033. *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
  2034. else if (dir > 0)
  2035. *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
  2036. // else dir == 0
  2037. /* Item selection using hotbar slot keys
  2038. */
  2039. for (u16 i = 0; i < 23; i++) {
  2040. if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
  2041. if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
  2042. *new_playeritem = i;
  2043. infostream << "Selected item: " << new_playeritem << std::endl;
  2044. }
  2045. break;
  2046. }
  2047. }
  2048. }
  2049. void Game::dropSelectedItem(bool single_item)
  2050. {
  2051. IDropAction *a = new IDropAction();
  2052. a->count = single_item ? 1 : 0;
  2053. a->from_inv.setCurrentPlayer();
  2054. a->from_list = "main";
  2055. a->from_i = client->getPlayerItem();
  2056. client->inventoryAction(a);
  2057. }
  2058. void Game::openInventory()
  2059. {
  2060. /*
  2061. * Don't permit to open inventory is CAO or player doesn't exists.
  2062. * This prevent showing an empty inventory at player load
  2063. */
  2064. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2065. if (!player || !player->getCAO())
  2066. return;
  2067. infostream << "the_game: " << "Launching inventory" << std::endl;
  2068. PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
  2069. InventoryLocation inventoryloc;
  2070. inventoryloc.setCurrentPlayer();
  2071. if (!client->moddingEnabled()
  2072. || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) {
  2073. TextDest *txt_dst = new TextDestPlayerInventory(client);
  2074. create_formspec_menu(&current_formspec, client, &input->joystick, fs_src, txt_dst);
  2075. cur_formname = "";
  2076. current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
  2077. }
  2078. }
  2079. void Game::openConsole(float scale, const wchar_t *line)
  2080. {
  2081. assert(scale > 0.0f && scale <= 1.0f);
  2082. #ifdef __ANDROID__
  2083. porting::showInputDialog(gettext("ok"), "", "", 2);
  2084. m_android_chat_open = true;
  2085. #else
  2086. if (gui_chat_console->isOpenInhibited())
  2087. return;
  2088. gui_chat_console->openConsole(scale);
  2089. if (line) {
  2090. gui_chat_console->setCloseOnEnter(true);
  2091. gui_chat_console->replaceAndAddToHistory(line);
  2092. }
  2093. #endif
  2094. }
  2095. #ifdef __ANDROID__
  2096. void Game::handleAndroidChatInput()
  2097. {
  2098. if (m_android_chat_open && porting::getInputDialogState() == 0) {
  2099. std::string text = porting::getInputDialogValue();
  2100. client->typeChatMessage(utf8_to_wide(text));
  2101. }
  2102. }
  2103. #endif
  2104. void Game::toggleFreeMove()
  2105. {
  2106. bool free_move = !g_settings->getBool("free_move");
  2107. g_settings->set("free_move", bool_to_cstr(free_move));
  2108. if (free_move) {
  2109. if (client->checkPrivilege("fly")) {
  2110. m_game_ui->showTranslatedStatusText("Fly mode enabled");
  2111. } else {
  2112. m_game_ui->showTranslatedStatusText("Fly mode enabled (note: no 'fly' privilege)");
  2113. }
  2114. } else {
  2115. m_game_ui->showTranslatedStatusText("Fly mode disabled");
  2116. }
  2117. }
  2118. void Game::toggleFreeMoveAlt()
  2119. {
  2120. if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
  2121. toggleFreeMove();
  2122. runData.reset_jump_timer = true;
  2123. }
  2124. void Game::toggleFast()
  2125. {
  2126. bool fast_move = !g_settings->getBool("fast_move");
  2127. g_settings->set("fast_move", bool_to_cstr(fast_move));
  2128. if (fast_move) {
  2129. if (client->checkPrivilege("fast")) {
  2130. m_game_ui->showTranslatedStatusText("Fast mode enabled");
  2131. } else {
  2132. m_game_ui->showTranslatedStatusText("Fast mode enabled (note: no 'fast' privilege)");
  2133. }
  2134. } else {
  2135. m_game_ui->showTranslatedStatusText("Fast mode disabled");
  2136. }
  2137. #ifdef __ANDROID__
  2138. m_cache_hold_aux1 = fast_move && has_fast_privs;
  2139. #endif
  2140. }
  2141. void Game::toggleNoClip()
  2142. {
  2143. bool noclip = !g_settings->getBool("noclip");
  2144. g_settings->set("noclip", bool_to_cstr(noclip));
  2145. if (noclip) {
  2146. if (client->checkPrivilege("noclip")) {
  2147. m_game_ui->showTranslatedStatusText("Noclip mode enabled");
  2148. } else {
  2149. m_game_ui->showTranslatedStatusText("Noclip mode enabled (note: no 'noclip' privilege)");
  2150. }
  2151. } else {
  2152. m_game_ui->showTranslatedStatusText("Noclip mode disabled");
  2153. }
  2154. }
  2155. void Game::toggleCinematic()
  2156. {
  2157. bool cinematic = !g_settings->getBool("cinematic");
  2158. g_settings->set("cinematic", bool_to_cstr(cinematic));
  2159. if (cinematic)
  2160. m_game_ui->showTranslatedStatusText("Cinematic mode enabled");
  2161. else
  2162. m_game_ui->showTranslatedStatusText("Cinematic mode disabled");
  2163. }
  2164. // Autoforward by toggling continuous forward.
  2165. void Game::toggleAutoforward()
  2166. {
  2167. bool autorun_enabled = !g_settings->getBool("continuous_forward");
  2168. g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
  2169. if (autorun_enabled)
  2170. m_game_ui->showTranslatedStatusText("Automatic forwards enabled");
  2171. else
  2172. m_game_ui->showTranslatedStatusText("Automatic forwards disabled");
  2173. }
  2174. void Game::toggleMinimap(bool shift_pressed)
  2175. {
  2176. if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap"))
  2177. return;
  2178. if (shift_pressed) {
  2179. mapper->toggleMinimapShape();
  2180. return;
  2181. }
  2182. u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
  2183. MinimapMode mode = MINIMAP_MODE_OFF;
  2184. if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
  2185. mode = mapper->getMinimapMode();
  2186. mode = (MinimapMode)((int)mode + 1);
  2187. // If radar is disabled and in, or switching to, radar mode
  2188. if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
  2189. mode = MINIMAP_MODE_OFF;
  2190. }
  2191. m_game_ui->m_flags.show_minimap = true;
  2192. switch (mode) {
  2193. case MINIMAP_MODE_SURFACEx1:
  2194. m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1");
  2195. break;
  2196. case MINIMAP_MODE_SURFACEx2:
  2197. m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2");
  2198. break;
  2199. case MINIMAP_MODE_SURFACEx4:
  2200. m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4");
  2201. break;
  2202. case MINIMAP_MODE_RADARx1:
  2203. m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1");
  2204. break;
  2205. case MINIMAP_MODE_RADARx2:
  2206. m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2");
  2207. break;
  2208. case MINIMAP_MODE_RADARx4:
  2209. m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4");
  2210. break;
  2211. default:
  2212. mode = MINIMAP_MODE_OFF;
  2213. m_game_ui->m_flags.show_minimap = false;
  2214. if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE)
  2215. m_game_ui->showTranslatedStatusText("Minimap hidden");
  2216. else
  2217. m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod");
  2218. }
  2219. mapper->setMinimapMode(mode);
  2220. }
  2221. void Game::toggleFog()
  2222. {
  2223. m_flags.force_fog_off = !m_flags.force_fog_off;
  2224. if (m_flags.force_fog_off)
  2225. m_game_ui->showTranslatedStatusText("Fog disabled");
  2226. else
  2227. m_game_ui->showTranslatedStatusText("Fog enabled");
  2228. }
  2229. void Game::toggleDebug()
  2230. {
  2231. // Initial / 4x toggle: Chat only
  2232. // 1x toggle: Debug text with chat
  2233. // 2x toggle: Debug text with profiler graph
  2234. // 3x toggle: Debug text and wireframe
  2235. if (!m_game_ui->m_flags.show_debug) {
  2236. m_game_ui->m_flags.show_debug = true;
  2237. m_game_ui->m_flags.show_profiler_graph = false;
  2238. draw_control->show_wireframe = false;
  2239. m_game_ui->showTranslatedStatusText("Debug info shown");
  2240. } else if (!m_game_ui->m_flags.show_profiler_graph && !draw_control->show_wireframe) {
  2241. m_game_ui->m_flags.show_profiler_graph = true;
  2242. m_game_ui->showTranslatedStatusText("Profiler graph shown");
  2243. } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
  2244. m_game_ui->m_flags.show_profiler_graph = false;
  2245. draw_control->show_wireframe = true;
  2246. m_game_ui->showTranslatedStatusText("Wireframe shown");
  2247. } else {
  2248. m_game_ui->m_flags.show_debug = false;
  2249. m_game_ui->m_flags.show_profiler_graph = false;
  2250. draw_control->show_wireframe = false;
  2251. if (client->checkPrivilege("debug")) {
  2252. m_game_ui->showTranslatedStatusText("Debug info, profiler graph, and wireframe hidden");
  2253. } else {
  2254. m_game_ui->showTranslatedStatusText("Debug info and profiler graph hidden");
  2255. }
  2256. }
  2257. }
  2258. void Game::toggleUpdateCamera()
  2259. {
  2260. m_flags.disable_camera_update = !m_flags.disable_camera_update;
  2261. if (m_flags.disable_camera_update)
  2262. m_game_ui->showTranslatedStatusText("Camera update disabled");
  2263. else
  2264. m_game_ui->showTranslatedStatusText("Camera update enabled");
  2265. }
  2266. void Game::increaseViewRange()
  2267. {
  2268. s16 range = g_settings->getS16("viewing_range");
  2269. s16 range_new = range + 10;
  2270. wchar_t buf[255];
  2271. const wchar_t *str;
  2272. if (range_new > 4000) {
  2273. range_new = 4000;
  2274. str = wgettext("Viewing range is at maximum: %d");
  2275. swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
  2276. delete[] str;
  2277. m_game_ui->showStatusText(buf);
  2278. } else {
  2279. str = wgettext("Viewing range changed to %d");
  2280. swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
  2281. delete[] str;
  2282. m_game_ui->showStatusText(buf);
  2283. }
  2284. g_settings->set("viewing_range", itos(range_new));
  2285. }
  2286. void Game::decreaseViewRange()
  2287. {
  2288. s16 range = g_settings->getS16("viewing_range");
  2289. s16 range_new = range - 10;
  2290. wchar_t buf[255];
  2291. const wchar_t *str;
  2292. if (range_new < 20) {
  2293. range_new = 20;
  2294. str = wgettext("Viewing range is at minimum: %d");
  2295. swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
  2296. delete[] str;
  2297. m_game_ui->showStatusText(buf);
  2298. } else {
  2299. str = wgettext("Viewing range changed to %d");
  2300. swprintf(buf, sizeof(buf) / sizeof(wchar_t), str, range_new);
  2301. delete[] str;
  2302. m_game_ui->showStatusText(buf);
  2303. }
  2304. g_settings->set("viewing_range", itos(range_new));
  2305. }
  2306. void Game::toggleFullViewRange()
  2307. {
  2308. draw_control->range_all = !draw_control->range_all;
  2309. if (draw_control->range_all)
  2310. m_game_ui->showTranslatedStatusText("Enabled unlimited viewing range");
  2311. else
  2312. m_game_ui->showTranslatedStatusText("Disabled unlimited viewing range");
  2313. }
  2314. void Game::checkZoomEnabled()
  2315. {
  2316. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2317. if (player->getZoomFOV() < 0.001f)
  2318. m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod");
  2319. }
  2320. void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
  2321. {
  2322. if ((device->isWindowActive() && device->isWindowFocused()
  2323. && !isMenuActive()) || random_input) {
  2324. #ifndef __ANDROID__
  2325. if (!random_input) {
  2326. // Mac OSX gets upset if this is set every frame
  2327. if (device->getCursorControl()->isVisible())
  2328. device->getCursorControl()->setVisible(false);
  2329. }
  2330. #endif
  2331. if (m_first_loop_after_window_activation)
  2332. m_first_loop_after_window_activation = false;
  2333. else
  2334. updateCameraOrientation(cam, dtime);
  2335. input->setMousePos((driver->getScreenSize().Width / 2),
  2336. (driver->getScreenSize().Height / 2));
  2337. } else {
  2338. #ifndef ANDROID
  2339. // Mac OSX gets upset if this is set every frame
  2340. if (!device->getCursorControl()->isVisible())
  2341. device->getCursorControl()->setVisible(true);
  2342. #endif
  2343. m_first_loop_after_window_activation = true;
  2344. }
  2345. }
  2346. void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
  2347. {
  2348. #ifdef HAVE_TOUCHSCREENGUI
  2349. if (g_touchscreengui) {
  2350. cam->camera_yaw += g_touchscreengui->getYawChange();
  2351. cam->camera_pitch = g_touchscreengui->getPitch();
  2352. } else {
  2353. #endif
  2354. s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
  2355. s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
  2356. if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
  2357. dy = -dy;
  2358. }
  2359. cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
  2360. cam->camera_pitch += dy * m_cache_mouse_sensitivity;
  2361. #ifdef HAVE_TOUCHSCREENGUI
  2362. }
  2363. #endif
  2364. if (m_cache_enable_joysticks) {
  2365. f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
  2366. cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
  2367. cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
  2368. }
  2369. cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
  2370. }
  2371. void Game::updatePlayerControl(const CameraOrientation &cam)
  2372. {
  2373. //TimeTaker tt("update player control", NULL, PRECISION_NANO);
  2374. // DO NOT use the isKeyDown method for the forward, backward, left, right
  2375. // buttons, as the code that uses the controls needs to be able to
  2376. // distinguish between the two in order to know when to use joysticks.
  2377. PlayerControl control(
  2378. input->isKeyDown(keycache.key[KeyType::FORWARD]),
  2379. input->isKeyDown(keycache.key[KeyType::BACKWARD]),
  2380. input->isKeyDown(keycache.key[KeyType::LEFT]),
  2381. input->isKeyDown(keycache.key[KeyType::RIGHT]),
  2382. isKeyDown(KeyType::JUMP),
  2383. isKeyDown(KeyType::SPECIAL1),
  2384. isKeyDown(KeyType::SNEAK),
  2385. isKeyDown(KeyType::ZOOM),
  2386. isLeftPressed(),
  2387. isRightPressed(),
  2388. cam.camera_pitch,
  2389. cam.camera_yaw,
  2390. input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
  2391. input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
  2392. );
  2393. u32 keypress_bits =
  2394. ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
  2395. ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
  2396. ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
  2397. ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
  2398. ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
  2399. ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
  2400. ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
  2401. ( (u32)(isLeftPressed() & 0x1) << 7) |
  2402. ( (u32)(isRightPressed() & 0x1) << 8
  2403. );
  2404. #ifdef ANDROID
  2405. /* For Android, simulate holding down AUX1 (fast move) if the user has
  2406. * the fast_move setting toggled on. If there is an aux1 key defined for
  2407. * Android then its meaning is inverted (i.e. holding aux1 means walk and
  2408. * not fast)
  2409. */
  2410. if (m_cache_hold_aux1) {
  2411. control.aux1 = control.aux1 ^ true;
  2412. keypress_bits ^= ((u32)(1U << 5));
  2413. }
  2414. #endif
  2415. client->setPlayerControl(control);
  2416. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2417. player->keyPressed = keypress_bits;
  2418. //tt.stop();
  2419. }
  2420. inline void Game::step(f32 *dtime)
  2421. {
  2422. bool can_be_and_is_paused =
  2423. (simple_singleplayer_mode && g_menumgr.pausesGame());
  2424. if (can_be_and_is_paused) { // This is for a singleplayer server
  2425. *dtime = 0; // No time passes
  2426. } else {
  2427. if (server) {
  2428. server->step(*dtime);
  2429. }
  2430. client->step(*dtime);
  2431. }
  2432. }
  2433. const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
  2434. {&Game::handleClientEvent_None},
  2435. {&Game::handleClientEvent_PlayerDamage},
  2436. {&Game::handleClientEvent_PlayerForceMove},
  2437. {&Game::handleClientEvent_Deathscreen},
  2438. {&Game::handleClientEvent_ShowFormSpec},
  2439. {&Game::handleClientEvent_ShowLocalFormSpec},
  2440. {&Game::handleClientEvent_HandleParticleEvent},
  2441. {&Game::handleClientEvent_HandleParticleEvent},
  2442. {&Game::handleClientEvent_HandleParticleEvent},
  2443. {&Game::handleClientEvent_HudAdd},
  2444. {&Game::handleClientEvent_HudRemove},
  2445. {&Game::handleClientEvent_HudChange},
  2446. {&Game::handleClientEvent_SetSky},
  2447. {&Game::handleClientEvent_OverrideDayNigthRatio},
  2448. {&Game::handleClientEvent_CloudParams},
  2449. };
  2450. void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
  2451. {
  2452. FATAL_ERROR("ClientEvent type None received");
  2453. }
  2454. void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
  2455. {
  2456. if (client->getHP() == 0)
  2457. return;
  2458. if (client->moddingEnabled()) {
  2459. client->getScript()->on_damage_taken(event->player_damage.amount);
  2460. }
  2461. runData.damage_flash += 95.0 + 3.2 * event->player_damage.amount;
  2462. runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
  2463. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2464. player->hurt_tilt_timer = 1.5;
  2465. player->hurt_tilt_strength =
  2466. rangelim(event->player_damage.amount / 4, 1.0, 4.0);
  2467. client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
  2468. }
  2469. void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
  2470. {
  2471. cam->camera_yaw = event->player_force_move.yaw;
  2472. cam->camera_pitch = event->player_force_move.pitch;
  2473. }
  2474. void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
  2475. {
  2476. // This should be enabled for death formspec in builtin
  2477. client->getScript()->on_death();
  2478. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2479. /* Handle visualization */
  2480. runData.damage_flash = 0;
  2481. player->hurt_tilt_timer = 0;
  2482. player->hurt_tilt_strength = 0;
  2483. }
  2484. void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
  2485. {
  2486. if (event->show_formspec.formspec->empty()) {
  2487. if (current_formspec && (event->show_formspec.formname->empty()
  2488. || *(event->show_formspec.formname) == cur_formname)) {
  2489. current_formspec->quitMenu();
  2490. }
  2491. } else {
  2492. FormspecFormSource *fs_src =
  2493. new FormspecFormSource(*(event->show_formspec.formspec));
  2494. TextDestPlayerInventory *txt_dst =
  2495. new TextDestPlayerInventory(client, *(event->show_formspec.formname));
  2496. create_formspec_menu(&current_formspec, client, &input->joystick,
  2497. fs_src, txt_dst);
  2498. cur_formname = *(event->show_formspec.formname);
  2499. }
  2500. delete event->show_formspec.formspec;
  2501. delete event->show_formspec.formname;
  2502. }
  2503. void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
  2504. {
  2505. FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
  2506. LocalFormspecHandler *txt_dst =
  2507. new LocalFormspecHandler(*event->show_formspec.formname, client);
  2508. create_formspec_menu(&current_formspec, client, &input->joystick, fs_src, txt_dst);
  2509. delete event->show_formspec.formspec;
  2510. delete event->show_formspec.formname;
  2511. }
  2512. void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
  2513. CameraOrientation *cam)
  2514. {
  2515. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2516. client->getParticleManager()->handleParticleEvent(event, client, player);
  2517. }
  2518. void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
  2519. {
  2520. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2521. u32 id = event->hudadd.id;
  2522. HudElement *e = player->getHud(id);
  2523. if (e != NULL) {
  2524. delete event->hudadd.pos;
  2525. delete event->hudadd.name;
  2526. delete event->hudadd.scale;
  2527. delete event->hudadd.text;
  2528. delete event->hudadd.align;
  2529. delete event->hudadd.offset;
  2530. delete event->hudadd.world_pos;
  2531. delete event->hudadd.size;
  2532. return;
  2533. }
  2534. e = new HudElement;
  2535. e->type = (HudElementType)event->hudadd.type;
  2536. e->pos = *event->hudadd.pos;
  2537. e->name = *event->hudadd.name;
  2538. e->scale = *event->hudadd.scale;
  2539. e->text = *event->hudadd.text;
  2540. e->number = event->hudadd.number;
  2541. e->item = event->hudadd.item;
  2542. e->dir = event->hudadd.dir;
  2543. e->align = *event->hudadd.align;
  2544. e->offset = *event->hudadd.offset;
  2545. e->world_pos = *event->hudadd.world_pos;
  2546. e->size = *event->hudadd.size;
  2547. u32 new_id = player->addHud(e);
  2548. //if this isn't true our huds aren't consistent
  2549. sanity_check(new_id == id);
  2550. delete event->hudadd.pos;
  2551. delete event->hudadd.name;
  2552. delete event->hudadd.scale;
  2553. delete event->hudadd.text;
  2554. delete event->hudadd.align;
  2555. delete event->hudadd.offset;
  2556. delete event->hudadd.world_pos;
  2557. delete event->hudadd.size;
  2558. }
  2559. void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
  2560. {
  2561. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2562. HudElement *e = player->removeHud(event->hudrm.id);
  2563. delete e;
  2564. }
  2565. void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
  2566. {
  2567. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2568. u32 id = event->hudchange.id;
  2569. HudElement *e = player->getHud(id);
  2570. if (e == NULL) {
  2571. delete event->hudchange.v3fdata;
  2572. delete event->hudchange.v2fdata;
  2573. delete event->hudchange.sdata;
  2574. delete event->hudchange.v2s32data;
  2575. return;
  2576. }
  2577. switch (event->hudchange.stat) {
  2578. case HUD_STAT_POS:
  2579. e->pos = *event->hudchange.v2fdata;
  2580. break;
  2581. case HUD_STAT_NAME:
  2582. e->name = *event->hudchange.sdata;
  2583. break;
  2584. case HUD_STAT_SCALE:
  2585. e->scale = *event->hudchange.v2fdata;
  2586. break;
  2587. case HUD_STAT_TEXT:
  2588. e->text = *event->hudchange.sdata;
  2589. break;
  2590. case HUD_STAT_NUMBER:
  2591. e->number = event->hudchange.data;
  2592. break;
  2593. case HUD_STAT_ITEM:
  2594. e->item = event->hudchange.data;
  2595. break;
  2596. case HUD_STAT_DIR:
  2597. e->dir = event->hudchange.data;
  2598. break;
  2599. case HUD_STAT_ALIGN:
  2600. e->align = *event->hudchange.v2fdata;
  2601. break;
  2602. case HUD_STAT_OFFSET:
  2603. e->offset = *event->hudchange.v2fdata;
  2604. break;
  2605. case HUD_STAT_WORLD_POS:
  2606. e->world_pos = *event->hudchange.v3fdata;
  2607. break;
  2608. case HUD_STAT_SIZE:
  2609. e->size = *event->hudchange.v2s32data;
  2610. break;
  2611. }
  2612. delete event->hudchange.v3fdata;
  2613. delete event->hudchange.v2fdata;
  2614. delete event->hudchange.sdata;
  2615. delete event->hudchange.v2s32data;
  2616. }
  2617. void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
  2618. {
  2619. sky->setVisible(false);
  2620. // Whether clouds are visible in front of a custom skybox
  2621. sky->setCloudsEnabled(event->set_sky.clouds);
  2622. if (skybox) {
  2623. skybox->remove();
  2624. skybox = NULL;
  2625. }
  2626. // Handle according to type
  2627. if (*event->set_sky.type == "regular") {
  2628. sky->setVisible(true);
  2629. sky->setCloudsEnabled(true);
  2630. } else if (*event->set_sky.type == "skybox" &&
  2631. event->set_sky.params->size() == 6) {
  2632. sky->setFallbackBgColor(*event->set_sky.bgcolor);
  2633. skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
  2634. texture_src->getTextureForMesh((*event->set_sky.params)[0]),
  2635. texture_src->getTextureForMesh((*event->set_sky.params)[1]),
  2636. texture_src->getTextureForMesh((*event->set_sky.params)[2]),
  2637. texture_src->getTextureForMesh((*event->set_sky.params)[3]),
  2638. texture_src->getTextureForMesh((*event->set_sky.params)[4]),
  2639. texture_src->getTextureForMesh((*event->set_sky.params)[5]));
  2640. }
  2641. // Handle everything else as plain color
  2642. else {
  2643. if (*event->set_sky.type != "plain")
  2644. infostream << "Unknown sky type: "
  2645. << (*event->set_sky.type) << std::endl;
  2646. sky->setFallbackBgColor(*event->set_sky.bgcolor);
  2647. }
  2648. delete event->set_sky.bgcolor;
  2649. delete event->set_sky.type;
  2650. delete event->set_sky.params;
  2651. }
  2652. void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
  2653. CameraOrientation *cam)
  2654. {
  2655. client->getEnv().setDayNightRatioOverride(
  2656. event->override_day_night_ratio.do_override,
  2657. event->override_day_night_ratio.ratio_f * 1000.0f);
  2658. }
  2659. void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
  2660. {
  2661. if (!clouds)
  2662. return;
  2663. clouds->setDensity(event->cloud_params.density);
  2664. clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
  2665. clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
  2666. clouds->setHeight(event->cloud_params.height);
  2667. clouds->setThickness(event->cloud_params.thickness);
  2668. clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
  2669. }
  2670. void Game::processClientEvents(CameraOrientation *cam)
  2671. {
  2672. while (client->hasClientEvents()) {
  2673. std::unique_ptr<ClientEvent> event(client->getClientEvent());
  2674. FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
  2675. const ClientEventHandler& evHandler = clientEventHandler[event->type];
  2676. (this->*evHandler.handler)(event.get(), cam);
  2677. }
  2678. }
  2679. void Game::updateChat(f32 dtime, const v2u32 &screensize)
  2680. {
  2681. // Add chat log output for errors to be shown in chat
  2682. static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
  2683. // Get new messages from error log buffer
  2684. while (!chat_log_error_buf.empty()) {
  2685. std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
  2686. if (!g_settings->getBool("disable_escape_sequences")) {
  2687. error_message = L"\x1b(c@red)";
  2688. error_message.append(error_message).append(L"\x1b(c@white)");
  2689. }
  2690. chat_backend->addMessage(L"", error_message);
  2691. }
  2692. // Get new messages from client
  2693. std::wstring message;
  2694. while (client->getChatMessage(message)) {
  2695. chat_backend->addUnparsedMessage(message);
  2696. }
  2697. // Remove old messages
  2698. chat_backend->step(dtime);
  2699. // Display all messages in a static text element
  2700. m_game_ui->setChatText(chat_backend->getRecentChat(),
  2701. chat_backend->getRecentBuffer().getLineCount());
  2702. }
  2703. void Game::updateCamera(u32 busy_time, f32 dtime)
  2704. {
  2705. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2706. /*
  2707. For interaction purposes, get info about the held item
  2708. - What item is it?
  2709. - Is it a usable item?
  2710. - Can it point to liquids?
  2711. */
  2712. ItemStack playeritem;
  2713. {
  2714. InventoryList *mlist = local_inventory->getList("main");
  2715. if (mlist && client->getPlayerItem() < mlist->getSize())
  2716. playeritem = mlist->getItem(client->getPlayerItem());
  2717. }
  2718. if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
  2719. InventoryList *hlist = local_inventory->getList("hand");
  2720. if (hlist)
  2721. playeritem = hlist->getItem(0);
  2722. }
  2723. ToolCapabilities playeritem_toolcap =
  2724. playeritem.getToolCapabilities(itemdef_manager);
  2725. v3s16 old_camera_offset = camera->getOffset();
  2726. if (wasKeyDown(KeyType::CAMERA_MODE)) {
  2727. GenericCAO *playercao = player->getCAO();
  2728. // If playercao not loaded, don't change camera
  2729. if (!playercao)
  2730. return;
  2731. camera->toggleCameraMode();
  2732. playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
  2733. playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
  2734. }
  2735. float full_punch_interval = playeritem_toolcap.full_punch_interval;
  2736. float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
  2737. tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
  2738. camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
  2739. camera->step(dtime);
  2740. v3f camera_position = camera->getPosition();
  2741. v3f camera_direction = camera->getDirection();
  2742. f32 camera_fov = camera->getFovMax();
  2743. v3s16 camera_offset = camera->getOffset();
  2744. m_camera_offset_changed = (camera_offset != old_camera_offset);
  2745. if (!m_flags.disable_camera_update) {
  2746. client->getEnv().getClientMap().updateCamera(camera_position,
  2747. camera_direction, camera_fov, camera_offset);
  2748. if (m_camera_offset_changed) {
  2749. client->updateCameraOffset(camera_offset);
  2750. client->getEnv().updateCameraOffset(camera_offset);
  2751. if (clouds)
  2752. clouds->updateCameraOffset(camera_offset);
  2753. }
  2754. }
  2755. }
  2756. void Game::updateSound(f32 dtime)
  2757. {
  2758. // Update sound listener
  2759. v3s16 camera_offset = camera->getOffset();
  2760. sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
  2761. v3f(0, 0, 0), // velocity
  2762. camera->getDirection(),
  2763. camera->getCameraNode()->getUpVector());
  2764. bool mute_sound = g_settings->getBool("mute_sound");
  2765. if (mute_sound) {
  2766. sound->setListenerGain(0.0f);
  2767. } else {
  2768. // Check if volume is in the proper range, else fix it.
  2769. float old_volume = g_settings->getFloat("sound_volume");
  2770. float new_volume = rangelim(old_volume, 0.0f, 1.0f);
  2771. sound->setListenerGain(new_volume);
  2772. if (old_volume != new_volume) {
  2773. g_settings->setFloat("sound_volume", new_volume);
  2774. }
  2775. }
  2776. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2777. // Tell the sound maker whether to make footstep sounds
  2778. soundmaker->makes_footstep_sound = player->makes_footstep_sound;
  2779. // Update sound maker
  2780. if (player->makes_footstep_sound)
  2781. soundmaker->step(dtime);
  2782. ClientMap &map = client->getEnv().getClientMap();
  2783. MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
  2784. soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
  2785. }
  2786. void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
  2787. {
  2788. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2789. ItemStack playeritem;
  2790. {
  2791. InventoryList *mlist = local_inventory->getList("main");
  2792. if (mlist && client->getPlayerItem() < mlist->getSize())
  2793. playeritem = mlist->getItem(client->getPlayerItem());
  2794. }
  2795. const ItemDefinition &playeritem_def =
  2796. playeritem.getDefinition(itemdef_manager);
  2797. InventoryList *hlist = local_inventory->getList("hand");
  2798. const ItemDefinition &hand_def =
  2799. hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
  2800. v3f player_position = player->getPosition();
  2801. v3f camera_position = camera->getPosition();
  2802. v3f camera_direction = camera->getDirection();
  2803. v3s16 camera_offset = camera->getOffset();
  2804. /*
  2805. Calculate what block is the crosshair pointing to
  2806. */
  2807. f32 d = playeritem_def.range; // max. distance
  2808. f32 d_hand = hand_def.range;
  2809. if (d < 0 && d_hand >= 0)
  2810. d = d_hand;
  2811. else if (d < 0)
  2812. d = 4.0;
  2813. core::line3d<f32> shootline;
  2814. if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
  2815. shootline = core::line3d<f32>(camera_position,
  2816. camera_position + camera_direction * BS * d);
  2817. } else {
  2818. // prevent player pointing anything in front-view
  2819. shootline = core::line3d<f32>(camera_position,camera_position);
  2820. }
  2821. #ifdef HAVE_TOUCHSCREENGUI
  2822. if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
  2823. shootline = g_touchscreengui->getShootline();
  2824. // Scale shootline to the acual distance the player can reach
  2825. shootline.end = shootline.start
  2826. + shootline.getVector().normalize() * BS * d;
  2827. shootline.start += intToFloat(camera_offset, BS);
  2828. shootline.end += intToFloat(camera_offset, BS);
  2829. }
  2830. #endif
  2831. PointedThing pointed = updatePointedThing(shootline,
  2832. playeritem_def.liquids_pointable,
  2833. !runData.ldown_for_dig,
  2834. camera_offset);
  2835. if (pointed != runData.pointed_old) {
  2836. infostream << "Pointing at " << pointed.dump() << std::endl;
  2837. hud->updateSelectionMesh(camera_offset);
  2838. }
  2839. if (runData.digging_blocked && !isLeftPressed()) {
  2840. // allow digging again if button is not pressed
  2841. runData.digging_blocked = false;
  2842. }
  2843. /*
  2844. Stop digging when
  2845. - releasing left mouse button
  2846. - pointing away from node
  2847. */
  2848. if (runData.digging) {
  2849. if (getLeftReleased()) {
  2850. infostream << "Left button released"
  2851. << " (stopped digging)" << std::endl;
  2852. runData.digging = false;
  2853. } else if (pointed != runData.pointed_old) {
  2854. if (pointed.type == POINTEDTHING_NODE
  2855. && runData.pointed_old.type == POINTEDTHING_NODE
  2856. && pointed.node_undersurface
  2857. == runData.pointed_old.node_undersurface) {
  2858. // Still pointing to the same node, but a different face.
  2859. // Don't reset.
  2860. } else {
  2861. infostream << "Pointing away from node"
  2862. << " (stopped digging)" << std::endl;
  2863. runData.digging = false;
  2864. hud->updateSelectionMesh(camera_offset);
  2865. }
  2866. }
  2867. if (!runData.digging) {
  2868. client->interact(1, runData.pointed_old);
  2869. client->setCrack(-1, v3s16(0, 0, 0));
  2870. runData.dig_time = 0.0;
  2871. }
  2872. } else if (runData.dig_instantly && getLeftReleased()) {
  2873. // Remove e.g. torches faster when clicking instead of holding LMB
  2874. runData.nodig_delay_timer = 0;
  2875. runData.dig_instantly = false;
  2876. }
  2877. if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
  2878. runData.ldown_for_dig = false;
  2879. }
  2880. runData.left_punch = false;
  2881. soundmaker->m_player_leftpunch_sound.name = "";
  2882. // Prepare for repeating, unless we're not supposed to
  2883. if (isRightPressed() && !g_settings->getBool("safe_dig_and_place"))
  2884. runData.repeat_rightclick_timer += dtime;
  2885. else
  2886. runData.repeat_rightclick_timer = 0;
  2887. if (playeritem_def.usable && isLeftPressed()) {
  2888. if (getLeftClicked() && (!client->moddingEnabled()
  2889. || !client->getScript()->on_item_use(playeritem, pointed)))
  2890. client->interact(4, pointed);
  2891. } else if (pointed.type == POINTEDTHING_NODE) {
  2892. ToolCapabilities playeritem_toolcap =
  2893. playeritem.getToolCapabilities(itemdef_manager);
  2894. if (playeritem.name.empty()) {
  2895. const ToolCapabilities *handToolcap = hlist
  2896. ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
  2897. : itemdef_manager->get("").tool_capabilities;
  2898. if (handToolcap != nullptr)
  2899. playeritem_toolcap = *handToolcap;
  2900. }
  2901. handlePointingAtNode(pointed, playeritem_def, playeritem,
  2902. playeritem_toolcap, dtime);
  2903. } else if (pointed.type == POINTEDTHING_OBJECT) {
  2904. handlePointingAtObject(pointed, playeritem, player_position, show_debug);
  2905. } else if (isLeftPressed()) {
  2906. // When button is held down in air, show continuous animation
  2907. runData.left_punch = true;
  2908. } else if (getRightClicked()) {
  2909. handlePointingAtNothing(playeritem);
  2910. }
  2911. runData.pointed_old = pointed;
  2912. if (runData.left_punch || getLeftClicked())
  2913. camera->setDigging(0); // left click animation
  2914. input->resetLeftClicked();
  2915. input->resetRightClicked();
  2916. input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
  2917. input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
  2918. input->resetLeftReleased();
  2919. input->resetRightReleased();
  2920. input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
  2921. input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
  2922. }
  2923. PointedThing Game::updatePointedThing(
  2924. const core::line3d<f32> &shootline,
  2925. bool liquids_pointable,
  2926. bool look_for_object,
  2927. const v3s16 &camera_offset)
  2928. {
  2929. std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
  2930. selectionboxes->clear();
  2931. hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
  2932. static thread_local const bool show_entity_selectionbox = g_settings->getBool(
  2933. "show_entity_selectionbox");
  2934. ClientEnvironment &env = client->getEnv();
  2935. ClientMap &map = env.getClientMap();
  2936. INodeDefManager *nodedef = map.getNodeDefManager();
  2937. runData.selected_object = NULL;
  2938. RaycastState s(shootline, look_for_object, liquids_pointable);
  2939. PointedThing result;
  2940. env.continueRaycast(&s, &result);
  2941. if (result.type == POINTEDTHING_OBJECT) {
  2942. runData.selected_object = client->getEnv().getActiveObject(result.object_id);
  2943. aabb3f selection_box;
  2944. if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
  2945. runData.selected_object->getSelectionBox(&selection_box)) {
  2946. v3f pos = runData.selected_object->getPosition();
  2947. selectionboxes->push_back(aabb3f(selection_box));
  2948. hud->setSelectionPos(pos, camera_offset);
  2949. }
  2950. } else if (result.type == POINTEDTHING_NODE) {
  2951. // Update selection boxes
  2952. MapNode n = map.getNodeNoEx(result.node_undersurface);
  2953. std::vector<aabb3f> boxes;
  2954. n.getSelectionBoxes(nodedef, &boxes,
  2955. n.getNeighbors(result.node_undersurface, &map));
  2956. f32 d = 0.002 * BS;
  2957. for (std::vector<aabb3f>::const_iterator i = boxes.begin();
  2958. i != boxes.end(); ++i) {
  2959. aabb3f box = *i;
  2960. box.MinEdge -= v3f(d, d, d);
  2961. box.MaxEdge += v3f(d, d, d);
  2962. selectionboxes->push_back(box);
  2963. }
  2964. hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
  2965. camera_offset);
  2966. hud->setSelectedFaceNormal(v3f(
  2967. result.intersection_normal.X,
  2968. result.intersection_normal.Y,
  2969. result.intersection_normal.Z));
  2970. }
  2971. // Update selection mesh light level and vertex colors
  2972. if (!selectionboxes->empty()) {
  2973. v3f pf = hud->getSelectionPos();
  2974. v3s16 p = floatToInt(pf, BS);
  2975. // Get selection mesh light level
  2976. MapNode n = map.getNodeNoEx(p);
  2977. u16 node_light = getInteriorLight(n, -1, nodedef);
  2978. u16 light_level = node_light;
  2979. for (const v3s16 &dir : g_6dirs) {
  2980. n = map.getNodeNoEx(p + dir);
  2981. node_light = getInteriorLight(n, -1, nodedef);
  2982. if (node_light > light_level)
  2983. light_level = node_light;
  2984. }
  2985. u32 daynight_ratio = client->getEnv().getDayNightRatio();
  2986. video::SColor c;
  2987. final_color_blend(&c, light_level, daynight_ratio);
  2988. // Modify final color a bit with time
  2989. u32 timer = porting::getTimeMs() % 5000;
  2990. float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
  2991. float sin_r = 0.08 * sin(timerf);
  2992. float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
  2993. float sin_b = 0.08 * sin(timerf + irr::core::PI);
  2994. c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
  2995. c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
  2996. c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
  2997. // Set mesh final color
  2998. hud->setSelectionMeshColor(c);
  2999. }
  3000. return result;
  3001. }
  3002. void Game::handlePointingAtNothing(const ItemStack &playerItem)
  3003. {
  3004. infostream << "Right Clicked in Air" << std::endl;
  3005. PointedThing fauxPointed;
  3006. fauxPointed.type = POINTEDTHING_NOTHING;
  3007. client->interact(5, fauxPointed);
  3008. }
  3009. void Game::handlePointingAtNode(const PointedThing &pointed,
  3010. const ItemDefinition &playeritem_def, const ItemStack &playeritem,
  3011. const ToolCapabilities &playeritem_toolcap, f32 dtime)
  3012. {
  3013. v3s16 nodepos = pointed.node_undersurface;
  3014. v3s16 neighbourpos = pointed.node_abovesurface;
  3015. /*
  3016. Check information text of node
  3017. */
  3018. ClientMap &map = client->getEnv().getClientMap();
  3019. if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
  3020. && !runData.digging_blocked
  3021. && client->checkPrivilege("interact")) {
  3022. handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
  3023. }
  3024. // This should be done after digging handling
  3025. NodeMetadata *meta = map.getNodeMetadata(nodepos);
  3026. if (meta) {
  3027. m_game_ui->setInfoText(unescape_translate(utf8_to_wide(
  3028. meta->getString("infotext"))));
  3029. } else {
  3030. MapNode n = map.getNodeNoEx(nodepos);
  3031. if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
  3032. m_game_ui->setInfoText(L"Unknown node: " +
  3033. utf8_to_wide(nodedef_manager->get(n).name));
  3034. }
  3035. }
  3036. if ((getRightClicked() ||
  3037. runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
  3038. client->checkPrivilege("interact")) {
  3039. runData.repeat_rightclick_timer = 0;
  3040. infostream << "Ground right-clicked" << std::endl;
  3041. if (meta && !meta->getString("formspec").empty() && !random_input
  3042. && !isKeyDown(KeyType::SNEAK)) {
  3043. // Report right click to server
  3044. if (nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
  3045. client->interact(3, pointed);
  3046. }
  3047. infostream << "Launching custom inventory view" << std::endl;
  3048. InventoryLocation inventoryloc;
  3049. inventoryloc.setNodeMeta(nodepos);
  3050. NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
  3051. &client->getEnv().getClientMap(), nodepos);
  3052. TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
  3053. create_formspec_menu(&current_formspec, client,
  3054. &input->joystick, fs_src, txt_dst);
  3055. cur_formname = "";
  3056. current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
  3057. } else {
  3058. // Report right click to server
  3059. camera->setDigging(1); // right click animation (always shown for feedback)
  3060. // If the wielded item has node placement prediction,
  3061. // make that happen
  3062. bool placed = nodePlacementPrediction(*client,
  3063. playeritem_def, playeritem,
  3064. nodepos, neighbourpos);
  3065. if (placed) {
  3066. // Report to server
  3067. client->interact(3, pointed);
  3068. // Read the sound
  3069. soundmaker->m_player_rightpunch_sound =
  3070. playeritem_def.sound_place;
  3071. if (client->moddingEnabled())
  3072. client->getScript()->on_placenode(pointed, playeritem_def);
  3073. } else {
  3074. soundmaker->m_player_rightpunch_sound =
  3075. SimpleSoundSpec();
  3076. if (playeritem_def.node_placement_prediction.empty() ||
  3077. nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
  3078. client->interact(3, pointed); // Report to server
  3079. } else {
  3080. soundmaker->m_player_rightpunch_sound =
  3081. playeritem_def.sound_place_failed;
  3082. }
  3083. }
  3084. }
  3085. }
  3086. }
  3087. void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
  3088. const v3f &player_position, bool show_debug)
  3089. {
  3090. std::wstring infotext = unescape_translate(
  3091. utf8_to_wide(runData.selected_object->infoText()));
  3092. if (show_debug) {
  3093. if (!infotext.empty()) {
  3094. infotext += L"\n";
  3095. }
  3096. infotext += utf8_to_wide(runData.selected_object->debugInfoText());
  3097. }
  3098. m_game_ui->setInfoText(infotext);
  3099. if (isLeftPressed()) {
  3100. bool do_punch = false;
  3101. bool do_punch_damage = false;
  3102. if (runData.object_hit_delay_timer <= 0.0) {
  3103. do_punch = true;
  3104. do_punch_damage = true;
  3105. runData.object_hit_delay_timer = object_hit_delay;
  3106. }
  3107. if (getLeftClicked())
  3108. do_punch = true;
  3109. if (do_punch) {
  3110. infostream << "Left-clicked object" << std::endl;
  3111. runData.left_punch = true;
  3112. }
  3113. if (do_punch_damage) {
  3114. // Report direct punch
  3115. v3f objpos = runData.selected_object->getPosition();
  3116. v3f dir = (objpos - player_position).normalize();
  3117. ItemStack item = playeritem;
  3118. if (playeritem.name.empty()) {
  3119. InventoryList *hlist = local_inventory->getList("hand");
  3120. if (hlist) {
  3121. item = hlist->getItem(0);
  3122. }
  3123. }
  3124. bool disable_send = runData.selected_object->directReportPunch(
  3125. dir, &item, runData.time_from_last_punch);
  3126. runData.time_from_last_punch = 0;
  3127. if (!disable_send)
  3128. client->interact(0, pointed);
  3129. }
  3130. } else if (getRightClicked()) {
  3131. infostream << "Right-clicked object" << std::endl;
  3132. client->interact(3, pointed); // place
  3133. }
  3134. }
  3135. void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
  3136. const ToolCapabilities &playeritem_toolcap, f32 dtime)
  3137. {
  3138. LocalPlayer *player = client->getEnv().getLocalPlayer();
  3139. ClientMap &map = client->getEnv().getClientMap();
  3140. MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
  3141. // NOTE: Similar piece of code exists on the server side for
  3142. // cheat detection.
  3143. // Get digging parameters
  3144. DigParams params = getDigParams(nodedef_manager->get(n).groups,
  3145. &playeritem_toolcap);
  3146. // If can't dig, try hand
  3147. if (!params.diggable) {
  3148. InventoryList *hlist = local_inventory->getList("hand");
  3149. const ToolCapabilities *tp = hlist
  3150. ? &hlist->getItem(0).getToolCapabilities(itemdef_manager)
  3151. : itemdef_manager->get("").tool_capabilities;
  3152. if (tp)
  3153. params = getDigParams(nodedef_manager->get(n).groups, tp);
  3154. }
  3155. if (!params.diggable) {
  3156. // I guess nobody will wait for this long
  3157. runData.dig_time_complete = 10000000.0;
  3158. } else {
  3159. runData.dig_time_complete = params.time;
  3160. if (m_cache_enable_particles) {
  3161. const ContentFeatures &features = client->getNodeDefManager()->get(n);
  3162. client->getParticleManager()->addNodeParticle(client,
  3163. player, nodepos, n, features);
  3164. }
  3165. }
  3166. if (!runData.digging) {
  3167. infostream << "Started digging" << std::endl;
  3168. runData.dig_instantly = runData.dig_time_complete == 0;
  3169. if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
  3170. return;
  3171. client->interact(0, pointed);
  3172. runData.digging = true;
  3173. runData.ldown_for_dig = true;
  3174. }
  3175. if (!runData.dig_instantly) {
  3176. runData.dig_index = (float)crack_animation_length
  3177. * runData.dig_time
  3178. / runData.dig_time_complete;
  3179. } else {
  3180. // This is for e.g. torches
  3181. runData.dig_index = crack_animation_length;
  3182. }
  3183. SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
  3184. if (sound_dig.exists() && params.diggable) {
  3185. if (sound_dig.name == "__group") {
  3186. if (!params.main_group.empty()) {
  3187. soundmaker->m_player_leftpunch_sound.gain = 0.5;
  3188. soundmaker->m_player_leftpunch_sound.name =
  3189. std::string("default_dig_") +
  3190. params.main_group;
  3191. }
  3192. } else {
  3193. soundmaker->m_player_leftpunch_sound = sound_dig;
  3194. }
  3195. }
  3196. // Don't show cracks if not diggable
  3197. if (runData.dig_time_complete >= 100000.0) {
  3198. } else if (runData.dig_index < crack_animation_length) {
  3199. //TimeTaker timer("client.setTempMod");
  3200. //infostream<<"dig_index="<<dig_index<<std::endl;
  3201. client->setCrack(runData.dig_index, nodepos);
  3202. } else {
  3203. infostream << "Digging completed" << std::endl;
  3204. client->setCrack(-1, v3s16(0, 0, 0));
  3205. runData.dig_time = 0;
  3206. runData.digging = false;
  3207. // we successfully dug, now block it from repeating if we want to be safe
  3208. if (g_settings->getBool("safe_dig_and_place"))
  3209. runData.digging_blocked = true;
  3210. runData.nodig_delay_timer =
  3211. runData.dig_time_complete / (float)crack_animation_length;
  3212. // We don't want a corresponding delay to very time consuming nodes
  3213. // and nodes without digging time (e.g. torches) get a fixed delay.
  3214. if (runData.nodig_delay_timer > 0.3)
  3215. runData.nodig_delay_timer = 0.3;
  3216. else if (runData.dig_instantly)
  3217. runData.nodig_delay_timer = 0.15;
  3218. bool is_valid_position;
  3219. MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
  3220. if (is_valid_position) {
  3221. if (client->moddingEnabled() &&
  3222. client->getScript()->on_dignode(nodepos, wasnode)) {
  3223. return;
  3224. }
  3225. const ContentFeatures &f = client->ndef()->get(wasnode);
  3226. if (f.node_dig_prediction == "air") {
  3227. client->removeNode(nodepos);
  3228. } else if (!f.node_dig_prediction.empty()) {
  3229. content_t id;
  3230. bool found = client->ndef()->getId(f.node_dig_prediction, id);
  3231. if (found)
  3232. client->addNode(nodepos, id, true);
  3233. }
  3234. // implicit else: no prediction
  3235. }
  3236. client->interact(2, pointed);
  3237. if (m_cache_enable_particles) {
  3238. const ContentFeatures &features =
  3239. client->getNodeDefManager()->get(wasnode);
  3240. client->getParticleManager()->addDiggingParticles(client,
  3241. player, nodepos, wasnode, features);
  3242. }
  3243. // Send event to trigger sound
  3244. MtEvent *e = new NodeDugEvent(nodepos, wasnode);
  3245. client->event()->put(e);
  3246. }
  3247. if (runData.dig_time_complete < 100000.0) {
  3248. runData.dig_time += dtime;
  3249. } else {
  3250. runData.dig_time = 0;
  3251. client->setCrack(-1, nodepos);
  3252. }
  3253. camera->setDigging(0); // left click animation
  3254. }
  3255. void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
  3256. const CameraOrientation &cam)
  3257. {
  3258. LocalPlayer *player = client->getEnv().getLocalPlayer();
  3259. /*
  3260. Fog range
  3261. */
  3262. if (draw_control->range_all) {
  3263. runData.fog_range = 100000 * BS;
  3264. } else {
  3265. runData.fog_range = draw_control->wanted_range * BS;
  3266. }
  3267. /*
  3268. Calculate general brightness
  3269. */
  3270. u32 daynight_ratio = client->getEnv().getDayNightRatio();
  3271. float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
  3272. float direct_brightness;
  3273. bool sunlight_seen;
  3274. if (m_cache_enable_noclip && m_cache_enable_free_move) {
  3275. direct_brightness = time_brightness;
  3276. sunlight_seen = true;
  3277. } else {
  3278. ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
  3279. float old_brightness = sky->getBrightness();
  3280. direct_brightness = client->getEnv().getClientMap()
  3281. .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
  3282. daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
  3283. / 255.0;
  3284. }
  3285. float time_of_day_smooth = runData.time_of_day_smooth;
  3286. float time_of_day = client->getEnv().getTimeOfDayF();
  3287. static const float maxsm = 0.05;
  3288. static const float todsm = 0.05;
  3289. if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
  3290. fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
  3291. fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
  3292. time_of_day_smooth = time_of_day;
  3293. if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
  3294. time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
  3295. + (time_of_day + 1.0) * todsm;
  3296. else
  3297. time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
  3298. + time_of_day * todsm;
  3299. runData.time_of_day_smooth = time_of_day_smooth;
  3300. sky->update(time_of_day_smooth, time_brightness, direct_brightness,
  3301. sunlight_seen, camera->getCameraMode(), player->getYaw(),
  3302. player->getPitch());
  3303. /*
  3304. Update clouds
  3305. */
  3306. if (clouds) {
  3307. if (sky->getCloudsVisible()) {
  3308. clouds->setVisible(true);
  3309. clouds->step(dtime);
  3310. // camera->getPosition is not enough for 3rd person views
  3311. v3f camera_node_position = camera->getCameraNode()->getPosition();
  3312. v3s16 camera_offset = camera->getOffset();
  3313. camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
  3314. camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
  3315. camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
  3316. clouds->update(camera_node_position,
  3317. sky->getCloudColor());
  3318. if (clouds->isCameraInsideCloud() && m_cache_enable_fog &&
  3319. !m_flags.force_fog_off) {
  3320. // if inside clouds, and fog enabled, use that as sky
  3321. // color(s)
  3322. video::SColor clouds_dark = clouds->getColor()
  3323. .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
  3324. sky->overrideColors(clouds_dark, clouds->getColor());
  3325. sky->setBodiesVisible(false);
  3326. runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
  3327. // do not draw clouds after all
  3328. clouds->setVisible(false);
  3329. }
  3330. } else {
  3331. clouds->setVisible(false);
  3332. }
  3333. }
  3334. /*
  3335. Update particles
  3336. */
  3337. client->getParticleManager()->step(dtime);
  3338. /*
  3339. Fog
  3340. */
  3341. if (m_cache_enable_fog && !m_flags.force_fog_off) {
  3342. driver->setFog(
  3343. sky->getBgColor(),
  3344. video::EFT_FOG_LINEAR,
  3345. runData.fog_range * m_cache_fog_start,
  3346. runData.fog_range * 1.0,
  3347. 0.01,
  3348. false, // pixel fog
  3349. true // range fog
  3350. );
  3351. } else {
  3352. driver->setFog(
  3353. sky->getBgColor(),
  3354. video::EFT_FOG_LINEAR,
  3355. 100000 * BS,
  3356. 110000 * BS,
  3357. 0.01,
  3358. false, // pixel fog
  3359. false // range fog
  3360. );
  3361. }
  3362. /*
  3363. Get chat messages from client
  3364. */
  3365. v2u32 screensize = driver->getScreenSize();
  3366. updateChat(dtime, screensize);
  3367. /*
  3368. Inventory
  3369. */
  3370. if (client->getPlayerItem() != runData.new_playeritem)
  3371. client->selectPlayerItem(runData.new_playeritem);
  3372. // Update local inventory if it has changed
  3373. if (client->getLocalInventoryUpdated()) {
  3374. //infostream<<"Updating local inventory"<<std::endl;
  3375. client->getLocalInventory(*local_inventory);
  3376. runData.update_wielded_item_trigger = true;
  3377. }
  3378. if (runData.update_wielded_item_trigger) {
  3379. // Update wielded tool
  3380. InventoryList *mlist = local_inventory->getList("main");
  3381. if (mlist && (client->getPlayerItem() < mlist->getSize())) {
  3382. ItemStack item = mlist->getItem(client->getPlayerItem());
  3383. if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
  3384. InventoryList *hlist = local_inventory->getList("hand");
  3385. if (hlist)
  3386. item = hlist->getItem(0);
  3387. }
  3388. camera->wield(item);
  3389. }
  3390. runData.update_wielded_item_trigger = false;
  3391. }
  3392. /*
  3393. Update block draw list every 200ms or when camera direction has
  3394. changed much
  3395. */
  3396. runData.update_draw_list_timer += dtime;
  3397. v3f camera_direction = camera->getDirection();
  3398. if (runData.update_draw_list_timer >= 0.2
  3399. || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
  3400. || m_camera_offset_changed) {
  3401. runData.update_draw_list_timer = 0;
  3402. client->getEnv().getClientMap().updateDrawList();
  3403. runData.update_draw_list_last_cam_dir = camera_direction;
  3404. }
  3405. m_game_ui->update(*stats, client, draw_control, cam, runData.pointed_old, dtime);
  3406. /*
  3407. make sure menu is on top
  3408. 1. Delete formspec menu reference if menu was removed
  3409. 2. Else, make sure formspec menu is on top
  3410. */
  3411. if (current_formspec) {
  3412. if (current_formspec->getReferenceCount() == 1) {
  3413. current_formspec->drop();
  3414. current_formspec = NULL;
  3415. } else if (isMenuActive()) {
  3416. guiroot->bringToFront(current_formspec);
  3417. }
  3418. }
  3419. /*
  3420. Drawing begins
  3421. */
  3422. const video::SColor &skycolor = sky->getSkyColor();
  3423. TimeTaker tt_draw("mainloop: draw");
  3424. driver->beginScene(true, true, skycolor);
  3425. bool draw_wield_tool = (m_game_ui->m_flags.show_hud &&
  3426. (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
  3427. (camera->getCameraMode() == CAMERA_MODE_FIRST));
  3428. bool draw_crosshair = (
  3429. (player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) &&
  3430. (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT));
  3431. #ifdef HAVE_TOUCHSCREENGUI
  3432. try {
  3433. draw_crosshair = !g_settings->getBool("touchtarget");
  3434. } catch (SettingNotFoundException) {
  3435. }
  3436. #endif
  3437. RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud,
  3438. m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair);
  3439. /*
  3440. Profiler graph
  3441. */
  3442. if (m_game_ui->m_flags.show_profiler_graph)
  3443. graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
  3444. /*
  3445. Damage flash
  3446. */
  3447. if (runData.damage_flash > 0.0) {
  3448. video::SColor color(runData.damage_flash, 180, 0, 0);
  3449. driver->draw2DRectangle(color,
  3450. core::rect<s32>(0, 0, screensize.X, screensize.Y),
  3451. NULL);
  3452. runData.damage_flash -= 100.0 * dtime;
  3453. }
  3454. /*
  3455. Damage camera tilt
  3456. */
  3457. if (player->hurt_tilt_timer > 0.0) {
  3458. player->hurt_tilt_timer -= dtime * 5;
  3459. if (player->hurt_tilt_timer < 0)
  3460. player->hurt_tilt_strength = 0;
  3461. }
  3462. /*
  3463. Update minimap pos and rotation
  3464. */
  3465. if (mapper && m_game_ui->m_flags.show_minimap && m_game_ui->m_flags.show_hud) {
  3466. mapper->setPos(floatToInt(player->getPosition(), BS));
  3467. mapper->setAngle(player->getYaw());
  3468. }
  3469. /*
  3470. End scene
  3471. */
  3472. driver->endScene();
  3473. stats->drawtime = tt_draw.stop(true);
  3474. g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
  3475. }
  3476. /* Log times and stuff for visualization */
  3477. inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
  3478. {
  3479. Profiler::GraphValues values;
  3480. g_profiler->graphGet(values);
  3481. graph->put(values);
  3482. }
  3483. /****************************************************************************
  3484. Misc
  3485. ****************************************************************************/
  3486. /* On some computers framerate doesn't seem to be automatically limited
  3487. */
  3488. inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
  3489. {
  3490. // not using getRealTime is necessary for wine
  3491. device->getTimer()->tick(); // Maker sure device time is up-to-date
  3492. u32 time = device->getTimer()->getTime();
  3493. u32 last_time = fps_timings->last_time;
  3494. if (time > last_time) // Make sure time hasn't overflowed
  3495. fps_timings->busy_time = time - last_time;
  3496. else
  3497. fps_timings->busy_time = 0;
  3498. u32 frametime_min = 1000 / (g_menumgr.pausesGame()
  3499. ? g_settings->getFloat("pause_fps_max")
  3500. : g_settings->getFloat("fps_max"));
  3501. if (fps_timings->busy_time < frametime_min) {
  3502. fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
  3503. device->sleep(fps_timings->sleep_time);
  3504. } else {
  3505. fps_timings->sleep_time = 0;
  3506. }
  3507. /* Get the new value of the device timer. Note that device->sleep() may
  3508. * not sleep for the entire requested time as sleep may be interrupted and
  3509. * therefore it is arguably more accurate to get the new time from the
  3510. * device rather than calculating it by adding sleep_time to time.
  3511. */
  3512. device->getTimer()->tick(); // Update device timer
  3513. time = device->getTimer()->getTime();
  3514. if (time > last_time) // Make sure last_time hasn't overflowed
  3515. *dtime = (time - last_time) / 1000.0;
  3516. else
  3517. *dtime = 0;
  3518. fps_timings->last_time = time;
  3519. }
  3520. void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
  3521. {
  3522. const wchar_t *wmsg = wgettext(msg);
  3523. RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
  3524. draw_clouds);
  3525. delete[] wmsg;
  3526. }
  3527. void Game::settingChangedCallback(const std::string &setting_name, void *data)
  3528. {
  3529. ((Game *)data)->readSettings();
  3530. }
  3531. void Game::readSettings()
  3532. {
  3533. m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
  3534. m_cache_enable_clouds = g_settings->getBool("enable_clouds");
  3535. m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
  3536. m_cache_enable_particles = g_settings->getBool("enable_particles");
  3537. m_cache_enable_fog = g_settings->getBool("enable_fog");
  3538. m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
  3539. m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
  3540. m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
  3541. m_cache_enable_noclip = g_settings->getBool("noclip");
  3542. m_cache_enable_free_move = g_settings->getBool("free_move");
  3543. m_cache_fog_start = g_settings->getFloat("fog_start");
  3544. m_cache_cam_smoothing = 0;
  3545. if (g_settings->getBool("cinematic"))
  3546. m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
  3547. else
  3548. m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
  3549. m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
  3550. m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
  3551. m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
  3552. m_does_lost_focus_pause_game = g_settings->getBool("pause_on_lost_focus");
  3553. }
  3554. /****************************************************************************/
  3555. /****************************************************************************
  3556. Shutdown / cleanup
  3557. ****************************************************************************/
  3558. /****************************************************************************/
  3559. void Game::extendedResourceCleanup()
  3560. {
  3561. // Extended resource accounting
  3562. infostream << "Irrlicht resources after cleanup:" << std::endl;
  3563. infostream << "\tRemaining meshes : "
  3564. << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
  3565. infostream << "\tRemaining textures : "
  3566. << driver->getTextureCount() << std::endl;
  3567. for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
  3568. irr::video::ITexture *texture = driver->getTextureByIndex(i);
  3569. infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
  3570. << std::endl;
  3571. }
  3572. clearTextureNameCache();
  3573. infostream << "\tRemaining materials: "
  3574. << driver-> getMaterialRendererCount()
  3575. << " (note: irrlicht doesn't support removing renderers)" << std::endl;
  3576. }
  3577. #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
  3578. void Game::showPauseMenu()
  3579. {
  3580. #ifdef __ANDROID__
  3581. static const std::string control_text = strgettext("Default Controls:\n"
  3582. "No menu visible:\n"
  3583. "- single tap: button activate\n"
  3584. "- double tap: place/use\n"
  3585. "- slide finger: look around\n"
  3586. "Menu/Inventory visible:\n"
  3587. "- double tap (outside):\n"
  3588. " -->close\n"
  3589. "- touch stack, touch slot:\n"
  3590. " --> move stack\n"
  3591. "- touch&drag, tap 2nd finger\n"
  3592. " --> place single item to slot\n"
  3593. );
  3594. #else
  3595. static const std::string control_text_template = strgettext("Controls:\n"
  3596. "- %s: move forwards\n"
  3597. "- %s: move backwards\n"
  3598. "- %s: move left\n"
  3599. "- %s: move right\n"
  3600. "- %s: jump/climb\n"
  3601. "- %s: sneak/go down\n"
  3602. "- %s: drop item\n"
  3603. "- %s: inventory\n"
  3604. "- Mouse: turn/look\n"
  3605. "- Mouse left: dig/punch\n"
  3606. "- Mouse right: place/use\n"
  3607. "- Mouse wheel: select item\n"
  3608. "- %s: chat\n"
  3609. );
  3610. char control_text_buf[600];
  3611. snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
  3612. GET_KEY_NAME(keymap_forward),
  3613. GET_KEY_NAME(keymap_backward),
  3614. GET_KEY_NAME(keymap_left),
  3615. GET_KEY_NAME(keymap_right),
  3616. GET_KEY_NAME(keymap_jump),
  3617. GET_KEY_NAME(keymap_sneak),
  3618. GET_KEY_NAME(keymap_drop),
  3619. GET_KEY_NAME(keymap_inventory),
  3620. GET_KEY_NAME(keymap_chat)
  3621. );
  3622. std::string control_text = std::string(control_text_buf);
  3623. str_formspec_escape(control_text);
  3624. #endif
  3625. float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
  3626. std::ostringstream os;
  3627. os << FORMSPEC_VERSION_STRING << SIZE_TAG
  3628. << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
  3629. << strgettext("Continue") << "]";
  3630. if (!simple_singleplayer_mode) {
  3631. os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
  3632. << strgettext("Change Password") << "]";
  3633. } else {
  3634. os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
  3635. }
  3636. #ifndef __ANDROID__
  3637. os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
  3638. << strgettext("Sound Volume") << "]";
  3639. os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
  3640. << strgettext("Change Keys") << "]";
  3641. #endif
  3642. os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
  3643. << strgettext("Exit to Menu") << "]";
  3644. os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
  3645. << strgettext("Exit to OS") << "]"
  3646. << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
  3647. << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
  3648. << "\n"
  3649. << strgettext("Game info:") << "\n";
  3650. const std::string &address = client->getAddressName();
  3651. static const std::string mode = strgettext("- Mode: ");
  3652. if (!simple_singleplayer_mode) {
  3653. Address serverAddress = client->getServerAddress();
  3654. if (!address.empty()) {
  3655. os << mode << strgettext("Remote server") << "\n"
  3656. << strgettext("- Address: ") << address;
  3657. } else {
  3658. os << mode << strgettext("Hosting server");
  3659. }
  3660. os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
  3661. } else {
  3662. os << mode << strgettext("Singleplayer") << "\n";
  3663. }
  3664. if (simple_singleplayer_mode || address.empty()) {
  3665. static const std::string on = strgettext("On");
  3666. static const std::string off = strgettext("Off");
  3667. const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
  3668. const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
  3669. const std::string &announced = g_settings->getBool("server_announce") ? on : off;
  3670. os << strgettext("- Damage: ") << damage << "\n"
  3671. << strgettext("- Creative Mode: ") << creative << "\n";
  3672. if (!simple_singleplayer_mode) {
  3673. const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
  3674. os << strgettext("- PvP: ") << pvp << "\n"
  3675. << strgettext("- Public: ") << announced << "\n";
  3676. std::string server_name = g_settings->get("server_name");
  3677. str_formspec_escape(server_name);
  3678. if (announced == on && !server_name.empty())
  3679. os << strgettext("- Server Name: ") << server_name;
  3680. }
  3681. }
  3682. os << ";]";
  3683. /* Create menu */
  3684. /* Note: FormspecFormSource and LocalFormspecHandler *
  3685. * are deleted by guiFormSpecMenu */
  3686. FormspecFormSource *fs_src = new FormspecFormSource(os.str());
  3687. LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
  3688. create_formspec_menu(&current_formspec, client, &input->joystick, fs_src, txt_dst);
  3689. current_formspec->setFocus("btn_continue");
  3690. current_formspec->doPause = true;
  3691. }
  3692. /****************************************************************************/
  3693. /****************************************************************************
  3694. extern function for launching the game
  3695. ****************************************************************************/
  3696. /****************************************************************************/
  3697. void the_game(bool *kill,
  3698. bool random_input,
  3699. InputHandler *input,
  3700. const std::string &map_dir,
  3701. const std::string &playername,
  3702. const std::string &password,
  3703. const std::string &address, // If empty local server is created
  3704. u16 port,
  3705. std::string &error_message,
  3706. ChatBackend &chat_backend,
  3707. bool *reconnect_requested,
  3708. const SubgameSpec &gamespec, // Used for local game
  3709. bool simple_singleplayer_mode)
  3710. {
  3711. Game game;
  3712. /* Make a copy of the server address because if a local singleplayer server
  3713. * is created then this is updated and we don't want to change the value
  3714. * passed to us by the calling function
  3715. */
  3716. std::string server_address = address;
  3717. try {
  3718. if (game.startup(kill, random_input, input, map_dir,
  3719. playername, password, &server_address, port, error_message,
  3720. reconnect_requested, &chat_backend, gamespec,
  3721. simple_singleplayer_mode)) {
  3722. game.run();
  3723. game.shutdown();
  3724. }
  3725. } catch (SerializationError &e) {
  3726. error_message = std::string("A serialization error occurred:\n")
  3727. + e.what() + "\n\nThe server is probably "
  3728. " running a different version of " PROJECT_NAME_C ".";
  3729. errorstream << error_message << std::endl;
  3730. } catch (ServerError &e) {
  3731. error_message = e.what();
  3732. errorstream << "ServerError: " << error_message << std::endl;
  3733. } catch (ModError &e) {
  3734. error_message = e.what() + strgettext("\nCheck debug.txt for details.");
  3735. errorstream << "ModError: " << error_message << std::endl;
  3736. }
  3737. }