serverenvironment.cpp 62 KB

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