serverenvironment.cpp 68 KB

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