serverenvironment.cpp 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2017 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 <algorithm>
  17. #include <stack>
  18. #include <utility>
  19. #include "serverenvironment.h"
  20. #include "settings.h"
  21. #include "log.h"
  22. #include "mapblock.h"
  23. #include "nodedef.h"
  24. #include "nodemetadata.h"
  25. #include "gamedef.h"
  26. #include "porting.h"
  27. #include "profiler.h"
  28. #include "raycast.h"
  29. #include "remoteplayer.h"
  30. #include "scripting_server.h"
  31. #include "server.h"
  32. #include "util/serialize.h"
  33. #include "util/numeric.h"
  34. #include "util/basic_macros.h"
  35. #include "util/pointedthing.h"
  36. #include "threading/mutex_auto_lock.h"
  37. #include "filesys.h"
  38. #include "gameparams.h"
  39. #include "database/database-dummy.h"
  40. #include "database/database-files.h"
  41. #include "database/database-sqlite3.h"
  42. #if USE_POSTGRESQL
  43. #include "database/database-postgresql.h"
  44. #endif
  45. #if USE_LEVELDB
  46. #include "database/database-leveldb.h"
  47. #endif
  48. #include "irrlicht_changes/printing.h"
  49. #include "server/luaentity_sao.h"
  50. #include "server/player_sao.h"
  51. #define LBM_NAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyz0123456789_:"
  52. // A number that is much smaller than the timeout for particle spawners should/could ever be
  53. #define PARTICLE_SPAWNER_NO_EXPIRY -1024.f
  54. /*
  55. ABMWithState
  56. */
  57. ABMWithState::ABMWithState(ActiveBlockModifier *abm_):
  58. abm(abm_)
  59. {
  60. // Initialize timer to random value to spread processing
  61. float itv = abm->getTriggerInterval();
  62. itv = MYMAX(0.001, itv); // No less than 1ms
  63. int minval = MYMAX(-0.51*itv, -60); // Clamp to
  64. int maxval = MYMIN(0.51*itv, 60); // +-60 seconds
  65. timer = myrand_range(minval, maxval);
  66. }
  67. /*
  68. LBMManager
  69. */
  70. void LBMContentMapping::deleteContents()
  71. {
  72. for (auto &it : lbm_list) {
  73. delete it;
  74. }
  75. }
  76. void LBMContentMapping::addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef)
  77. {
  78. // Add the lbm_def to the LBMContentMapping.
  79. // Unknown names get added to the global NameIdMapping.
  80. const NodeDefManager *nodedef = gamedef->ndef();
  81. lbm_list.push_back(lbm_def);
  82. for (const std::string &nodeTrigger: lbm_def->trigger_contents) {
  83. std::vector<content_t> c_ids;
  84. bool found = nodedef->getIds(nodeTrigger, c_ids);
  85. if (!found) {
  86. content_t c_id = gamedef->allocateUnknownNodeId(nodeTrigger);
  87. if (c_id == CONTENT_IGNORE) {
  88. // Seems it can't be allocated.
  89. warningstream << "Could not internalize node name \"" << nodeTrigger
  90. << "\" while loading LBM \"" << lbm_def->name << "\"." << std::endl;
  91. continue;
  92. }
  93. c_ids.push_back(c_id);
  94. }
  95. for (content_t c_id : c_ids) {
  96. map[c_id].push_back(lbm_def);
  97. }
  98. }
  99. }
  100. const std::vector<LoadingBlockModifierDef *> *
  101. LBMContentMapping::lookup(content_t c) const
  102. {
  103. lbm_map::const_iterator it = map.find(c);
  104. if (it == map.end())
  105. return NULL;
  106. // This first dereferences the iterator, returning
  107. // a std::vector<LoadingBlockModifierDef *>
  108. // reference, then we convert it to a pointer.
  109. return &(it->second);
  110. }
  111. LBMManager::~LBMManager()
  112. {
  113. for (auto &m_lbm_def : m_lbm_defs) {
  114. delete m_lbm_def.second;
  115. }
  116. for (auto &it : m_lbm_lookup) {
  117. (it.second).deleteContents();
  118. }
  119. }
  120. void LBMManager::addLBMDef(LoadingBlockModifierDef *lbm_def)
  121. {
  122. // Precondition, in query mode the map isn't used anymore
  123. FATAL_ERROR_IF(m_query_mode,
  124. "attempted to modify LBMManager in query mode");
  125. if (!string_allowed(lbm_def->name, LBM_NAME_ALLOWED_CHARS)) {
  126. throw ModError("Error adding LBM \"" + lbm_def->name +
  127. "\": Does not follow naming conventions: "
  128. "Only characters [a-z0-9_:] are allowed.");
  129. }
  130. m_lbm_defs[lbm_def->name] = lbm_def;
  131. }
  132. void LBMManager::loadIntroductionTimes(const std::string &times,
  133. IGameDef *gamedef, u32 now)
  134. {
  135. m_query_mode = true;
  136. // name -> time map.
  137. // Storing it in a map first instead of
  138. // handling the stuff directly in the loop
  139. // removes all duplicate entries.
  140. std::unordered_map<std::string, u32> introduction_times;
  141. /*
  142. The introduction times string consists of name~time entries,
  143. with each entry terminated by a semicolon. The time is decimal.
  144. */
  145. size_t idx = 0;
  146. size_t idx_new;
  147. while ((idx_new = times.find(';', idx)) != std::string::npos) {
  148. std::string entry = times.substr(idx, idx_new - idx);
  149. std::vector<std::string> components = str_split(entry, '~');
  150. if (components.size() != 2)
  151. throw SerializationError("Introduction times entry \""
  152. + entry + "\" requires exactly one '~'!");
  153. const std::string &name = components[0];
  154. u32 time = from_string<u32>(components[1]);
  155. introduction_times[name] = time;
  156. idx = idx_new + 1;
  157. }
  158. // Put stuff from introduction_times into m_lbm_lookup
  159. for (auto &it : introduction_times) {
  160. const std::string &name = it.first;
  161. u32 time = it.second;
  162. auto def_it = m_lbm_defs.find(name);
  163. if (def_it == m_lbm_defs.end()) {
  164. // This seems to be an LBM entry for
  165. // an LBM we haven't loaded. Discard it.
  166. continue;
  167. }
  168. LoadingBlockModifierDef *lbm_def = def_it->second;
  169. if (lbm_def->run_at_every_load) {
  170. // This seems to be an LBM entry for
  171. // an LBM that runs at every load.
  172. // Don't add it just yet.
  173. continue;
  174. }
  175. m_lbm_lookup[time].addLBM(lbm_def, gamedef);
  176. // Erase the entry so that we know later
  177. // what elements didn't get put into m_lbm_lookup
  178. m_lbm_defs.erase(name);
  179. }
  180. // Now also add the elements from m_lbm_defs to m_lbm_lookup
  181. // that weren't added in the previous step.
  182. // They are introduced first time to this world,
  183. // or are run at every load (introducement time hardcoded to U32_MAX).
  184. LBMContentMapping &lbms_we_introduce_now = m_lbm_lookup[now];
  185. LBMContentMapping &lbms_running_always = m_lbm_lookup[U32_MAX];
  186. for (auto &m_lbm_def : m_lbm_defs) {
  187. if (m_lbm_def.second->run_at_every_load) {
  188. lbms_running_always.addLBM(m_lbm_def.second, gamedef);
  189. } else {
  190. lbms_we_introduce_now.addLBM(m_lbm_def.second, gamedef);
  191. }
  192. }
  193. // Clear the list, so that we don't delete remaining elements
  194. // twice in the destructor
  195. m_lbm_defs.clear();
  196. }
  197. std::string LBMManager::createIntroductionTimesString()
  198. {
  199. // Precondition, we must be in query mode
  200. FATAL_ERROR_IF(!m_query_mode,
  201. "attempted to query on non fully set up LBMManager");
  202. std::ostringstream oss;
  203. for (const auto &it : m_lbm_lookup) {
  204. u32 time = it.first;
  205. const std::vector<LoadingBlockModifierDef *> &lbm_list = it.second.lbm_list;
  206. for (const auto &lbm_def : lbm_list) {
  207. // Don't add if the LBM runs at every load,
  208. // then introducement time is hardcoded
  209. // and doesn't need to be stored
  210. if (lbm_def->run_at_every_load)
  211. continue;
  212. oss << lbm_def->name << "~" << time << ";";
  213. }
  214. }
  215. return oss.str();
  216. }
  217. void LBMManager::applyLBMs(ServerEnvironment *env, MapBlock *block,
  218. const u32 stamp, const float dtime_s)
  219. {
  220. // Precondition, we need m_lbm_lookup to be initialized
  221. FATAL_ERROR_IF(!m_query_mode,
  222. "attempted to query on non fully set up LBMManager");
  223. v3s16 pos_of_block = block->getPosRelative();
  224. v3s16 pos;
  225. MapNode n;
  226. content_t c;
  227. auto it = getLBMsIntroducedAfter(stamp);
  228. for (; it != m_lbm_lookup.end(); ++it) {
  229. // Cache previous version to speedup lookup which has a very high performance
  230. // penalty on each call
  231. content_t previous_c = CONTENT_IGNORE;
  232. const std::vector<LoadingBlockModifierDef *> *lbm_list = nullptr;
  233. for (pos.X = 0; pos.X < MAP_BLOCKSIZE; pos.X++)
  234. for (pos.Y = 0; pos.Y < MAP_BLOCKSIZE; pos.Y++)
  235. for (pos.Z = 0; pos.Z < MAP_BLOCKSIZE; pos.Z++) {
  236. n = block->getNodeNoCheck(pos);
  237. c = n.getContent();
  238. // If content_t are not matching perform an LBM lookup
  239. if (previous_c != c) {
  240. lbm_list = it->second.lookup(c);
  241. previous_c = c;
  242. }
  243. if (!lbm_list)
  244. continue;
  245. for (auto lbmdef : *lbm_list) {
  246. lbmdef->trigger(env, pos + pos_of_block, n, dtime_s);
  247. if (block->isOrphan())
  248. return;
  249. n = block->getNodeNoCheck(pos);
  250. if (n.getContent() != c)
  251. break; // The node was changed and the LBMs no longer apply
  252. }
  253. }
  254. }
  255. }
  256. /*
  257. ActiveBlockList
  258. */
  259. static void fillRadiusBlock(v3s16 p0, s16 r, std::set<v3s16> &list)
  260. {
  261. v3s16 p;
  262. for(p.X=p0.X-r; p.X<=p0.X+r; p.X++)
  263. for(p.Y=p0.Y-r; p.Y<=p0.Y+r; p.Y++)
  264. for(p.Z=p0.Z-r; p.Z<=p0.Z+r; p.Z++)
  265. {
  266. // limit to a sphere
  267. if (p.getDistanceFrom(p0) <= r) {
  268. // Set in list
  269. list.insert(p);
  270. }
  271. }
  272. }
  273. static void fillViewConeBlock(v3s16 p0,
  274. const s16 r,
  275. const v3f camera_pos,
  276. const v3f camera_dir,
  277. const float camera_fov,
  278. std::set<v3s16> &list)
  279. {
  280. v3s16 p;
  281. const s16 r_nodes = r * BS * MAP_BLOCKSIZE;
  282. for (p.X = p0.X - r; p.X <= p0.X+r; p.X++)
  283. for (p.Y = p0.Y - r; p.Y <= p0.Y+r; p.Y++)
  284. for (p.Z = p0.Z - r; p.Z <= p0.Z+r; p.Z++) {
  285. if (isBlockInSight(p, camera_pos, camera_dir, camera_fov, r_nodes)) {
  286. list.insert(p);
  287. }
  288. }
  289. }
  290. void ActiveBlockList::update(std::vector<PlayerSAO*> &active_players,
  291. s16 active_block_range,
  292. s16 active_object_range,
  293. std::set<v3s16> &blocks_removed,
  294. std::set<v3s16> &blocks_added,
  295. std::set<v3s16> &extra_blocks_added)
  296. {
  297. /*
  298. Create the new list
  299. */
  300. std::set<v3s16> newlist = m_forceloaded_list;
  301. std::set<v3s16> extralist;
  302. m_abm_list = m_forceloaded_list;
  303. for (const PlayerSAO *playersao : active_players) {
  304. v3s16 pos = getNodeBlockPos(floatToInt(playersao->getBasePosition(), BS));
  305. fillRadiusBlock(pos, active_block_range, m_abm_list);
  306. fillRadiusBlock(pos, active_block_range, newlist);
  307. s16 player_ao_range = std::min(active_object_range, playersao->getWantedRange());
  308. // only do this if this would add blocks
  309. if (player_ao_range > active_block_range) {
  310. v3f camera_dir = v3f(0,0,1);
  311. camera_dir.rotateYZBy(playersao->getLookPitch());
  312. camera_dir.rotateXZBy(playersao->getRotation().Y);
  313. if (playersao->getCameraInverted())
  314. camera_dir = -camera_dir;
  315. fillViewConeBlock(pos,
  316. player_ao_range,
  317. playersao->getEyePosition(),
  318. camera_dir,
  319. playersao->getFov(),
  320. extralist);
  321. }
  322. }
  323. /*
  324. Find out which blocks on the new list are not on the old list
  325. */
  326. for (v3s16 p : newlist) {
  327. // also remove duplicate blocks from the extra list
  328. extralist.erase(p);
  329. // If not on old list, it's been added
  330. if (m_list.find(p) == m_list.end())
  331. blocks_added.insert(p);
  332. }
  333. /*
  334. Find out which blocks on the extra list are not on the old list
  335. */
  336. for (v3s16 p : extralist) {
  337. // also make sure newlist has all blocks
  338. newlist.insert(p);
  339. // If not on old list, it's been added
  340. if (m_list.find(p) == m_list.end())
  341. extra_blocks_added.insert(p);
  342. }
  343. /*
  344. Find out which blocks on the old list are not on the new + extra list
  345. */
  346. std::set_difference(m_list.begin(), m_list.end(), newlist.begin(), newlist.end(),
  347. std::inserter(blocks_removed, blocks_removed.end()));
  348. /*
  349. Do some least-effort sanity checks to hopefully catch code bugs.
  350. */
  351. assert(newlist.size() >= extralist.size());
  352. assert(blocks_removed.size() <= m_list.size());
  353. if (!blocks_added.empty()) {
  354. assert(newlist.count(*blocks_added.begin()) > 0);
  355. assert(blocks_removed.count(*blocks_added.begin()) == 0);
  356. }
  357. if (!extra_blocks_added.empty()) {
  358. assert(newlist.count(*extra_blocks_added.begin()) > 0);
  359. assert(extralist.count(*extra_blocks_added.begin()) > 0);
  360. assert(blocks_added.count(*extra_blocks_added.begin()) == 0);
  361. }
  362. if (!blocks_removed.empty()) {
  363. assert(newlist.count(*blocks_removed.begin()) == 0);
  364. assert(extralist.count(*blocks_removed.begin()) == 0);
  365. assert(m_list.count(*blocks_removed.begin()) > 0);
  366. }
  367. /*
  368. Update m_list
  369. */
  370. m_list = std::move(newlist);
  371. }
  372. /*
  373. OnMapblocksChangedReceiver
  374. */
  375. void OnMapblocksChangedReceiver::onMapEditEvent(const MapEditEvent &event)
  376. {
  377. assert(receiving);
  378. for (const v3s16 &p : event.modified_blocks) {
  379. modified_blocks.insert(p);
  380. }
  381. }
  382. /*
  383. ServerEnvironment
  384. */
  385. ServerEnvironment::ServerEnvironment(std::unique_ptr<ServerMap> map,
  386. Server *server, MetricsBackend *mb):
  387. Environment(server),
  388. m_map(std::move(map)),
  389. m_script(server->getScriptIface()),
  390. m_server(server)
  391. {
  392. m_step_time_counter = mb->addCounter(
  393. "minetest_env_step_time", "Time spent in environment step (in microseconds)");
  394. m_active_block_gauge = mb->addGauge(
  395. "minetest_env_active_blocks", "Number of active blocks");
  396. m_active_object_gauge = mb->addGauge(
  397. "minetest_env_active_objects", "Number of active objects");
  398. }
  399. void ServerEnvironment::init()
  400. {
  401. // Determine which database backend to use
  402. const std::string world_path = m_server->getWorldPath();
  403. const std::string conf_path = world_path + DIR_DELIM "world.mt";
  404. Settings conf;
  405. std::string player_backend_name = "sqlite3";
  406. std::string auth_backend_name = "sqlite3";
  407. bool succeeded = conf.readConfigFile(conf_path.c_str());
  408. // If we open world.mt read the backend configurations.
  409. if (succeeded) {
  410. // Check that the world's blocksize matches the compiled MAP_BLOCKSIZE
  411. u16 blocksize = 16;
  412. conf.getU16NoEx("blocksize", blocksize);
  413. if (blocksize != MAP_BLOCKSIZE) {
  414. throw BaseException("The map's blocksize is not supported.");
  415. }
  416. // Read those values before setting defaults
  417. bool player_backend_exists = conf.exists("player_backend");
  418. bool auth_backend_exists = conf.exists("auth_backend");
  419. // player backend is not set, assume it's legacy file backend.
  420. if (!player_backend_exists) {
  421. // fall back to files
  422. conf.set("player_backend", "files");
  423. player_backend_name = "files";
  424. if (!conf.updateConfigFile(conf_path.c_str())) {
  425. errorstream << "ServerEnvironment::ServerEnvironment(): "
  426. << "Failed to update world.mt!" << std::endl;
  427. }
  428. } else {
  429. conf.getNoEx("player_backend", player_backend_name);
  430. }
  431. // auth backend is not set, assume it's legacy file backend.
  432. if (!auth_backend_exists) {
  433. conf.set("auth_backend", "files");
  434. auth_backend_name = "files";
  435. if (!conf.updateConfigFile(conf_path.c_str())) {
  436. errorstream << "ServerEnvironment::ServerEnvironment(): "
  437. << "Failed to update world.mt!" << std::endl;
  438. }
  439. } else {
  440. conf.getNoEx("auth_backend", auth_backend_name);
  441. }
  442. }
  443. if (player_backend_name == "files") {
  444. warningstream << "/!\\ You are using old player file backend. "
  445. << "This backend is deprecated and will be removed in a future release /!\\"
  446. << std::endl << "Switching to SQLite3 or PostgreSQL is advised, "
  447. << "please read http://wiki.minetest.net/Database_backends." << std::endl;
  448. }
  449. if (auth_backend_name == "files") {
  450. warningstream << "/!\\ You are using old auth file backend. "
  451. << "This backend is deprecated and will be removed in a future release /!\\"
  452. << std::endl << "Switching to SQLite3 is advised, "
  453. << "please read http://wiki.minetest.net/Database_backends." << std::endl;
  454. }
  455. m_player_database = openPlayerDatabase(player_backend_name, world_path, conf);
  456. m_auth_database = openAuthDatabase(auth_backend_name, world_path, conf);
  457. if (m_map && m_script->has_on_mapblocks_changed()) {
  458. m_map->addEventReceiver(&m_on_mapblocks_changed_receiver);
  459. m_on_mapblocks_changed_receiver.receiving = true;
  460. }
  461. }
  462. void ServerEnvironment::deactivateBlocksAndObjects()
  463. {
  464. // Clear active block list.
  465. // This makes the next one delete all active objects.
  466. m_active_blocks.clear();
  467. deactivateFarObjects(true);
  468. }
  469. ServerEnvironment::~ServerEnvironment()
  470. {
  471. assert(m_active_blocks.size() == 0); // deactivateBlocksAndObjects does this
  472. // Drop/delete map
  473. m_map.reset();
  474. // Delete ActiveBlockModifiers
  475. for (ABMWithState &m_abm : m_abms) {
  476. delete m_abm.abm;
  477. }
  478. // Deallocate players
  479. for (RemotePlayer *m_player : m_players) {
  480. delete m_player;
  481. }
  482. delete m_player_database;
  483. delete m_auth_database;
  484. }
  485. Map & ServerEnvironment::getMap()
  486. {
  487. return *m_map;
  488. }
  489. ServerMap & ServerEnvironment::getServerMap()
  490. {
  491. return *m_map;
  492. }
  493. RemotePlayer *ServerEnvironment::getPlayer(const session_t peer_id)
  494. {
  495. for (RemotePlayer *player : m_players) {
  496. if (player->getPeerId() == peer_id)
  497. return player;
  498. }
  499. return NULL;
  500. }
  501. RemotePlayer *ServerEnvironment::getPlayer(const char* name, bool match_invalid_peer)
  502. {
  503. for (RemotePlayer *player : m_players) {
  504. if (strcmp(player->getName(), name) != 0)
  505. continue;
  506. if (match_invalid_peer || player->getPeerId() != PEER_ID_INEXISTENT)
  507. return player;
  508. break;
  509. }
  510. return nullptr;
  511. }
  512. void ServerEnvironment::addPlayer(RemotePlayer *player)
  513. {
  514. /*
  515. Check that peer_ids are unique.
  516. Also check that names are unique.
  517. Exception: there can be multiple players with peer_id=0
  518. */
  519. // If peer id is non-zero, it has to be unique.
  520. if (player->getPeerId() != PEER_ID_INEXISTENT)
  521. FATAL_ERROR_IF(getPlayer(player->getPeerId()) != NULL, "Peer id not unique");
  522. // Name has to be unique.
  523. FATAL_ERROR_IF(getPlayer(player->getName()) != NULL, "Player name not unique");
  524. // Add.
  525. m_players.push_back(player);
  526. }
  527. void ServerEnvironment::removePlayer(RemotePlayer *player)
  528. {
  529. for (std::vector<RemotePlayer *>::iterator it = m_players.begin();
  530. it != m_players.end(); ++it) {
  531. if ((*it) == player) {
  532. delete *it;
  533. m_players.erase(it);
  534. return;
  535. }
  536. }
  537. }
  538. bool ServerEnvironment::removePlayerFromDatabase(const std::string &name)
  539. {
  540. return m_player_database->removePlayer(name);
  541. }
  542. void ServerEnvironment::saveLoadedPlayers(bool force)
  543. {
  544. for (RemotePlayer *player : m_players) {
  545. if (force || player->checkModified() || (player->getPlayerSAO() &&
  546. player->getPlayerSAO()->getMeta().isModified())) {
  547. try {
  548. m_player_database->savePlayer(player);
  549. } catch (DatabaseException &e) {
  550. errorstream << "Failed to save player " << player->getName() << " exception: "
  551. << e.what() << std::endl;
  552. throw;
  553. }
  554. }
  555. }
  556. }
  557. void ServerEnvironment::savePlayer(RemotePlayer *player)
  558. {
  559. try {
  560. m_player_database->savePlayer(player);
  561. } catch (DatabaseException &e) {
  562. errorstream << "Failed to save player " << player->getName() << " exception: "
  563. << e.what() << std::endl;
  564. throw;
  565. }
  566. }
  567. PlayerSAO *ServerEnvironment::loadPlayer(RemotePlayer *player, bool *new_player,
  568. session_t peer_id, bool is_singleplayer)
  569. {
  570. auto playersao = std::make_unique<PlayerSAO>(this, player, peer_id, is_singleplayer);
  571. // Create player if it doesn't exist
  572. if (!m_player_database->loadPlayer(player, playersao.get())) {
  573. *new_player = true;
  574. // Set player position
  575. infostream << "Server: Finding spawn place for player \""
  576. << player->getName() << "\"" << std::endl;
  577. playersao->setBasePosition(m_server->findSpawnPos());
  578. // Make sure the player is saved
  579. player->setModified(true);
  580. } else {
  581. // If the player exists, ensure that they respawn inside legal bounds
  582. // This fixes an assert crash when the player can't be added
  583. // to the environment
  584. if (objectpos_over_limit(playersao->getBasePosition())) {
  585. actionstream << "Respawn position for player \""
  586. << player->getName() << "\" outside limits, resetting" << std::endl;
  587. playersao->setBasePosition(m_server->findSpawnPos());
  588. }
  589. }
  590. // Add player to environment
  591. addPlayer(player);
  592. /* Clean up old HUD elements from previous sessions */
  593. player->clearHud();
  594. /* Add object to environment */
  595. PlayerSAO *ret = playersao.get();
  596. addActiveObject(std::move(playersao));
  597. // Update active blocks quickly for a bit so objects in those blocks appear on the client
  598. m_fast_active_block_divider = 10;
  599. return ret;
  600. }
  601. void ServerEnvironment::saveMeta()
  602. {
  603. if (!m_meta_loaded)
  604. return;
  605. std::string path = m_server->getWorldPath() + DIR_DELIM "env_meta.txt";
  606. // Open file and serialize
  607. std::ostringstream ss(std::ios_base::binary);
  608. Settings args("EnvArgsEnd");
  609. args.setU64("game_time", m_game_time);
  610. args.setU64("time_of_day", getTimeOfDay());
  611. args.setU64("last_clear_objects_time", m_last_clear_objects_time);
  612. args.setU64("lbm_introduction_times_version", 1);
  613. args.set("lbm_introduction_times",
  614. m_lbm_mgr.createIntroductionTimesString());
  615. args.setU64("day_count", m_day_count);
  616. args.writeLines(ss);
  617. if(!fs::safeWriteToFile(path, ss.str()))
  618. {
  619. infostream<<"ServerEnvironment::saveMeta(): Failed to write "
  620. <<path<<std::endl;
  621. throw SerializationError("Couldn't save env meta");
  622. }
  623. }
  624. void ServerEnvironment::loadMeta()
  625. {
  626. SANITY_CHECK(!m_meta_loaded);
  627. m_meta_loaded = true;
  628. std::string path = m_server->getWorldPath() + DIR_DELIM "env_meta.txt";
  629. // If file doesn't exist, load default environment metadata
  630. if (!fs::PathExists(path)) {
  631. infostream << "ServerEnvironment: Loading default environment metadata"
  632. << std::endl;
  633. loadDefaultMeta();
  634. return;
  635. }
  636. infostream << "ServerEnvironment: Loading environment metadata" << std::endl;
  637. // Open file and deserialize
  638. std::ifstream is(path.c_str(), std::ios_base::binary);
  639. if (!is.good()) {
  640. infostream << "ServerEnvironment::loadMeta(): Failed to open "
  641. << path << std::endl;
  642. throw SerializationError("Couldn't load env meta");
  643. }
  644. Settings args("EnvArgsEnd");
  645. if (!args.parseConfigLines(is)) {
  646. throw SerializationError("ServerEnvironment::loadMeta(): "
  647. "EnvArgsEnd not found!");
  648. }
  649. try {
  650. m_game_time = args.getU64("game_time");
  651. } catch (SettingNotFoundException &e) {
  652. // Getting this is crucial, otherwise timestamps are useless
  653. throw SerializationError("Couldn't load env meta game_time");
  654. }
  655. setTimeOfDay(args.exists("time_of_day") ?
  656. // set day to early morning by default
  657. args.getU64("time_of_day") : 5250);
  658. m_last_clear_objects_time = args.exists("last_clear_objects_time") ?
  659. // If missing, do as if clearObjects was never called
  660. args.getU64("last_clear_objects_time") : 0;
  661. std::string lbm_introduction_times;
  662. try {
  663. u64 ver = args.getU64("lbm_introduction_times_version");
  664. if (ver == 1) {
  665. lbm_introduction_times = args.get("lbm_introduction_times");
  666. } else {
  667. infostream << "ServerEnvironment::loadMeta(): Non-supported"
  668. << " introduction time version " << ver << std::endl;
  669. }
  670. } catch (SettingNotFoundException &e) {
  671. // No problem, this is expected. Just continue with an empty string
  672. }
  673. m_lbm_mgr.loadIntroductionTimes(lbm_introduction_times, m_server, m_game_time);
  674. m_day_count = args.exists("day_count") ? args.getU32("day_count") : 0;
  675. }
  676. /**
  677. * called if env_meta.txt doesn't exist (e.g. new world)
  678. */
  679. void ServerEnvironment::loadDefaultMeta()
  680. {
  681. m_lbm_mgr.loadIntroductionTimes("", m_server, m_game_time);
  682. }
  683. struct ActiveABM
  684. {
  685. ActiveBlockModifier *abm;
  686. int chance;
  687. std::vector<content_t> required_neighbors;
  688. bool check_required_neighbors; // false if required_neighbors is known to be empty
  689. s16 min_y;
  690. s16 max_y;
  691. };
  692. #define CONTENT_TYPE_CACHE_MAX 64
  693. class ABMHandler
  694. {
  695. private:
  696. ServerEnvironment *m_env;
  697. std::vector<std::vector<ActiveABM> *> m_aabms;
  698. public:
  699. ABMHandler(std::vector<ABMWithState> &abms,
  700. float dtime_s, ServerEnvironment *env,
  701. bool use_timers):
  702. m_env(env)
  703. {
  704. if(dtime_s < 0.001)
  705. return;
  706. const NodeDefManager *ndef = env->getGameDef()->ndef();
  707. for (ABMWithState &abmws : abms) {
  708. ActiveBlockModifier *abm = abmws.abm;
  709. float trigger_interval = abm->getTriggerInterval();
  710. if(trigger_interval < 0.001)
  711. trigger_interval = 0.001;
  712. float actual_interval = dtime_s;
  713. if(use_timers){
  714. abmws.timer += dtime_s;
  715. if(abmws.timer < trigger_interval)
  716. continue;
  717. abmws.timer -= trigger_interval;
  718. actual_interval = trigger_interval;
  719. }
  720. float chance = abm->getTriggerChance();
  721. if (chance == 0)
  722. chance = 1;
  723. ActiveABM aabm;
  724. aabm.abm = abm;
  725. if (abm->getSimpleCatchUp()) {
  726. float intervals = actual_interval / trigger_interval;
  727. if (intervals == 0)
  728. continue;
  729. aabm.chance = chance / intervals;
  730. if (aabm.chance == 0)
  731. aabm.chance = 1;
  732. } else {
  733. aabm.chance = chance;
  734. }
  735. // y limits
  736. aabm.min_y = abm->getMinY();
  737. aabm.max_y = abm->getMaxY();
  738. // Trigger neighbors
  739. const std::vector<std::string> &required_neighbors_s =
  740. abm->getRequiredNeighbors();
  741. for (const std::string &required_neighbor_s : required_neighbors_s) {
  742. ndef->getIds(required_neighbor_s, aabm.required_neighbors);
  743. }
  744. aabm.check_required_neighbors = !required_neighbors_s.empty();
  745. // Trigger contents
  746. const std::vector<std::string> &contents_s = abm->getTriggerContents();
  747. for (const std::string &content_s : contents_s) {
  748. std::vector<content_t> ids;
  749. ndef->getIds(content_s, ids);
  750. for (content_t c : ids) {
  751. if (c >= m_aabms.size())
  752. m_aabms.resize(c + 256, NULL);
  753. if (!m_aabms[c])
  754. m_aabms[c] = new std::vector<ActiveABM>;
  755. m_aabms[c]->push_back(aabm);
  756. }
  757. }
  758. }
  759. }
  760. ~ABMHandler()
  761. {
  762. for (auto &aabms : m_aabms)
  763. delete aabms;
  764. }
  765. // Find out how many objects the given block and its neighbors contain.
  766. // Returns the number of objects in the block, and also in 'wider' the
  767. // number of objects in the block and all its neighbors. The latter
  768. // may an estimate if any neighbors are unloaded.
  769. u32 countObjects(MapBlock *block, ServerMap * map, u32 &wider)
  770. {
  771. wider = 0;
  772. u32 wider_unknown_count = 0;
  773. for(s16 x=-1; x<=1; x++)
  774. for(s16 y=-1; y<=1; y++)
  775. for(s16 z=-1; z<=1; z++)
  776. {
  777. MapBlock *block2 = map->getBlockNoCreateNoEx(
  778. block->getPos() + v3s16(x,y,z));
  779. if(block2==NULL){
  780. wider_unknown_count++;
  781. continue;
  782. }
  783. wider += block2->m_static_objects.size();
  784. }
  785. // Extrapolate
  786. u32 active_object_count = block->m_static_objects.getActiveSize();
  787. u32 wider_known_count = 3 * 3 * 3 - wider_unknown_count;
  788. wider += wider_unknown_count * wider / wider_known_count;
  789. return active_object_count;
  790. }
  791. void apply(MapBlock *block, int &blocks_scanned, int &abms_run, int &blocks_cached)
  792. {
  793. if (m_aabms.empty())
  794. return;
  795. // Check the content type cache first
  796. // to see whether there are any ABMs
  797. // to be run at all for this block.
  798. if (!block->contents.empty()) {
  799. assert(!block->do_not_cache_contents); // invariant
  800. blocks_cached++;
  801. bool run_abms = false;
  802. for (content_t c : block->contents) {
  803. if (c < m_aabms.size() && m_aabms[c]) {
  804. run_abms = true;
  805. break;
  806. }
  807. }
  808. if (!run_abms)
  809. return;
  810. }
  811. blocks_scanned++;
  812. ServerMap *map = &m_env->getServerMap();
  813. u32 active_object_count_wider;
  814. u32 active_object_count = this->countObjects(block, map, active_object_count_wider);
  815. m_env->m_added_objects = 0;
  816. bool want_contents_cached = block->contents.empty() && !block->do_not_cache_contents;
  817. v3s16 p0;
  818. for(p0.X=0; p0.X<MAP_BLOCKSIZE; p0.X++)
  819. for(p0.Y=0; p0.Y<MAP_BLOCKSIZE; p0.Y++)
  820. for(p0.Z=0; p0.Z<MAP_BLOCKSIZE; p0.Z++)
  821. {
  822. MapNode n = block->getNodeNoCheck(p0);
  823. content_t c = n.getContent();
  824. // Cache content types as we go
  825. if (want_contents_cached && !CONTAINS(block->contents, c)) {
  826. if (block->contents.size() >= CONTENT_TYPE_CACHE_MAX) {
  827. // Too many different nodes... don't try to cache
  828. want_contents_cached = false;
  829. block->do_not_cache_contents = true;
  830. block->contents.clear();
  831. block->contents.shrink_to_fit();
  832. } else {
  833. block->contents.push_back(c);
  834. }
  835. }
  836. if (c >= m_aabms.size() || !m_aabms[c])
  837. continue;
  838. v3s16 p = p0 + block->getPosRelative();
  839. for (ActiveABM &aabm : *m_aabms[c]) {
  840. if ((p.Y < aabm.min_y) || (p.Y > aabm.max_y))
  841. continue;
  842. if (myrand() % aabm.chance != 0)
  843. continue;
  844. // Check neighbors
  845. if (aabm.check_required_neighbors) {
  846. v3s16 p1;
  847. for(p1.X = p0.X-1; p1.X <= p0.X+1; p1.X++)
  848. for(p1.Y = p0.Y-1; p1.Y <= p0.Y+1; p1.Y++)
  849. for(p1.Z = p0.Z-1; p1.Z <= p0.Z+1; p1.Z++)
  850. {
  851. if(p1 == p0)
  852. continue;
  853. content_t c;
  854. if (block->isValidPosition(p1)) {
  855. // if the neighbor is found on the same map block
  856. // get it straight from there
  857. const MapNode &n = block->getNodeNoCheck(p1);
  858. c = n.getContent();
  859. } else {
  860. // otherwise consult the map
  861. MapNode n = map->getNode(p1 + block->getPosRelative());
  862. c = n.getContent();
  863. }
  864. if (CONTAINS(aabm.required_neighbors, c))
  865. goto neighbor_found;
  866. }
  867. // No required neighbor found
  868. continue;
  869. }
  870. neighbor_found:
  871. abms_run++;
  872. // Call all the trigger variations
  873. aabm.abm->trigger(m_env, p, n);
  874. aabm.abm->trigger(m_env, p, n,
  875. active_object_count, active_object_count_wider);
  876. if (block->isOrphan())
  877. return;
  878. // Count surrounding objects again if the abms added any
  879. if(m_env->m_added_objects > 0) {
  880. active_object_count = countObjects(block, map, active_object_count_wider);
  881. m_env->m_added_objects = 0;
  882. }
  883. // Update and check node after possible modification
  884. n = block->getNodeNoCheck(p0);
  885. if (n.getContent() != c)
  886. break;
  887. }
  888. }
  889. }
  890. };
  891. void ServerEnvironment::activateBlock(MapBlock *block, u32 additional_dtime)
  892. {
  893. // Reset usage timer immediately, otherwise a block that becomes active
  894. // again at around the same time as it would normally be unloaded will
  895. // get unloaded incorrectly. (I think this still leaves a small possibility
  896. // of a race condition between this and server::AsyncRunStep, which only
  897. // some kind of synchronisation will fix, but it at least reduces the window
  898. // of opportunity for it to break from seconds to nanoseconds)
  899. block->resetUsageTimer();
  900. // Get time difference
  901. u32 dtime_s = 0;
  902. u32 stamp = block->getTimestamp();
  903. if (m_game_time > stamp && stamp != BLOCK_TIMESTAMP_UNDEFINED)
  904. dtime_s = m_game_time - stamp;
  905. dtime_s += additional_dtime;
  906. /*infostream<<"ServerEnvironment::activateBlock(): block timestamp: "
  907. <<stamp<<", game time: "<<m_game_time<<std::endl;*/
  908. // Remove stored static objects if clearObjects was called since block's timestamp
  909. // Note that non-generated blocks may still have stored static objects
  910. if (stamp != BLOCK_TIMESTAMP_UNDEFINED && stamp < m_last_clear_objects_time) {
  911. block->m_static_objects.clearStored();
  912. // do not set changed flag to avoid unnecessary mapblock writes
  913. }
  914. // Set current time as timestamp
  915. block->setTimestampNoChangedFlag(m_game_time);
  916. /*infostream<<"ServerEnvironment::activateBlock(): block is "
  917. <<dtime_s<<" seconds old."<<std::endl;*/
  918. // Activate stored objects
  919. activateObjects(block, dtime_s);
  920. if (block->isOrphan())
  921. return;
  922. /* Handle LoadingBlockModifiers */
  923. m_lbm_mgr.applyLBMs(this, block, stamp, (float)dtime_s);
  924. if (block->isOrphan())
  925. return;
  926. // Run node timers
  927. block->step((float)dtime_s, [&](v3s16 p, MapNode n, f32 d) -> bool {
  928. return !block->isOrphan() && m_script->node_on_timer(p, n, d);
  929. });
  930. }
  931. void ServerEnvironment::addActiveBlockModifier(ActiveBlockModifier *abm)
  932. {
  933. m_abms.emplace_back(abm);
  934. }
  935. void ServerEnvironment::addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm)
  936. {
  937. m_lbm_mgr.addLBMDef(lbm);
  938. }
  939. bool ServerEnvironment::setNode(v3s16 p, const MapNode &n)
  940. {
  941. const NodeDefManager *ndef = m_server->ndef();
  942. MapNode n_old = m_map->getNode(p);
  943. const ContentFeatures &cf_old = ndef->get(n_old);
  944. // Call destructor
  945. if (cf_old.has_on_destruct)
  946. m_script->node_on_destruct(p, n_old);
  947. // Replace node
  948. if (!m_map->addNodeWithEvent(p, n))
  949. return false;
  950. // Update active VoxelManipulator if a mapgen thread
  951. m_map->updateVManip(p);
  952. // Call post-destructor
  953. if (cf_old.has_after_destruct)
  954. m_script->node_after_destruct(p, n_old);
  955. // Retrieve node content features
  956. // if new node is same as old, reuse old definition to prevent a lookup
  957. const ContentFeatures &cf_new = n_old == n ? cf_old : ndef->get(n);
  958. // Call constructor
  959. if (cf_new.has_on_construct)
  960. m_script->node_on_construct(p, n);
  961. return true;
  962. }
  963. bool ServerEnvironment::removeNode(v3s16 p)
  964. {
  965. const NodeDefManager *ndef = m_server->ndef();
  966. MapNode n_old = m_map->getNode(p);
  967. // Call destructor
  968. if (ndef->get(n_old).has_on_destruct)
  969. m_script->node_on_destruct(p, n_old);
  970. // Replace with air
  971. // This is slightly optimized compared to addNodeWithEvent(air)
  972. if (!m_map->removeNodeWithEvent(p))
  973. return false;
  974. // Update active VoxelManipulator if a mapgen thread
  975. m_map->updateVManip(p);
  976. // Call post-destructor
  977. if (ndef->get(n_old).has_after_destruct)
  978. m_script->node_after_destruct(p, n_old);
  979. // Air doesn't require constructor
  980. return true;
  981. }
  982. bool ServerEnvironment::swapNode(v3s16 p, const MapNode &n)
  983. {
  984. if (!m_map->addNodeWithEvent(p, n, false))
  985. return false;
  986. // Update active VoxelManipulator if a mapgen thread
  987. m_map->updateVManip(p);
  988. return true;
  989. }
  990. u8 ServerEnvironment::findSunlight(v3s16 pos) const
  991. {
  992. // Directions for neighboring nodes with specified order
  993. static const v3s16 dirs[] = {
  994. v3s16(-1, 0, 0), v3s16(1, 0, 0), v3s16(0, 0, -1), v3s16(0, 0, 1),
  995. v3s16(0, -1, 0), v3s16(0, 1, 0)
  996. };
  997. const NodeDefManager *ndef = m_server->ndef();
  998. // found_light remembers the highest known sunlight value at pos
  999. u8 found_light = 0;
  1000. struct stack_entry {
  1001. v3s16 pos;
  1002. s16 dist;
  1003. };
  1004. std::stack<stack_entry> stack;
  1005. stack.push({pos, 0});
  1006. std::unordered_map<s64, s8> dists;
  1007. dists[MapDatabase::getBlockAsInteger(pos)] = 0;
  1008. while (!stack.empty()) {
  1009. struct stack_entry e = stack.top();
  1010. stack.pop();
  1011. v3s16 currentPos = e.pos;
  1012. s8 dist = e.dist + 1;
  1013. for (const v3s16& off : dirs) {
  1014. v3s16 neighborPos = currentPos + off;
  1015. s64 neighborHash = MapDatabase::getBlockAsInteger(neighborPos);
  1016. // Do not walk neighborPos multiple times unless the distance to the start
  1017. // position is shorter
  1018. auto it = dists.find(neighborHash);
  1019. if (it != dists.end() && dist >= it->second)
  1020. continue;
  1021. // Position to walk
  1022. bool is_position_ok;
  1023. MapNode node = m_map->getNode(neighborPos, &is_position_ok);
  1024. if (!is_position_ok) {
  1025. // This happens very rarely because the map at currentPos is loaded
  1026. m_map->emergeBlock(neighborPos, false);
  1027. node = m_map->getNode(neighborPos, &is_position_ok);
  1028. if (!is_position_ok)
  1029. continue; // not generated
  1030. }
  1031. const ContentFeatures &def = ndef->get(node);
  1032. if (!def.sunlight_propagates) {
  1033. // Do not test propagation here again
  1034. dists[neighborHash] = -1;
  1035. continue;
  1036. }
  1037. // Sunlight could have come from here
  1038. dists[neighborHash] = dist;
  1039. u8 daylight = node.param1 & 0x0f;
  1040. // In the special case where sunlight shines from above and thus
  1041. // does not decrease with upwards distance, daylight is always
  1042. // bigger than nightlight, which never reaches 15
  1043. int possible_finlight = daylight - dist;
  1044. if (possible_finlight <= found_light) {
  1045. // Light from here cannot make a brighter light at currentPos than
  1046. // found_light
  1047. continue;
  1048. }
  1049. u8 nightlight = node.param1 >> 4;
  1050. if (daylight > nightlight) {
  1051. // Found a valid daylight
  1052. found_light = possible_finlight;
  1053. } else {
  1054. // Sunlight may be darker, so walk the neighbors
  1055. stack.push({neighborPos, dist});
  1056. }
  1057. }
  1058. }
  1059. return found_light;
  1060. }
  1061. void ServerEnvironment::clearObjects(ClearObjectsMode mode)
  1062. {
  1063. infostream << "ServerEnvironment::clearObjects(): "
  1064. << "Removing all active objects" << std::endl;
  1065. auto cb_removal = [this] (ServerActiveObject *obj, u16 id) {
  1066. if (obj->getType() == ACTIVEOBJECT_TYPE_PLAYER)
  1067. return false;
  1068. // Delete static object if block is loaded
  1069. deleteStaticFromBlock(obj, id, MOD_REASON_CLEAR_ALL_OBJECTS, true);
  1070. obj->markForRemoval();
  1071. // If known by some client, don't delete immediately
  1072. if (obj->m_known_by_count > 0)
  1073. return false;
  1074. processActiveObjectRemove(obj);
  1075. // Delete active object
  1076. return true;
  1077. };
  1078. m_ao_manager.clearIf(cb_removal);
  1079. // Get list of loaded blocks
  1080. std::vector<v3s16> loaded_blocks;
  1081. infostream << "ServerEnvironment::clearObjects(): "
  1082. << "Listing all loaded blocks" << std::endl;
  1083. m_map->listAllLoadedBlocks(loaded_blocks);
  1084. infostream << "ServerEnvironment::clearObjects(): "
  1085. << "Done listing all loaded blocks: "
  1086. << loaded_blocks.size()<<std::endl;
  1087. // Get list of loadable blocks
  1088. std::vector<v3s16> loadable_blocks;
  1089. if (mode == CLEAR_OBJECTS_MODE_FULL) {
  1090. infostream << "ServerEnvironment::clearObjects(): "
  1091. << "Listing all loadable blocks" << std::endl;
  1092. m_map->listAllLoadableBlocks(loadable_blocks);
  1093. infostream << "ServerEnvironment::clearObjects(): "
  1094. << "Done listing all loadable blocks: "
  1095. << loadable_blocks.size() << std::endl;
  1096. } else {
  1097. loadable_blocks = loaded_blocks;
  1098. }
  1099. actionstream << "ServerEnvironment::clearObjects(): "
  1100. << "Now clearing objects in " << loadable_blocks.size()
  1101. << " blocks" << std::endl;
  1102. // Grab a reference on each loaded block to avoid unloading it
  1103. for (v3s16 p : loaded_blocks) {
  1104. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  1105. assert(block != NULL);
  1106. block->refGrab();
  1107. }
  1108. // Remove objects in all loadable blocks
  1109. u32 unload_interval = U32_MAX;
  1110. if (mode == CLEAR_OBJECTS_MODE_FULL) {
  1111. unload_interval = g_settings->getS32("max_clearobjects_extra_loaded_blocks");
  1112. unload_interval = MYMAX(unload_interval, 1);
  1113. }
  1114. u32 report_interval = loadable_blocks.size() / 10;
  1115. u32 num_blocks_checked = 0;
  1116. u32 num_blocks_cleared = 0;
  1117. u32 num_objs_cleared = 0;
  1118. for (auto i = loadable_blocks.begin();
  1119. i != loadable_blocks.end(); ++i) {
  1120. v3s16 p = *i;
  1121. MapBlock *block = m_map->emergeBlock(p, false);
  1122. if (!block) {
  1123. errorstream << "ServerEnvironment::clearObjects(): "
  1124. << "Failed to emerge block " << p << std::endl;
  1125. continue;
  1126. }
  1127. u32 num_cleared = block->clearObjects();
  1128. if (num_cleared > 0) {
  1129. num_objs_cleared += num_cleared;
  1130. num_blocks_cleared++;
  1131. }
  1132. num_blocks_checked++;
  1133. if (report_interval != 0 &&
  1134. num_blocks_checked % report_interval == 0) {
  1135. float percent = 100.0 * (float)num_blocks_checked /
  1136. loadable_blocks.size();
  1137. actionstream << "ServerEnvironment::clearObjects(): "
  1138. << "Cleared " << num_objs_cleared << " objects"
  1139. << " in " << num_blocks_cleared << " blocks ("
  1140. << percent << "%)" << std::endl;
  1141. }
  1142. if (num_blocks_checked % unload_interval == 0) {
  1143. m_map->unloadUnreferencedBlocks();
  1144. }
  1145. }
  1146. m_map->unloadUnreferencedBlocks();
  1147. // Drop references that were added above
  1148. for (v3s16 p : loaded_blocks) {
  1149. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  1150. assert(block);
  1151. block->refDrop();
  1152. }
  1153. m_last_clear_objects_time = m_game_time;
  1154. actionstream << "ServerEnvironment::clearObjects(): "
  1155. << "Finished: Cleared " << num_objs_cleared << " objects"
  1156. << " in " << num_blocks_cleared << " blocks" << std::endl;
  1157. }
  1158. void ServerEnvironment::step(float dtime)
  1159. {
  1160. ScopeProfiler sp2(g_profiler, "ServerEnv::step()", SPT_AVG);
  1161. const auto start_time = porting::getTimeUs();
  1162. /* Step time of day */
  1163. stepTimeOfDay(dtime);
  1164. // Update this one
  1165. // NOTE: This is kind of funny on a singleplayer game, but doesn't
  1166. // really matter that much.
  1167. static thread_local const float server_step =
  1168. g_settings->getFloat("dedicated_server_step");
  1169. m_recommended_send_interval = server_step;
  1170. /*
  1171. Increment game time
  1172. */
  1173. {
  1174. m_game_time_fraction_counter += dtime;
  1175. u32 inc_i = (u32)m_game_time_fraction_counter;
  1176. m_game_time += inc_i;
  1177. m_game_time_fraction_counter -= (float)inc_i;
  1178. }
  1179. /*
  1180. Handle players
  1181. */
  1182. {
  1183. ScopeProfiler sp(g_profiler, "ServerEnv: move players", SPT_AVG);
  1184. for (RemotePlayer *player : m_players) {
  1185. // Ignore disconnected players
  1186. if (player->getPeerId() == PEER_ID_INEXISTENT)
  1187. continue;
  1188. // Move
  1189. player->move(dtime, this, 100 * BS);
  1190. }
  1191. }
  1192. /*
  1193. Manage active block list
  1194. */
  1195. if (m_active_blocks_mgmt_interval.step(dtime, m_cache_active_block_mgmt_interval / m_fast_active_block_divider)) {
  1196. ScopeProfiler sp(g_profiler, "ServerEnv: update active blocks", SPT_AVG);
  1197. /*
  1198. Get player block positions
  1199. */
  1200. std::vector<PlayerSAO*> players;
  1201. players.reserve(m_players.size());
  1202. for (RemotePlayer *player : m_players) {
  1203. // Ignore disconnected players
  1204. if (player->getPeerId() == PEER_ID_INEXISTENT)
  1205. continue;
  1206. PlayerSAO *playersao = player->getPlayerSAO();
  1207. assert(playersao);
  1208. players.push_back(playersao);
  1209. }
  1210. /*
  1211. Update list of active blocks, collecting changes
  1212. */
  1213. // use active_object_send_range_blocks since that is max distance
  1214. // for active objects sent the client anyway
  1215. static thread_local const s16 active_object_range =
  1216. g_settings->getS16("active_object_send_range_blocks");
  1217. static thread_local const s16 active_block_range =
  1218. g_settings->getS16("active_block_range");
  1219. std::set<v3s16> blocks_removed;
  1220. std::set<v3s16> blocks_added;
  1221. std::set<v3s16> extra_blocks_added;
  1222. m_active_blocks.update(players, active_block_range, active_object_range,
  1223. blocks_removed, blocks_added, extra_blocks_added);
  1224. /*
  1225. Handle removed blocks
  1226. */
  1227. // Convert active objects that are no more in active blocks to static
  1228. deactivateFarObjects(false);
  1229. for (const v3s16 &p: blocks_removed) {
  1230. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  1231. if (!block)
  1232. continue;
  1233. // Set current time as timestamp (and let it set ChangedFlag)
  1234. block->setTimestamp(m_game_time);
  1235. }
  1236. /*
  1237. Handle added blocks
  1238. */
  1239. for (const v3s16 &p: blocks_added) {
  1240. MapBlock *block = m_map->getBlockOrEmerge(p, true);
  1241. if (!block) {
  1242. // TODO: The blocks removed here will only be picked up again
  1243. // on the next cycle. To minimize the latency of objects being
  1244. // activated we could remember the blocks pending activating
  1245. // and activate them instantly as soon as they're loaded.
  1246. m_active_blocks.remove(p);
  1247. continue;
  1248. }
  1249. activateBlock(block);
  1250. }
  1251. for (const v3s16 &p: extra_blocks_added) {
  1252. // only activate if the block is already loaded
  1253. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  1254. if (!block) {
  1255. m_active_blocks.remove(p);
  1256. continue;
  1257. }
  1258. activateBlock(block);
  1259. }
  1260. // Some blocks may be removed again by the code above so do this here
  1261. m_active_block_gauge->set(m_active_blocks.size());
  1262. if (m_fast_active_block_divider > 1)
  1263. --m_fast_active_block_divider;
  1264. }
  1265. /*
  1266. Mess around in active blocks
  1267. */
  1268. if (m_active_blocks_nodemetadata_interval.step(dtime, m_cache_nodetimer_interval)) {
  1269. ScopeProfiler sp(g_profiler, "ServerEnv: Run node timers", SPT_AVG);
  1270. float dtime = m_cache_nodetimer_interval;
  1271. for (const v3s16 &p: m_active_blocks.m_list) {
  1272. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  1273. if (!block)
  1274. continue;
  1275. // Reset block usage timer
  1276. block->resetUsageTimer();
  1277. // Set current time as timestamp
  1278. block->setTimestampNoChangedFlag(m_game_time);
  1279. // If time has changed much from the one on disk,
  1280. // set block to be saved when it is unloaded
  1281. if(block->getTimestamp() > block->getDiskTimestamp() + 60)
  1282. block->raiseModified(MOD_STATE_WRITE_AT_UNLOAD,
  1283. MOD_REASON_BLOCK_EXPIRED);
  1284. // Run node timers
  1285. block->step(dtime, [&](v3s16 p, MapNode n, f32 d) -> bool {
  1286. return m_script->node_on_timer(p, n, d);
  1287. });
  1288. }
  1289. }
  1290. if (m_active_block_modifier_interval.step(dtime, m_cache_abm_interval)) {
  1291. ScopeProfiler sp(g_profiler, "SEnv: modify in blocks avg per interval", SPT_AVG);
  1292. TimeTaker timer("modify in active blocks per interval");
  1293. // Shuffle to prevent persistent artifacts of ordering
  1294. std::shuffle(m_abms.begin(), m_abms.end(), MyRandGenerator());
  1295. // Initialize handling of ActiveBlockModifiers
  1296. ABMHandler abmhandler(m_abms, m_cache_abm_interval, this, true);
  1297. int blocks_scanned = 0;
  1298. int abms_run = 0;
  1299. int blocks_cached = 0;
  1300. std::vector<v3s16> output(m_active_blocks.m_abm_list.size());
  1301. // Shuffle the active blocks so that each block gets an equal chance
  1302. // of having its ABMs run.
  1303. std::copy(m_active_blocks.m_abm_list.begin(), m_active_blocks.m_abm_list.end(), output.begin());
  1304. std::shuffle(output.begin(), output.end(), MyRandGenerator());
  1305. int i = 0;
  1306. // determine the time budget for ABMs
  1307. u32 max_time_ms = m_cache_abm_interval * 1000 * m_cache_abm_time_budget;
  1308. for (const v3s16 &p : output) {
  1309. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  1310. if (!block)
  1311. continue;
  1312. i++;
  1313. // Set current time as timestamp
  1314. block->setTimestampNoChangedFlag(m_game_time);
  1315. /* Handle ActiveBlockModifiers */
  1316. abmhandler.apply(block, blocks_scanned, abms_run, blocks_cached);
  1317. u32 time_ms = timer.getTimerTime();
  1318. if (time_ms > max_time_ms) {
  1319. warningstream << "active block modifiers took "
  1320. << time_ms << "ms (processed " << i << " of "
  1321. << output.size() << " active blocks)" << std::endl;
  1322. break;
  1323. }
  1324. }
  1325. g_profiler->avg("ServerEnv: active blocks", m_active_blocks.m_abm_list.size());
  1326. g_profiler->avg("ServerEnv: active blocks cached", blocks_cached);
  1327. g_profiler->avg("ServerEnv: active blocks scanned for ABMs", blocks_scanned);
  1328. g_profiler->avg("ServerEnv: ABMs run", abms_run);
  1329. timer.stop(true);
  1330. }
  1331. /*
  1332. Step script environment (run global on_step())
  1333. */
  1334. m_script->environment_Step(dtime);
  1335. m_script->stepAsync();
  1336. /*
  1337. Step active objects
  1338. */
  1339. {
  1340. ScopeProfiler sp(g_profiler, "ServerEnv: Run SAO::step()", SPT_AVG);
  1341. // This helps the objects to send data at the same time
  1342. bool send_recommended = false;
  1343. m_send_recommended_timer += dtime;
  1344. if (m_send_recommended_timer > getSendRecommendedInterval()) {
  1345. m_send_recommended_timer -= getSendRecommendedInterval();
  1346. send_recommended = true;
  1347. }
  1348. u32 object_count = 0;
  1349. auto cb_state = [&](ServerActiveObject *obj) {
  1350. if (obj->isGone())
  1351. return;
  1352. object_count++;
  1353. // Step object
  1354. obj->step(dtime, send_recommended);
  1355. // Read messages from object
  1356. obj->dumpAOMessagesToQueue(m_active_object_messages);
  1357. };
  1358. m_ao_manager.step(dtime, cb_state);
  1359. m_active_object_gauge->set(object_count);
  1360. }
  1361. /*
  1362. Manage active objects
  1363. */
  1364. if (m_object_management_interval.step(dtime, 0.5)) {
  1365. removeRemovedObjects();
  1366. }
  1367. /*
  1368. Manage particle spawner expiration
  1369. */
  1370. if (m_particle_management_interval.step(dtime, 1.0)) {
  1371. for (auto i = m_particle_spawners.begin(); i != m_particle_spawners.end(); ) {
  1372. // non expiring spawners
  1373. if (i->second == PARTICLE_SPAWNER_NO_EXPIRY) {
  1374. ++i;
  1375. continue;
  1376. }
  1377. i->second -= 1.0f;
  1378. if (i->second <= 0.f)
  1379. i = m_particle_spawners.erase(i);
  1380. else
  1381. ++i;
  1382. }
  1383. }
  1384. // Send outdated player inventories
  1385. for (RemotePlayer *player : m_players) {
  1386. if (player->getPeerId() == PEER_ID_INEXISTENT)
  1387. continue;
  1388. if (player->inventory.checkModified())
  1389. m_server->SendInventory(player, true);
  1390. }
  1391. // Send outdated detached inventories
  1392. if (!m_players.empty())
  1393. m_server->sendDetachedInventories(PEER_ID_INEXISTENT, true);
  1394. // Notify mods of modified mapblocks
  1395. if (m_on_mapblocks_changed_receiver.receiving &&
  1396. !m_on_mapblocks_changed_receiver.modified_blocks.empty()) {
  1397. std::unordered_set<v3s16> modified_blocks;
  1398. std::swap(modified_blocks, m_on_mapblocks_changed_receiver.modified_blocks);
  1399. m_script->on_mapblocks_changed(modified_blocks);
  1400. }
  1401. const auto end_time = porting::getTimeUs();
  1402. m_step_time_counter->increment(end_time - start_time);
  1403. }
  1404. ServerEnvironment::BlockStatus ServerEnvironment::getBlockStatus(v3s16 blockpos)
  1405. {
  1406. if (m_active_blocks.contains(blockpos))
  1407. return BS_ACTIVE;
  1408. const MapBlock *block = m_map->getBlockNoCreateNoEx(blockpos);
  1409. if (block)
  1410. return BS_LOADED;
  1411. if (m_map->isBlockInQueue(blockpos))
  1412. return BS_EMERGING;
  1413. return BS_UNKNOWN;
  1414. }
  1415. u32 ServerEnvironment::addParticleSpawner(float exptime)
  1416. {
  1417. // Timers with lifetime 0 do not expire
  1418. float time = exptime > 0.f ? exptime : PARTICLE_SPAWNER_NO_EXPIRY;
  1419. u32 free_id = m_particle_spawners_id_last_used;
  1420. do {
  1421. free_id++;
  1422. if (free_id == m_particle_spawners_id_last_used)
  1423. return 0; // full
  1424. } while (free_id == 0 || m_particle_spawners.find(free_id) != m_particle_spawners.end());
  1425. m_particle_spawners_id_last_used = free_id;
  1426. m_particle_spawners[free_id] = time;
  1427. return free_id;
  1428. }
  1429. u32 ServerEnvironment::addParticleSpawner(float exptime, u16 attached_id)
  1430. {
  1431. u32 id = addParticleSpawner(exptime);
  1432. m_particle_spawner_attachments[id] = attached_id;
  1433. if (ServerActiveObject *obj = getActiveObject(attached_id)) {
  1434. obj->attachParticleSpawner(id);
  1435. }
  1436. return id;
  1437. }
  1438. void ServerEnvironment::deleteParticleSpawner(u32 id, bool remove_from_object)
  1439. {
  1440. m_particle_spawners.erase(id);
  1441. const auto &it = m_particle_spawner_attachments.find(id);
  1442. if (it != m_particle_spawner_attachments.end()) {
  1443. u16 obj_id = it->second;
  1444. ServerActiveObject *sao = getActiveObject(obj_id);
  1445. if (sao != NULL && remove_from_object) {
  1446. sao->detachParticleSpawner(id);
  1447. }
  1448. m_particle_spawner_attachments.erase(id);
  1449. }
  1450. }
  1451. u16 ServerEnvironment::addActiveObject(std::unique_ptr<ServerActiveObject> object)
  1452. {
  1453. assert(object); // Pre-condition
  1454. m_added_objects++;
  1455. u16 id = addActiveObjectRaw(std::move(object), nullptr, 0);
  1456. return id;
  1457. }
  1458. /*
  1459. Finds out what new objects have been added to
  1460. inside a radius around a position
  1461. */
  1462. void ServerEnvironment::getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
  1463. s16 player_radius,
  1464. const std::set<u16> &current_objects,
  1465. std::vector<u16> &added_objects)
  1466. {
  1467. f32 radius_f = radius * BS;
  1468. f32 player_radius_f = player_radius * BS;
  1469. if (player_radius_f < 0.0f)
  1470. player_radius_f = 0.0f;
  1471. m_ao_manager.getAddedActiveObjectsAroundPos(playersao->getBasePosition(), radius_f,
  1472. player_radius_f, current_objects, added_objects);
  1473. }
  1474. /*
  1475. Finds out what objects have been removed from
  1476. inside a radius around a position
  1477. */
  1478. void ServerEnvironment::getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
  1479. s16 player_radius,
  1480. const std::set<u16> &current_objects,
  1481. std::vector<std::pair<bool /* gone? */, u16>> &removed_objects)
  1482. {
  1483. f32 radius_f = radius * BS;
  1484. f32 player_radius_f = player_radius * BS;
  1485. if (player_radius_f < 0)
  1486. player_radius_f = 0;
  1487. /*
  1488. Go through current_objects; object is removed if:
  1489. - object is not found in m_active_objects (this is actually an
  1490. error condition; objects should be removed only after all clients
  1491. have been informed about removal), or
  1492. - object is to be removed or deactivated, or
  1493. - object is too far away
  1494. */
  1495. for (u16 id : current_objects) {
  1496. ServerActiveObject *object = getActiveObject(id);
  1497. if (!object) {
  1498. warningstream << FUNCTION_NAME << ": found NULL object id="
  1499. << (int)id << std::endl;
  1500. removed_objects.emplace_back(true, id);
  1501. continue;
  1502. }
  1503. if (object->isGone()) {
  1504. removed_objects.emplace_back(true, id);
  1505. continue;
  1506. }
  1507. f32 distance_f = object->getBasePosition().getDistanceFrom(playersao->getBasePosition());
  1508. if (object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
  1509. if (distance_f <= player_radius_f || player_radius_f == 0)
  1510. continue;
  1511. } else if (distance_f <= radius_f)
  1512. continue;
  1513. // Object is no longer visible
  1514. removed_objects.emplace_back(false, id);
  1515. }
  1516. }
  1517. void ServerEnvironment::setStaticForActiveObjectsInBlock(
  1518. v3s16 blockpos, bool static_exists, v3s16 static_block)
  1519. {
  1520. MapBlock *block = m_map->getBlockNoCreateNoEx(blockpos);
  1521. if (!block)
  1522. return;
  1523. for (auto &so_it : block->m_static_objects.getAllActives()) {
  1524. // Get the ServerActiveObject counterpart to this StaticObject
  1525. ServerActiveObject *sao = m_ao_manager.getActiveObject(so_it.first);
  1526. if (!sao) {
  1527. // If this ever happens, there must be some kind of nasty bug.
  1528. errorstream << "ServerEnvironment::setStaticForObjectsInBlock(): "
  1529. "Object from MapBlock::m_static_objects::m_active not found "
  1530. "in m_active_objects";
  1531. continue;
  1532. }
  1533. sao->m_static_exists = static_exists;
  1534. sao->m_static_block = static_block;
  1535. }
  1536. }
  1537. bool ServerEnvironment::getActiveObjectMessage(ActiveObjectMessage *dest)
  1538. {
  1539. if (m_active_object_messages.empty())
  1540. return false;
  1541. *dest = std::move(m_active_object_messages.front());
  1542. m_active_object_messages.pop();
  1543. return true;
  1544. }
  1545. void ServerEnvironment::getSelectedActiveObjects(
  1546. const core::line3d<f32> &shootline_on_map,
  1547. std::vector<PointedThing> &objects,
  1548. const std::optional<Pointabilities> &pointabilities)
  1549. {
  1550. std::vector<ServerActiveObject *> objs;
  1551. getObjectsInsideRadius(objs, shootline_on_map.getMiddle(),
  1552. 0.5 * shootline_on_map.getLength() + 5 * BS, nullptr);
  1553. const v3f line_vector = shootline_on_map.getVector();
  1554. for (auto obj : objs) {
  1555. if (obj->isGone())
  1556. continue;
  1557. aabb3f selection_box;
  1558. if (!obj->getSelectionBox(&selection_box))
  1559. continue;
  1560. v3f pos = obj->getBasePosition();
  1561. v3f rel_pos = shootline_on_map.start - pos;
  1562. v3f current_intersection;
  1563. v3f current_normal;
  1564. v3f current_raw_normal;
  1565. ObjectProperties *props = obj->accessObjectProperties();
  1566. bool collision;
  1567. UnitSAO* usao = dynamic_cast<UnitSAO*>(obj);
  1568. if (props->rotate_selectionbox && usao != nullptr) {
  1569. collision = boxLineCollision(selection_box, usao->getTotalRotation(),
  1570. rel_pos, line_vector, &current_intersection, &current_normal, &current_raw_normal);
  1571. } else {
  1572. collision = boxLineCollision(selection_box, rel_pos, line_vector,
  1573. &current_intersection, &current_normal);
  1574. current_raw_normal = current_normal;
  1575. }
  1576. if (collision) {
  1577. PointabilityType pointable;
  1578. if (pointabilities) {
  1579. if (LuaEntitySAO* lsao = dynamic_cast<LuaEntitySAO*>(obj)) {
  1580. pointable = pointabilities->matchObject(lsao->getName(),
  1581. usao->getArmorGroups()).value_or(props->pointable);
  1582. } else if (PlayerSAO* psao = dynamic_cast<PlayerSAO*>(obj)) {
  1583. pointable = pointabilities->matchPlayer(psao->getArmorGroups()).value_or(
  1584. props->pointable);
  1585. } else {
  1586. pointable = props->pointable;
  1587. }
  1588. } else {
  1589. pointable = props->pointable;
  1590. }
  1591. if (pointable != PointabilityType::POINTABLE_NOT) {
  1592. current_intersection += pos;
  1593. objects.emplace_back(
  1594. (s16) obj->getId(), current_intersection, current_normal, current_raw_normal,
  1595. (current_intersection - shootline_on_map.start).getLengthSQ(), pointable);
  1596. }
  1597. }
  1598. }
  1599. }
  1600. /*
  1601. ************ Private methods *************
  1602. */
  1603. u16 ServerEnvironment::addActiveObjectRaw(std::unique_ptr<ServerActiveObject> object_u,
  1604. const StaticObject *from_static, u32 dtime_s)
  1605. {
  1606. auto object = object_u.get();
  1607. if (!m_ao_manager.registerObject(std::move(object_u))) {
  1608. return 0;
  1609. }
  1610. // Register reference in scripting api (must be done before post-init)
  1611. m_script->addObjectReference(object);
  1612. // Post-initialize object
  1613. // Note that this can change the value of isStaticAllowed() in case of LuaEntitySAO
  1614. object->addedToEnvironment(dtime_s);
  1615. // Activate object
  1616. if (object->m_static_exists)
  1617. {
  1618. sanity_check(from_static);
  1619. /*
  1620. * Note: Don't check isStaticAllowed() here. If an object has static data
  1621. * when it shouldn't, we still need to activate it so the static data
  1622. * can be properly removed.
  1623. */
  1624. auto blockpos = object->m_static_block;
  1625. MapBlock *block = m_map->emergeBlock(blockpos);
  1626. if (block) {
  1627. block->m_static_objects.setActive(object->getId(), *from_static);
  1628. } else {
  1629. warningstream << "ServerEnvironment::addActiveObjectRaw(): "
  1630. << "object was supposed to be in block " << blockpos
  1631. << ", but this block disappeared." << std::endl;
  1632. object->m_static_exists = false;
  1633. }
  1634. }
  1635. // Add static data to block
  1636. else if (object->isStaticAllowed())
  1637. {
  1638. v3f objectpos = object->getBasePosition();
  1639. StaticObject s_obj(object, objectpos);
  1640. // Add to the block where the object is located in
  1641. v3s16 blockpos = getNodeBlockPos(floatToInt(objectpos, BS));
  1642. MapBlock *block = m_map->emergeBlock(blockpos);
  1643. if (block) {
  1644. block->m_static_objects.setActive(object->getId(), s_obj);
  1645. object->m_static_exists = true;
  1646. object->m_static_block = blockpos;
  1647. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  1648. MOD_REASON_ADD_ACTIVE_OBJECT_RAW);
  1649. } else {
  1650. v3s16 p = floatToInt(objectpos, BS);
  1651. errorstream << "ServerEnvironment::addActiveObjectRaw(): "
  1652. << "could not emerge block " << p << " for storing id="
  1653. << object->getId() << " statically" << std::endl;
  1654. // clean in case of error
  1655. object->markForRemoval();
  1656. processActiveObjectRemove(object);
  1657. m_ao_manager.removeObject(object->getId());
  1658. return 0;
  1659. }
  1660. }
  1661. return object->getId();
  1662. }
  1663. /*
  1664. Remove objects that satisfy (isGone() && m_known_by_count==0)
  1665. */
  1666. void ServerEnvironment::removeRemovedObjects()
  1667. {
  1668. ScopeProfiler sp(g_profiler, "ServerEnvironment::removeRemovedObjects()", SPT_AVG);
  1669. auto clear_cb = [this](ServerActiveObject *obj, u16 id) {
  1670. /*
  1671. We will handle objects marked for removal or deactivation
  1672. */
  1673. if (!obj->isGone())
  1674. return false;
  1675. /*
  1676. Delete static data from block if removed
  1677. */
  1678. if (obj->isPendingRemoval())
  1679. deleteStaticFromBlock(obj, id, MOD_REASON_REMOVE_OBJECTS_REMOVE, false);
  1680. // If still known by clients, don't actually remove. On some future
  1681. // invocation this will be 0, which is when removal will continue.
  1682. if (obj->m_known_by_count > 0)
  1683. return false;
  1684. /*
  1685. Move static data from active to stored if deactivated
  1686. */
  1687. if (!obj->isPendingRemoval() && obj->m_static_exists) {
  1688. if (MapBlock *block = m_map->emergeBlock(obj->m_static_block, false)) {
  1689. if (!block->storeActiveObject(id)) {
  1690. warningstream << "ServerEnvironment::removeRemovedObjects(): "
  1691. << "id=" << id << " m_static_exists=true but "
  1692. << "static data doesn't actually exist in "
  1693. << obj->m_static_block << std::endl;
  1694. }
  1695. } else {
  1696. infostream << "Failed to emerge block from which an object to "
  1697. << "be deactivated was loaded from. id=" << id << std::endl;
  1698. }
  1699. }
  1700. processActiveObjectRemove(obj);
  1701. // Delete
  1702. return true;
  1703. };
  1704. m_ao_manager.clearIf(clear_cb);
  1705. }
  1706. static void print_hexdump(std::ostream &o, const std::string &data)
  1707. {
  1708. const int linelength = 16;
  1709. for (int l = 0;; l++) {
  1710. int i0 = linelength * l;
  1711. bool at_end = false;
  1712. int thislinelength = linelength;
  1713. if (i0 + thislinelength > (int)data.size()) {
  1714. thislinelength = data.size() - i0;
  1715. at_end = true;
  1716. }
  1717. for (int di = 0; di < linelength; di++) {
  1718. int i = i0 + di;
  1719. char buf[4];
  1720. if (di < thislinelength)
  1721. porting::mt_snprintf(buf, sizeof(buf), "%.2x ", data[i]);
  1722. else
  1723. porting::mt_snprintf(buf, sizeof(buf), " ");
  1724. o << buf;
  1725. }
  1726. o << " ";
  1727. for (int di = 0; di < thislinelength; di++) {
  1728. int i = i0 + di;
  1729. if (data[i] >= 32)
  1730. o << data[i];
  1731. else
  1732. o << ".";
  1733. }
  1734. o << std::endl;
  1735. if (at_end)
  1736. break;
  1737. }
  1738. }
  1739. std::unique_ptr<ServerActiveObject> ServerEnvironment::createSAO(ActiveObjectType type,
  1740. v3f pos, const std::string &data)
  1741. {
  1742. switch (type) {
  1743. case ACTIVEOBJECT_TYPE_LUAENTITY:
  1744. return std::make_unique<LuaEntitySAO>(this, pos, data);
  1745. default:
  1746. warningstream << "ServerActiveObject: No factory for type=" << type << std::endl;
  1747. }
  1748. return nullptr;
  1749. }
  1750. /*
  1751. Convert stored objects from blocks near the players to active.
  1752. */
  1753. void ServerEnvironment::activateObjects(MapBlock *block, u32 dtime_s)
  1754. {
  1755. if (block == NULL)
  1756. return;
  1757. if (!block->onObjectsActivation())
  1758. return;
  1759. // Activate stored objects
  1760. std::vector<StaticObject> new_stored;
  1761. for (const StaticObject &s_obj : block->m_static_objects.getAllStored()) {
  1762. // Create an active object from the data
  1763. std::unique_ptr<ServerActiveObject> obj =
  1764. createSAO((ActiveObjectType)s_obj.type, s_obj.pos, s_obj.data);
  1765. // If couldn't create object, store static data back.
  1766. if (!obj) {
  1767. errorstream << "ServerEnvironment::activateObjects(): "
  1768. << "failed to create active object from static object "
  1769. << "in block " << block->getPos()
  1770. << " type=" << (int)s_obj.type << " data:" << std::endl;
  1771. print_hexdump(verbosestream, s_obj.data);
  1772. new_stored.push_back(s_obj);
  1773. continue;
  1774. }
  1775. obj->m_static_exists = true;
  1776. obj->m_static_block = block->getPos();
  1777. // This will also add the object to the active static list
  1778. bool ok = addActiveObjectRaw(std::move(obj), &s_obj, dtime_s) != 0;
  1779. if (ok) {
  1780. verbosestream << "ServerEnvironment::activateObjects(): "
  1781. << "activated static object pos=" << (s_obj.pos / BS)
  1782. << " type=" << (int)s_obj.type << std::endl;
  1783. }
  1784. // callbacks could invalidate this block
  1785. if (block->isOrphan())
  1786. return;
  1787. }
  1788. // Clear stored list
  1789. block->m_static_objects.clearStored();
  1790. // Add leftover failed stuff to stored list
  1791. for (const StaticObject &s_obj : new_stored) {
  1792. block->m_static_objects.pushStored(s_obj);
  1793. }
  1794. /*
  1795. Note: Block hasn't really been modified here.
  1796. The objects have just been activated and moved from the stored
  1797. static list to the active static list.
  1798. As such, the block is essentially the same.
  1799. Thus, do not call block->raiseModified(MOD_STATE_WRITE_NEEDED).
  1800. Otherwise there would be a huge amount of unnecessary I/O.
  1801. */
  1802. }
  1803. /*
  1804. Convert objects that are not standing inside active blocks to static.
  1805. If m_known_by_count != 0, active object is not deleted, but static
  1806. data is still updated.
  1807. If force_delete is set, active object is deleted nevertheless. It
  1808. shall only be set so in the destructor of the environment.
  1809. If block wasn't generated (not in memory or on disk),
  1810. */
  1811. void ServerEnvironment::deactivateFarObjects(const bool _force_delete)
  1812. {
  1813. auto cb_deactivate = [this, _force_delete](ServerActiveObject *obj, u16 id) {
  1814. // force_delete might be overridden per object
  1815. bool force_delete = _force_delete;
  1816. // Do not deactivate if disallowed
  1817. if (!force_delete && !obj->shouldUnload())
  1818. return false;
  1819. // removeRemovedObjects() is responsible for these
  1820. if (!force_delete && obj->isGone())
  1821. return false;
  1822. const v3f &objectpos = obj->getBasePosition();
  1823. // The block in which the object resides in
  1824. v3s16 blockpos_o = getNodeBlockPos(floatToInt(objectpos, BS));
  1825. // If object's static data is stored in a deactivated block and object
  1826. // is actually located in an active block, re-save to the block in
  1827. // which the object is actually located in.
  1828. if (!force_delete && obj->isStaticAllowed() && obj->m_static_exists &&
  1829. !m_active_blocks.contains(obj->m_static_block) &&
  1830. m_active_blocks.contains(blockpos_o)) {
  1831. // Delete from block where object was located
  1832. deleteStaticFromBlock(obj, id, MOD_REASON_STATIC_DATA_REMOVED, false);
  1833. StaticObject s_obj(obj, objectpos);
  1834. // Save to block where object is located
  1835. saveStaticToBlock(blockpos_o, id, obj, s_obj, MOD_REASON_STATIC_DATA_ADDED);
  1836. return false;
  1837. }
  1838. // If block is still active, don't remove
  1839. bool still_active = obj->isStaticAllowed() ?
  1840. m_active_blocks.contains(blockpos_o) :
  1841. getMap().getBlockNoCreateNoEx(blockpos_o) != nullptr;
  1842. if (!force_delete && still_active)
  1843. return false;
  1844. verbosestream << "ServerEnvironment::deactivateFarObjects(): "
  1845. << "deactivating object id=" << id << " on inactive block "
  1846. << blockpos_o << std::endl;
  1847. // If known by some client, don't immediately delete.
  1848. bool pending_delete = (obj->m_known_by_count > 0 && !force_delete);
  1849. /*
  1850. Update the static data
  1851. */
  1852. if (obj->isStaticAllowed()) {
  1853. // Create new static object
  1854. StaticObject s_obj(obj, objectpos);
  1855. bool stays_in_same_block = false;
  1856. bool data_changed = true;
  1857. // Check if static data has changed considerably
  1858. if (obj->m_static_exists) {
  1859. if (obj->m_static_block == blockpos_o)
  1860. stays_in_same_block = true;
  1861. if (MapBlock *block = m_map->emergeBlock(obj->m_static_block, false)) {
  1862. const auto n = block->m_static_objects.getAllActives().find(id);
  1863. if (n != block->m_static_objects.getAllActives().end()) {
  1864. StaticObject static_old = n->second;
  1865. float save_movem = obj->getMinimumSavedMovement();
  1866. if (static_old.data == s_obj.data &&
  1867. (static_old.pos - objectpos).getLength() < save_movem)
  1868. data_changed = false;
  1869. } else {
  1870. warningstream << "ServerEnvironment::deactivateFarObjects(): "
  1871. << "id=" << id << " m_static_exists=true but "
  1872. << "static data doesn't actually exist in "
  1873. << obj->m_static_block << std::endl;
  1874. }
  1875. }
  1876. }
  1877. /*
  1878. While changes are always saved, blocks are only marked as modified
  1879. if the object has moved or different staticdata. (see above)
  1880. */
  1881. bool shall_be_written = (!stays_in_same_block || data_changed);
  1882. u32 reason = shall_be_written ? MOD_REASON_STATIC_DATA_CHANGED : MOD_REASON_UNKNOWN;
  1883. // Delete old static object
  1884. deleteStaticFromBlock(obj, id, reason, false);
  1885. // Add to the block where the object is located in
  1886. v3s16 blockpos = getNodeBlockPos(floatToInt(objectpos, BS));
  1887. u16 store_id = pending_delete ? id : 0;
  1888. if (!saveStaticToBlock(blockpos, store_id, obj, s_obj, reason))
  1889. force_delete = true;
  1890. } else {
  1891. // If the object has static data but shouldn't we need to get rid of it.
  1892. deleteStaticFromBlock(obj, id, MOD_REASON_STATIC_DATA_REMOVED, false);
  1893. }
  1894. // Regardless of what happens to the object at this point, deactivate it first.
  1895. // This ensures that LuaEntity on_deactivate is always called.
  1896. obj->markForDeactivation();
  1897. /*
  1898. If known by some client, set pending deactivation.
  1899. Otherwise delete it immediately.
  1900. */
  1901. if (pending_delete && !force_delete) {
  1902. verbosestream << "ServerEnvironment::deactivateFarObjects(): "
  1903. << "object id=" << id << " is known by clients"
  1904. << "; not deleting yet" << std::endl;
  1905. return false;
  1906. }
  1907. processActiveObjectRemove(obj);
  1908. // Delete active object
  1909. return true;
  1910. };
  1911. m_ao_manager.clearIf(cb_deactivate);
  1912. }
  1913. void ServerEnvironment::deleteStaticFromBlock(
  1914. ServerActiveObject *obj, u16 id, u32 mod_reason, bool no_emerge)
  1915. {
  1916. if (!obj->m_static_exists)
  1917. return;
  1918. MapBlock *block;
  1919. if (no_emerge)
  1920. block = m_map->getBlockNoCreateNoEx(obj->m_static_block);
  1921. else
  1922. block = m_map->emergeBlock(obj->m_static_block, false);
  1923. if (!block) {
  1924. if (!no_emerge)
  1925. errorstream << "ServerEnv: Failed to emerge block " << obj->m_static_block
  1926. << " when deleting static data of object from it. id=" << id << std::endl;
  1927. return;
  1928. }
  1929. block->m_static_objects.remove(id);
  1930. if (mod_reason != MOD_REASON_UNKNOWN) // Do not mark as modified if requested
  1931. block->raiseModified(MOD_STATE_WRITE_NEEDED, mod_reason);
  1932. obj->m_static_exists = false;
  1933. }
  1934. bool ServerEnvironment::saveStaticToBlock(
  1935. v3s16 blockpos, u16 store_id,
  1936. ServerActiveObject *obj, const StaticObject &s_obj,
  1937. u32 mod_reason)
  1938. {
  1939. MapBlock *block = nullptr;
  1940. try {
  1941. block = m_map->emergeBlock(blockpos);
  1942. } catch (InvalidPositionException &e) {
  1943. // Handled via NULL pointer
  1944. // NOTE: emergeBlock's failure is usually determined by it
  1945. // actually returning NULL
  1946. }
  1947. if (!block) {
  1948. errorstream << "ServerEnv: Failed to emerge block " << obj->m_static_block
  1949. << " when saving static data of object to it. id=" << store_id << std::endl;
  1950. return false;
  1951. }
  1952. if (!block->saveStaticObject(store_id, s_obj, mod_reason))
  1953. return false;
  1954. obj->m_static_exists = true;
  1955. obj->m_static_block = blockpos;
  1956. return true;
  1957. }
  1958. void ServerEnvironment::processActiveObjectRemove(ServerActiveObject *obj)
  1959. {
  1960. // markForRemoval or markForDeactivation should have been called before
  1961. // Not because it's strictly necessary but because the Lua callback is
  1962. // bound to that.
  1963. assert(obj->isGone());
  1964. // Tell the object about removal
  1965. obj->removingFromEnvironment();
  1966. // Deregister in scripting api
  1967. m_script->removeObjectReference(obj);
  1968. }
  1969. PlayerDatabase *ServerEnvironment::openPlayerDatabase(const std::string &name,
  1970. const std::string &savedir, const Settings &conf)
  1971. {
  1972. if (name == "sqlite3")
  1973. return new PlayerDatabaseSQLite3(savedir);
  1974. if (name == "dummy")
  1975. return new Database_Dummy();
  1976. #if USE_POSTGRESQL
  1977. if (name == "postgresql") {
  1978. std::string connect_string;
  1979. conf.getNoEx("pgsql_player_connection", connect_string);
  1980. return new PlayerDatabasePostgreSQL(connect_string);
  1981. }
  1982. #endif
  1983. #if USE_LEVELDB
  1984. if (name == "leveldb")
  1985. return new PlayerDatabaseLevelDB(savedir);
  1986. #endif
  1987. if (name == "files")
  1988. return new PlayerDatabaseFiles(savedir + DIR_DELIM + "players");
  1989. throw BaseException(std::string("Database backend ") + name + " not supported.");
  1990. }
  1991. bool ServerEnvironment::migratePlayersDatabase(const GameParams &game_params,
  1992. const Settings &cmd_args)
  1993. {
  1994. std::string migrate_to = cmd_args.get("migrate-players");
  1995. Settings world_mt;
  1996. std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
  1997. if (!world_mt.readConfigFile(world_mt_path.c_str())) {
  1998. errorstream << "Cannot read world.mt!" << std::endl;
  1999. return false;
  2000. }
  2001. if (!world_mt.exists("player_backend")) {
  2002. errorstream << "Please specify your current backend in world.mt:"
  2003. << std::endl
  2004. << " player_backend = {files|sqlite3|leveldb|postgresql}"
  2005. << std::endl;
  2006. return false;
  2007. }
  2008. std::string backend = world_mt.get("player_backend");
  2009. if (backend == migrate_to) {
  2010. errorstream << "Cannot migrate: new backend is same"
  2011. << " as the old one" << std::endl;
  2012. return false;
  2013. }
  2014. const std::string players_backup_path = game_params.world_path + DIR_DELIM
  2015. + "players.bak";
  2016. if (backend == "files") {
  2017. // Create backup directory
  2018. fs::CreateDir(players_backup_path);
  2019. }
  2020. try {
  2021. PlayerDatabase *srcdb = ServerEnvironment::openPlayerDatabase(backend,
  2022. game_params.world_path, world_mt);
  2023. PlayerDatabase *dstdb = ServerEnvironment::openPlayerDatabase(migrate_to,
  2024. game_params.world_path, world_mt);
  2025. std::vector<std::string> player_list;
  2026. srcdb->listPlayers(player_list);
  2027. for (std::vector<std::string>::const_iterator it = player_list.begin();
  2028. it != player_list.end(); ++it) {
  2029. actionstream << "Migrating player " << it->c_str() << std::endl;
  2030. RemotePlayer player(it->c_str(), NULL);
  2031. PlayerSAO playerSAO(NULL, &player, 15000, false);
  2032. srcdb->loadPlayer(&player, &playerSAO);
  2033. playerSAO.finalize(&player, std::set<std::string>());
  2034. player.setPlayerSAO(&playerSAO);
  2035. dstdb->savePlayer(&player);
  2036. // For files source, move player files to backup dir
  2037. if (backend == "files") {
  2038. fs::Rename(
  2039. game_params.world_path + DIR_DELIM + "players" + DIR_DELIM + (*it),
  2040. players_backup_path + DIR_DELIM + (*it));
  2041. }
  2042. }
  2043. actionstream << "Successfully migrated " << player_list.size() << " players"
  2044. << std::endl;
  2045. world_mt.set("player_backend", migrate_to);
  2046. if (!world_mt.updateConfigFile(world_mt_path.c_str()))
  2047. errorstream << "Failed to update world.mt!" << std::endl;
  2048. else
  2049. actionstream << "world.mt updated" << std::endl;
  2050. // When migration is finished from file backend, remove players directory if empty
  2051. if (backend == "files") {
  2052. fs::DeleteSingleFileOrEmptyDirectory(game_params.world_path + DIR_DELIM
  2053. + "players");
  2054. }
  2055. delete srcdb;
  2056. delete dstdb;
  2057. } catch (BaseException &e) {
  2058. errorstream << "An error occurred during migration: " << e.what() << std::endl;
  2059. return false;
  2060. }
  2061. return true;
  2062. }
  2063. AuthDatabase *ServerEnvironment::openAuthDatabase(
  2064. const std::string &name, const std::string &savedir, const Settings &conf)
  2065. {
  2066. if (name == "sqlite3")
  2067. return new AuthDatabaseSQLite3(savedir);
  2068. #if USE_POSTGRESQL
  2069. if (name == "postgresql") {
  2070. std::string connect_string;
  2071. conf.getNoEx("pgsql_auth_connection", connect_string);
  2072. return new AuthDatabasePostgreSQL(connect_string);
  2073. }
  2074. #endif
  2075. if (name == "files")
  2076. return new AuthDatabaseFiles(savedir);
  2077. #if USE_LEVELDB
  2078. if (name == "leveldb")
  2079. return new AuthDatabaseLevelDB(savedir);
  2080. #endif
  2081. throw BaseException(std::string("Database backend ") + name + " not supported.");
  2082. }
  2083. bool ServerEnvironment::migrateAuthDatabase(
  2084. const GameParams &game_params, const Settings &cmd_args)
  2085. {
  2086. std::string migrate_to = cmd_args.get("migrate-auth");
  2087. Settings world_mt;
  2088. std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
  2089. if (!world_mt.readConfigFile(world_mt_path.c_str())) {
  2090. errorstream << "Cannot read world.mt!" << std::endl;
  2091. return false;
  2092. }
  2093. std::string backend = "files";
  2094. if (world_mt.exists("auth_backend"))
  2095. backend = world_mt.get("auth_backend");
  2096. else
  2097. warningstream << "No auth_backend found in world.mt, "
  2098. "assuming \"files\"." << std::endl;
  2099. if (backend == migrate_to) {
  2100. errorstream << "Cannot migrate: new backend is same"
  2101. << " as the old one" << std::endl;
  2102. return false;
  2103. }
  2104. try {
  2105. const std::unique_ptr<AuthDatabase> srcdb(ServerEnvironment::openAuthDatabase(
  2106. backend, game_params.world_path, world_mt));
  2107. const std::unique_ptr<AuthDatabase> dstdb(ServerEnvironment::openAuthDatabase(
  2108. migrate_to, game_params.world_path, world_mt));
  2109. std::vector<std::string> names_list;
  2110. srcdb->listNames(names_list);
  2111. for (const std::string &name : names_list) {
  2112. actionstream << "Migrating auth entry for " << name << std::endl;
  2113. bool success;
  2114. AuthEntry authEntry;
  2115. success = srcdb->getAuth(name, authEntry);
  2116. success = success && dstdb->createAuth(authEntry);
  2117. if (!success)
  2118. errorstream << "Failed to migrate " << name << std::endl;
  2119. }
  2120. actionstream << "Successfully migrated " << names_list.size()
  2121. << " auth entries" << std::endl;
  2122. world_mt.set("auth_backend", migrate_to);
  2123. if (!world_mt.updateConfigFile(world_mt_path.c_str()))
  2124. errorstream << "Failed to update world.mt!" << std::endl;
  2125. else
  2126. actionstream << "world.mt updated" << std::endl;
  2127. if (backend == "files") {
  2128. // special-case files migration:
  2129. // move auth.txt to auth.txt.bak if possible
  2130. std::string auth_txt_path =
  2131. game_params.world_path + DIR_DELIM + "auth.txt";
  2132. std::string auth_bak_path = auth_txt_path + ".bak";
  2133. if (!fs::PathExists(auth_bak_path))
  2134. if (fs::Rename(auth_txt_path, auth_bak_path))
  2135. actionstream << "Renamed auth.txt to auth.txt.bak"
  2136. << std::endl;
  2137. else
  2138. errorstream << "Could not rename auth.txt to "
  2139. "auth.txt.bak" << std::endl;
  2140. else
  2141. warningstream << "auth.txt.bak already exists, auth.txt "
  2142. "not renamed" << std::endl;
  2143. }
  2144. } catch (BaseException &e) {
  2145. errorstream << "An error occurred during migration: " << e.what()
  2146. << std::endl;
  2147. return false;
  2148. }
  2149. return true;
  2150. }