forked from luanti-org/luanti
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserverenvironment.cpp
2442 lines (2078 loc) · 68.8 KB
/
serverenvironment.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Minetest
Copyright (C) 2010-2017 celeron55, Perttu Ahola <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <algorithm>
#include <stack>
#include "serverenvironment.h"
#include "settings.h"
#include "log.h"
#include "mapblock.h"
#include "nodedef.h"
#include "nodemetadata.h"
#include "gamedef.h"
#include "map.h"
#include "porting.h"
#include "profiler.h"
#include "raycast.h"
#include "remoteplayer.h"
#include "scripting_server.h"
#include "server.h"
#include "util/serialize.h"
#include "util/basic_macros.h"
#include "util/pointedthing.h"
#include "threading/mutex_auto_lock.h"
#include "filesys.h"
#include "gameparams.h"
#include "database/database-dummy.h"
#include "database/database-files.h"
#include "database/database-sqlite3.h"
#if USE_POSTGRESQL
#include "database/database-postgresql.h"
#endif
#if USE_LEVELDB
#include "database/database-leveldb.h"
#endif
#include "irrlicht_changes/printing.h"
#include "server/luaentity_sao.h"
#include "server/player_sao.h"
#define LBM_NAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyz0123456789_:"
// A number that is much smaller than the timeout for particle spawners should/could ever be
#define PARTICLE_SPAWNER_NO_EXPIRY -1024.f
/*
ABMWithState
*/
ABMWithState::ABMWithState(ActiveBlockModifier *abm_):
abm(abm_)
{
// Initialize timer to random value to spread processing
float itv = abm->getTriggerInterval();
itv = MYMAX(0.001, itv); // No less than 1ms
int minval = MYMAX(-0.51*itv, -60); // Clamp to
int maxval = MYMIN(0.51*itv, 60); // +-60 seconds
timer = myrand_range(minval, maxval);
}
/*
LBMManager
*/
void LBMContentMapping::deleteContents()
{
for (auto &it : lbm_list) {
delete it;
}
}
void LBMContentMapping::addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef)
{
// Add the lbm_def to the LBMContentMapping.
// Unknown names get added to the global NameIdMapping.
const NodeDefManager *nodedef = gamedef->ndef();
lbm_list.push_back(lbm_def);
for (const std::string &nodeTrigger: lbm_def->trigger_contents) {
std::vector<content_t> c_ids;
bool found = nodedef->getIds(nodeTrigger, c_ids);
if (!found) {
content_t c_id = gamedef->allocateUnknownNodeId(nodeTrigger);
if (c_id == CONTENT_IGNORE) {
// Seems it can't be allocated.
warningstream << "Could not internalize node name \"" << nodeTrigger
<< "\" while loading LBM \"" << lbm_def->name << "\"." << std::endl;
continue;
}
c_ids.push_back(c_id);
}
for (content_t c_id : c_ids) {
map[c_id].push_back(lbm_def);
}
}
}
const std::vector<LoadingBlockModifierDef *> *
LBMContentMapping::lookup(content_t c) const
{
lbm_map::const_iterator it = map.find(c);
if (it == map.end())
return NULL;
// This first dereferences the iterator, returning
// a std::vector<LoadingBlockModifierDef *>
// reference, then we convert it to a pointer.
return &(it->second);
}
LBMManager::~LBMManager()
{
for (auto &m_lbm_def : m_lbm_defs) {
delete m_lbm_def.second;
}
for (auto &it : m_lbm_lookup) {
(it.second).deleteContents();
}
}
void LBMManager::addLBMDef(LoadingBlockModifierDef *lbm_def)
{
// Precondition, in query mode the map isn't used anymore
FATAL_ERROR_IF(m_query_mode,
"attempted to modify LBMManager in query mode");
if (!string_allowed(lbm_def->name, LBM_NAME_ALLOWED_CHARS)) {
throw ModError("Error adding LBM \"" + lbm_def->name +
"\": Does not follow naming conventions: "
"Only characters [a-z0-9_:] are allowed.");
}
m_lbm_defs[lbm_def->name] = lbm_def;
}
void LBMManager::loadIntroductionTimes(const std::string ×,
IGameDef *gamedef, u32 now)
{
m_query_mode = true;
// name -> time map.
// Storing it in a map first instead of
// handling the stuff directly in the loop
// removes all duplicate entries.
// TODO make this std::unordered_map
std::map<std::string, u32> introduction_times;
/*
The introduction times string consists of name~time entries,
with each entry terminated by a semicolon. The time is decimal.
*/
size_t idx = 0;
size_t idx_new;
while ((idx_new = times.find(';', idx)) != std::string::npos) {
std::string entry = times.substr(idx, idx_new - idx);
std::vector<std::string> components = str_split(entry, '~');
if (components.size() != 2)
throw SerializationError("Introduction times entry \""
+ entry + "\" requires exactly one '~'!");
const std::string &name = components[0];
u32 time = from_string<u32>(components[1]);
introduction_times[name] = time;
idx = idx_new + 1;
}
// Put stuff from introduction_times into m_lbm_lookup
for (std::map<std::string, u32>::const_iterator it = introduction_times.begin();
it != introduction_times.end(); ++it) {
const std::string &name = it->first;
u32 time = it->second;
std::map<std::string, LoadingBlockModifierDef *>::iterator def_it =
m_lbm_defs.find(name);
if (def_it == m_lbm_defs.end()) {
// This seems to be an LBM entry for
// an LBM we haven't loaded. Discard it.
continue;
}
LoadingBlockModifierDef *lbm_def = def_it->second;
if (lbm_def->run_at_every_load) {
// This seems to be an LBM entry for
// an LBM that runs at every load.
// Don't add it just yet.
continue;
}
m_lbm_lookup[time].addLBM(lbm_def, gamedef);
// Erase the entry so that we know later
// what elements didn't get put into m_lbm_lookup
m_lbm_defs.erase(name);
}
// Now also add the elements from m_lbm_defs to m_lbm_lookup
// that weren't added in the previous step.
// They are introduced first time to this world,
// or are run at every load (introducement time hardcoded to U32_MAX).
LBMContentMapping &lbms_we_introduce_now = m_lbm_lookup[now];
LBMContentMapping &lbms_running_always = m_lbm_lookup[U32_MAX];
for (auto &m_lbm_def : m_lbm_defs) {
if (m_lbm_def.second->run_at_every_load) {
lbms_running_always.addLBM(m_lbm_def.second, gamedef);
} else {
lbms_we_introduce_now.addLBM(m_lbm_def.second, gamedef);
}
}
// Clear the list, so that we don't delete remaining elements
// twice in the destructor
m_lbm_defs.clear();
}
std::string LBMManager::createIntroductionTimesString()
{
// Precondition, we must be in query mode
FATAL_ERROR_IF(!m_query_mode,
"attempted to query on non fully set up LBMManager");
std::ostringstream oss;
for (const auto &it : m_lbm_lookup) {
u32 time = it.first;
const std::vector<LoadingBlockModifierDef *> &lbm_list = it.second.lbm_list;
for (const auto &lbm_def : lbm_list) {
// Don't add if the LBM runs at every load,
// then introducement time is hardcoded
// and doesn't need to be stored
if (lbm_def->run_at_every_load)
continue;
oss << lbm_def->name << "~" << time << ";";
}
}
return oss.str();
}
void LBMManager::applyLBMs(ServerEnvironment *env, MapBlock *block,
const u32 stamp, const float dtime_s)
{
// Precondition, we need m_lbm_lookup to be initialized
FATAL_ERROR_IF(!m_query_mode,
"attempted to query on non fully set up LBMManager");
v3s16 pos_of_block = block->getPosRelative();
v3s16 pos;
MapNode n;
content_t c;
auto it = getLBMsIntroducedAfter(stamp);
for (; it != m_lbm_lookup.end(); ++it) {
// Cache previous version to speedup lookup which has a very high performance
// penalty on each call
content_t previous_c = CONTENT_IGNORE;
const std::vector<LoadingBlockModifierDef *> *lbm_list = nullptr;
for (pos.X = 0; pos.X < MAP_BLOCKSIZE; pos.X++)
for (pos.Y = 0; pos.Y < MAP_BLOCKSIZE; pos.Y++)
for (pos.Z = 0; pos.Z < MAP_BLOCKSIZE; pos.Z++) {
n = block->getNodeNoCheck(pos);
c = n.getContent();
// If content_t are not matching perform an LBM lookup
if (previous_c != c) {
lbm_list = it->second.lookup(c);
previous_c = c;
}
if (!lbm_list)
continue;
for (auto lbmdef : *lbm_list) {
lbmdef->trigger(env, pos + pos_of_block, n, dtime_s);
if (block->isOrphan())
return;
n = block->getNodeNoCheck(pos);
if (n.getContent() != c)
break; // The node was changed and the LBMs no longer apply
}
}
}
}
/*
ActiveBlockList
*/
void fillRadiusBlock(v3s16 p0, s16 r, std::set<v3s16> &list)
{
v3s16 p;
for(p.X=p0.X-r; p.X<=p0.X+r; p.X++)
for(p.Y=p0.Y-r; p.Y<=p0.Y+r; p.Y++)
for(p.Z=p0.Z-r; p.Z<=p0.Z+r; p.Z++)
{
// limit to a sphere
if (p.getDistanceFrom(p0) <= r) {
// Set in list
list.insert(p);
}
}
}
void fillViewConeBlock(v3s16 p0,
const s16 r,
const v3f camera_pos,
const v3f camera_dir,
const float camera_fov,
std::set<v3s16> &list)
{
v3s16 p;
const s16 r_nodes = r * BS * MAP_BLOCKSIZE;
for (p.X = p0.X - r; p.X <= p0.X+r; p.X++)
for (p.Y = p0.Y - r; p.Y <= p0.Y+r; p.Y++)
for (p.Z = p0.Z - r; p.Z <= p0.Z+r; p.Z++) {
if (isBlockInSight(p, camera_pos, camera_dir, camera_fov, r_nodes)) {
list.insert(p);
}
}
}
void ActiveBlockList::update(std::vector<PlayerSAO*> &active_players,
s16 active_block_range,
s16 active_object_range,
std::set<v3s16> &blocks_removed,
std::set<v3s16> &blocks_added)
{
/*
Create the new list
*/
std::set<v3s16> newlist = m_forceloaded_list;
m_abm_list = m_forceloaded_list;
for (const PlayerSAO *playersao : active_players) {
v3s16 pos = getNodeBlockPos(floatToInt(playersao->getBasePosition(), BS));
fillRadiusBlock(pos, active_block_range, m_abm_list);
fillRadiusBlock(pos, active_block_range, newlist);
s16 player_ao_range = std::min(active_object_range, playersao->getWantedRange());
// only do this if this would add blocks
if (player_ao_range > active_block_range) {
v3f camera_dir = v3f(0,0,1);
camera_dir.rotateYZBy(playersao->getLookPitch());
camera_dir.rotateXZBy(playersao->getRotation().Y);
if (playersao->getCameraInverted())
camera_dir = -camera_dir;
fillViewConeBlock(pos,
player_ao_range,
playersao->getEyePosition(),
camera_dir,
playersao->getFov(),
newlist);
}
}
/*
Find out which blocks on the old list are not on the new list
*/
// Go through old list
for (v3s16 p : m_list) {
// If not on new list, it's been removed
if (newlist.find(p) == newlist.end())
blocks_removed.insert(p);
}
/*
Find out which blocks on the new list are not on the old list
*/
// Go through new list
for (v3s16 p : newlist) {
// If not on old list, it's been added
if (m_list.find(p) == m_list.end())
blocks_added.insert(p);
}
/*
Update m_list
*/
m_list = std::move(newlist);
}
/*
OnMapblocksChangedReceiver
*/
void OnMapblocksChangedReceiver::onMapEditEvent(const MapEditEvent &event)
{
assert(receiving);
for (const v3s16 &p : event.modified_blocks) {
modified_blocks.insert(p);
}
}
/*
ServerEnvironment
*/
// Random device to seed pseudo random generators.
static std::random_device seed;
ServerEnvironment::ServerEnvironment(ServerMap *map,
ServerScripting *script_iface, Server *server,
const std::string &path_world, MetricsBackend *mb):
Environment(server),
m_map(map),
m_script(script_iface),
m_server(server),
m_path_world(path_world),
m_rgen(seed())
{
m_step_time_counter = mb->addCounter(
"minetest_env_step_time", "Time spent in environment step (in microseconds)");
m_active_block_gauge = mb->addGauge(
"minetest_env_active_blocks", "Number of active blocks");
m_active_object_gauge = mb->addGauge(
"minetest_env_active_objects", "Number of active objects");
}
void ServerEnvironment::init()
{
// Determine which database backend to use
std::string conf_path = m_path_world + DIR_DELIM + "world.mt";
Settings conf;
std::string player_backend_name = "sqlite3";
std::string auth_backend_name = "sqlite3";
bool succeeded = conf.readConfigFile(conf_path.c_str());
// If we open world.mt read the backend configurations.
if (succeeded) {
// Check that the world's blocksize matches the compiled MAP_BLOCKSIZE
u16 blocksize = 16;
conf.getU16NoEx("blocksize", blocksize);
if (blocksize != MAP_BLOCKSIZE) {
throw BaseException(std::string("The map's blocksize is not supported."));
}
// Read those values before setting defaults
bool player_backend_exists = conf.exists("player_backend");
bool auth_backend_exists = conf.exists("auth_backend");
// player backend is not set, assume it's legacy file backend.
if (!player_backend_exists) {
// fall back to files
conf.set("player_backend", "files");
player_backend_name = "files";
if (!conf.updateConfigFile(conf_path.c_str())) {
errorstream << "ServerEnvironment::ServerEnvironment(): "
<< "Failed to update world.mt!" << std::endl;
}
} else {
conf.getNoEx("player_backend", player_backend_name);
}
// auth backend is not set, assume it's legacy file backend.
if (!auth_backend_exists) {
conf.set("auth_backend", "files");
auth_backend_name = "files";
if (!conf.updateConfigFile(conf_path.c_str())) {
errorstream << "ServerEnvironment::ServerEnvironment(): "
<< "Failed to update world.mt!" << std::endl;
}
} else {
conf.getNoEx("auth_backend", auth_backend_name);
}
}
if (player_backend_name == "files") {
warningstream << "/!\\ You are using old player file backend. "
<< "This backend is deprecated and will be removed in a future release /!\\"
<< std::endl << "Switching to SQLite3 or PostgreSQL is advised, "
<< "please read http://wiki.minetest.net/Database_backends." << std::endl;
}
if (auth_backend_name == "files") {
warningstream << "/!\\ You are using old auth file backend. "
<< "This backend is deprecated and will be removed in a future release /!\\"
<< std::endl << "Switching to SQLite3 is advised, "
<< "please read http://wiki.minetest.net/Database_backends." << std::endl;
}
m_player_database = openPlayerDatabase(player_backend_name, m_path_world, conf);
m_auth_database = openAuthDatabase(auth_backend_name, m_path_world, conf);
if (m_map && m_script->has_on_mapblocks_changed()) {
m_map->addEventReceiver(&m_on_mapblocks_changed_receiver);
m_on_mapblocks_changed_receiver.receiving = true;
}
}
ServerEnvironment::~ServerEnvironment()
{
// Clear active block list.
// This makes the next one delete all active objects.
m_active_blocks.clear();
try {
// Convert all objects to static and delete the active objects
deactivateFarObjects(true);
} catch (ModError &e) {
m_server->addShutdownError(e);
}
// Drop/delete map
if (m_map)
m_map->drop();
// Delete ActiveBlockModifiers
for (ABMWithState &m_abm : m_abms) {
delete m_abm.abm;
}
// Deallocate players
for (RemotePlayer *m_player : m_players) {
delete m_player;
}
delete m_player_database;
delete m_auth_database;
}
Map & ServerEnvironment::getMap()
{
return *m_map;
}
ServerMap & ServerEnvironment::getServerMap()
{
return *m_map;
}
RemotePlayer *ServerEnvironment::getPlayer(const session_t peer_id)
{
for (RemotePlayer *player : m_players) {
if (player->getPeerId() == peer_id)
return player;
}
return NULL;
}
RemotePlayer *ServerEnvironment::getPlayer(const char* name)
{
for (RemotePlayer *player : m_players) {
if (strcmp(player->getName(), name) == 0)
return player;
}
return NULL;
}
void ServerEnvironment::addPlayer(RemotePlayer *player)
{
/*
Check that peer_ids are unique.
Also check that names are unique.
Exception: there can be multiple players with peer_id=0
*/
// If peer id is non-zero, it has to be unique.
if (player->getPeerId() != PEER_ID_INEXISTENT)
FATAL_ERROR_IF(getPlayer(player->getPeerId()) != NULL, "Peer id not unique");
// Name has to be unique.
FATAL_ERROR_IF(getPlayer(player->getName()) != NULL, "Player name not unique");
// Add.
m_players.push_back(player);
}
void ServerEnvironment::removePlayer(RemotePlayer *player)
{
for (std::vector<RemotePlayer *>::iterator it = m_players.begin();
it != m_players.end(); ++it) {
if ((*it) == player) {
delete *it;
m_players.erase(it);
return;
}
}
}
bool ServerEnvironment::removePlayerFromDatabase(const std::string &name)
{
return m_player_database->removePlayer(name);
}
void ServerEnvironment::kickAllPlayers(AccessDeniedCode reason,
const std::string &str_reason, bool reconnect)
{
for (RemotePlayer *player : m_players)
m_server->DenyAccess(player->getPeerId(), reason, str_reason, reconnect);
}
void ServerEnvironment::saveLoadedPlayers(bool force)
{
for (RemotePlayer *player : m_players) {
if (force || player->checkModified() || (player->getPlayerSAO() &&
player->getPlayerSAO()->getMeta().isModified())) {
try {
m_player_database->savePlayer(player);
} catch (DatabaseException &e) {
errorstream << "Failed to save player " << player->getName() << " exception: "
<< e.what() << std::endl;
throw;
}
}
}
}
void ServerEnvironment::savePlayer(RemotePlayer *player)
{
try {
m_player_database->savePlayer(player);
} catch (DatabaseException &e) {
errorstream << "Failed to save player " << player->getName() << " exception: "
<< e.what() << std::endl;
throw;
}
}
PlayerSAO *ServerEnvironment::loadPlayer(RemotePlayer *player, bool *new_player,
session_t peer_id, bool is_singleplayer)
{
auto playersao = std::make_unique<PlayerSAO>(this, player, peer_id, is_singleplayer);
// Create player if it doesn't exist
if (!m_player_database->loadPlayer(player, playersao.get())) {
*new_player = true;
// Set player position
infostream << "Server: Finding spawn place for player \""
<< player->getName() << "\"" << std::endl;
playersao->setBasePosition(m_server->findSpawnPos());
// Make sure the player is saved
player->setModified(true);
} else {
// If the player exists, ensure that they respawn inside legal bounds
// This fixes an assert crash when the player can't be added
// to the environment
if (objectpos_over_limit(playersao->getBasePosition())) {
actionstream << "Respawn position for player \""
<< player->getName() << "\" outside limits, resetting" << std::endl;
playersao->setBasePosition(m_server->findSpawnPos());
}
}
// Add player to environment
addPlayer(player);
/* Clean up old HUD elements from previous sessions */
player->clearHud();
/* Add object to environment */
PlayerSAO *ret = playersao.get();
addActiveObject(std::move(playersao));
// Update active blocks quickly for a bit so objects in those blocks appear on the client
m_fast_active_block_divider = 10;
return ret;
}
void ServerEnvironment::saveMeta()
{
if (!m_meta_loaded)
return;
std::string path = m_path_world + DIR_DELIM "env_meta.txt";
// Open file and serialize
std::ostringstream ss(std::ios_base::binary);
Settings args("EnvArgsEnd");
args.setU64("game_time", m_game_time);
args.setU64("time_of_day", getTimeOfDay());
args.setU64("last_clear_objects_time", m_last_clear_objects_time);
args.setU64("lbm_introduction_times_version", 1);
args.set("lbm_introduction_times",
m_lbm_mgr.createIntroductionTimesString());
args.setU64("day_count", m_day_count);
args.writeLines(ss);
if(!fs::safeWriteToFile(path, ss.str()))
{
infostream<<"ServerEnvironment::saveMeta(): Failed to write "
<<path<<std::endl;
throw SerializationError("Couldn't save env meta");
}
}
void ServerEnvironment::loadMeta()
{
SANITY_CHECK(!m_meta_loaded);
m_meta_loaded = true;
// If file doesn't exist, load default environment metadata
if (!fs::PathExists(m_path_world + DIR_DELIM "env_meta.txt")) {
infostream << "ServerEnvironment: Loading default environment metadata"
<< std::endl;
loadDefaultMeta();
return;
}
infostream << "ServerEnvironment: Loading environment metadata" << std::endl;
std::string path = m_path_world + DIR_DELIM "env_meta.txt";
// Open file and deserialize
std::ifstream is(path.c_str(), std::ios_base::binary);
if (!is.good()) {
infostream << "ServerEnvironment::loadMeta(): Failed to open "
<< path << std::endl;
throw SerializationError("Couldn't load env meta");
}
Settings args("EnvArgsEnd");
if (!args.parseConfigLines(is)) {
throw SerializationError("ServerEnvironment::loadMeta(): "
"EnvArgsEnd not found!");
}
try {
m_game_time = args.getU64("game_time");
} catch (SettingNotFoundException &e) {
// Getting this is crucial, otherwise timestamps are useless
throw SerializationError("Couldn't load env meta game_time");
}
setTimeOfDay(args.exists("time_of_day") ?
// set day to early morning by default
args.getU64("time_of_day") : 5250);
m_last_clear_objects_time = args.exists("last_clear_objects_time") ?
// If missing, do as if clearObjects was never called
args.getU64("last_clear_objects_time") : 0;
std::string lbm_introduction_times;
try {
u64 ver = args.getU64("lbm_introduction_times_version");
if (ver == 1) {
lbm_introduction_times = args.get("lbm_introduction_times");
} else {
infostream << "ServerEnvironment::loadMeta(): Non-supported"
<< " introduction time version " << ver << std::endl;
}
} catch (SettingNotFoundException &e) {
// No problem, this is expected. Just continue with an empty string
}
m_lbm_mgr.loadIntroductionTimes(lbm_introduction_times, m_server, m_game_time);
m_day_count = args.exists("day_count") ?
args.getU64("day_count") : 0;
}
/**
* called if env_meta.txt doesn't exist (e.g. new world)
*/
void ServerEnvironment::loadDefaultMeta()
{
m_lbm_mgr.loadIntroductionTimes("", m_server, m_game_time);
}
struct ActiveABM
{
ActiveBlockModifier *abm;
int chance;
std::vector<content_t> required_neighbors;
bool check_required_neighbors; // false if required_neighbors is known to be empty
s16 min_y;
s16 max_y;
};
class ABMHandler
{
private:
ServerEnvironment *m_env;
std::vector<std::vector<ActiveABM> *> m_aabms;
public:
ABMHandler(std::vector<ABMWithState> &abms,
float dtime_s, ServerEnvironment *env,
bool use_timers):
m_env(env)
{
if(dtime_s < 0.001)
return;
const NodeDefManager *ndef = env->getGameDef()->ndef();
for (ABMWithState &abmws : abms) {
ActiveBlockModifier *abm = abmws.abm;
float trigger_interval = abm->getTriggerInterval();
if(trigger_interval < 0.001)
trigger_interval = 0.001;
float actual_interval = dtime_s;
if(use_timers){
abmws.timer += dtime_s;
if(abmws.timer < trigger_interval)
continue;
abmws.timer -= trigger_interval;
actual_interval = trigger_interval;
}
float chance = abm->getTriggerChance();
if (chance == 0)
chance = 1;
ActiveABM aabm;
aabm.abm = abm;
if (abm->getSimpleCatchUp()) {
float intervals = actual_interval / trigger_interval;
if (intervals == 0)
continue;
aabm.chance = chance / intervals;
if (aabm.chance == 0)
aabm.chance = 1;
} else {
aabm.chance = chance;
}
// y limits
aabm.min_y = abm->getMinY();
aabm.max_y = abm->getMaxY();
// Trigger neighbors
const std::vector<std::string> &required_neighbors_s =
abm->getRequiredNeighbors();
for (const std::string &required_neighbor_s : required_neighbors_s) {
ndef->getIds(required_neighbor_s, aabm.required_neighbors);
}
aabm.check_required_neighbors = !required_neighbors_s.empty();
// Trigger contents
const std::vector<std::string> &contents_s = abm->getTriggerContents();
for (const std::string &content_s : contents_s) {
std::vector<content_t> ids;
ndef->getIds(content_s, ids);
for (content_t c : ids) {
if (c >= m_aabms.size())
m_aabms.resize(c + 256, NULL);
if (!m_aabms[c])
m_aabms[c] = new std::vector<ActiveABM>;
m_aabms[c]->push_back(aabm);
}
}
}
}
~ABMHandler()
{
for (auto &aabms : m_aabms)
delete aabms;
}
// Find out how many objects the given block and its neighbors contain.
// Returns the number of objects in the block, and also in 'wider' the
// number of objects in the block and all its neighbors. The latter
// may an estimate if any neighbors are unloaded.
u32 countObjects(MapBlock *block, ServerMap * map, u32 &wider)
{
wider = 0;
u32 wider_unknown_count = 0;
for(s16 x=-1; x<=1; x++)
for(s16 y=-1; y<=1; y++)
for(s16 z=-1; z<=1; z++)
{
MapBlock *block2 = map->getBlockNoCreateNoEx(
block->getPos() + v3s16(x,y,z));
if(block2==NULL){
wider_unknown_count++;
continue;
}
wider += block2->m_static_objects.size();
}
// Extrapolate
u32 active_object_count = block->m_static_objects.getActiveSize();
u32 wider_known_count = 3 * 3 * 3 - wider_unknown_count;
wider += wider_unknown_count * wider / wider_known_count;
return active_object_count;
}
void apply(MapBlock *block, int &blocks_scanned, int &abms_run, int &blocks_cached)
{
if (m_aabms.empty())
return;
// Check the content type cache first
// to see whether there are any ABMs
// to be run at all for this block.
if (block->contents_cached) {
blocks_cached++;
bool run_abms = false;
for (content_t c : block->contents) {
if (c < m_aabms.size() && m_aabms[c]) {
run_abms = true;
break;
}
}
if (!run_abms)
return;
} else {
// Clear any caching
block->contents.clear();
}
blocks_scanned++;
ServerMap *map = &m_env->getServerMap();
u32 active_object_count_wider;
u32 active_object_count = this->countObjects(block, map, active_object_count_wider);
m_env->m_added_objects = 0;
v3s16 p0;
for(p0.X=0; p0.X<MAP_BLOCKSIZE; p0.X++)
for(p0.Y=0; p0.Y<MAP_BLOCKSIZE; p0.Y++)
for(p0.Z=0; p0.Z<MAP_BLOCKSIZE; p0.Z++)
{
MapNode n = block->getNodeNoCheck(p0);
content_t c = n.getContent();
// Cache content types as we go
if (!block->contents_cached && !block->do_not_cache_contents) {
block->contents.insert(c);
if (block->contents.size() > 64) {
// Too many different nodes... don't try to cache
block->do_not_cache_contents = true;
block->contents.clear();
}
}
if (c >= m_aabms.size() || !m_aabms[c])
continue;
v3s16 p = p0 + block->getPosRelative();
for (ActiveABM &aabm : *m_aabms[c]) {
if ((p.Y < aabm.min_y) || (p.Y > aabm.max_y))
continue;
if (myrand() % aabm.chance != 0)
continue;
// Check neighbors
if (aabm.check_required_neighbors) {
v3s16 p1;
for(p1.X = p0.X-1; p1.X <= p0.X+1; p1.X++)
for(p1.Y = p0.Y-1; p1.Y <= p0.Y+1; p1.Y++)
for(p1.Z = p0.Z-1; p1.Z <= p0.Z+1; p1.Z++)
{
if(p1 == p0)
continue;
content_t c;
if (block->isValidPosition(p1)) {
// if the neighbor is found on the same map block
// get it straight from there
const MapNode &n = block->getNodeNoCheck(p1);
c = n.getContent();
} else {
// otherwise consult the map
MapNode n = map->getNode(p1 + block->getPosRelative());
c = n.getContent();
}
if (CONTAINS(aabm.required_neighbors, c))
goto neighbor_found;
}
// No required neighbor found
continue;
}
neighbor_found:
abms_run++;
// Call all the trigger variations
aabm.abm->trigger(m_env, p, n);
aabm.abm->trigger(m_env, p, n,
active_object_count, active_object_count_wider);
if (block->isOrphan())
return;
// Count surrounding objects again if the abms added any
if(m_env->m_added_objects > 0) {
active_object_count = countObjects(block, map, active_object_count_wider);
m_env->m_added_objects = 0;
}
// Update and check node after possible modification
n = block->getNodeNoCheck(p0);
if (n.getContent() != c)
break;
}
}
block->contents_cached = !block->do_not_cache_contents;
}
};
void ServerEnvironment::activateBlock(MapBlock *block, u32 additional_dtime)
{