Add minetest.register_lbm() to run code on block load only

This commit is contained in:
est31 2016-02-09 07:08:31 +01:00
parent 88fbe7ca1e
commit d494733839
12 changed files with 493 additions and 25 deletions

@ -11,10 +11,11 @@ local register_alias_raw = core.register_alias_raw
core.register_alias_raw = nil
--
-- Item / entity / ABM registration functions
-- Item / entity / ABM / LBM registration functions
--
core.registered_abms = {}
core.registered_lbms = {}
core.registered_entities = {}
core.registered_items = {}
core.registered_nodes = {}
@ -79,6 +80,13 @@ function core.register_abm(spec)
spec.mod_origin = core.get_current_modname() or "??"
end
function core.register_lbm(spec)
-- Add to core.registered_lbms
check_modname_prefix(spec.name)
core.registered_lbms[#core.registered_lbms + 1] = spec
spec.mod_origin = core.get_current_modname() or "??"
end
function core.register_entity(name, prototype)
-- Check name
if name == nil then

@ -1793,6 +1793,7 @@ Call these functions only at load time!
* `minetest.register_entity(name, prototype table)`
* `minetest.register_abm(abm definition)`
* `minetest.register_lbm(lbm definition)`
* `minetest.register_node(name, node definition)`
* `minetest.register_tool(name, item definition)`
* `minetest.register_craftitem(name, item definition)`
@ -3305,6 +3306,21 @@ Definition tables
action = func(pos, node, active_object_count, active_object_count_wider),
}
### LBM (LoadingBlockModifier) definition (`register_lbm`)
{
name = "modname:replace_legacy_door",
nodenames = {"default:lava_source"},
-- ^ List of node names to trigger the LBM on.
-- Also non-registered nodes will work.
-- Groups (as of group:groupname) will work as well.
run_at_every_load = false,
-- ^ Whether to run the LBM's action every time a block gets loaded,
-- and not just for blocks that were saved last time before LBMs were
-- introduced to the world.
action = func(pos, node),
}
### Item definition (`register_node`, `register_craftitem`, `register_tool`)
{

@ -48,6 +48,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
#define LBM_NAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyz0123456789_:"
Environment::Environment():
m_time_of_day_speed(0),
m_time_of_day(9000),
@ -270,6 +272,223 @@ ABMWithState::ABMWithState(ActiveBlockModifier *abm_):
timer = myrand_range(minval, maxval);
}
/*
LBMManager
*/
void LBMContentMapping::deleteContents()
{
for (std::vector<LoadingBlockModifierDef *>::iterator it = lbm_list.begin();
it != lbm_list.end(); ++it) {
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.
INodeDefManager *nodedef = gamedef->ndef();
lbm_list.push_back(lbm_def);
for (std::set<std::string>::const_iterator it = lbm_def->trigger_contents.begin();
it != lbm_def->trigger_contents.end(); ++it) {
std::set<content_t> c_ids;
bool found = nodedef->getIds(*it, c_ids);
if (!found) {
content_t c_id = gamedef->allocateUnknownNodeId(*it);
if (c_id == CONTENT_IGNORE) {
// Seems it can't be allocated.
warningstream << "Could not internalize node name \"" << *it
<< "\" while loading LBM \"" << lbm_def->name << "\"." << std::endl;
continue;
}
c_ids.insert(c_id);
}
for (std::set<content_t>::const_iterator iit =
c_ids.begin(); iit != c_ids.end(); ++iit) {
content_t c_id = *iit;
map[c_id].push_back(lbm_def);
}
}
}
const std::vector<LoadingBlockModifierDef *> *
LBMContentMapping::lookup(content_t c) const
{
container_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 (std::map<std::string, LoadingBlockModifierDef *>::iterator it =
m_lbm_defs.begin(); it != m_lbm_defs.end(); ++it) {
delete it->second;
}
for (lbm_lookup_map::iterator it = m_lbm_lookup.begin();
it != m_lbm_lookup.end(); ++it) {
(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 == true,
"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 chararacters [a-z0-9_:] are allowed.");
}
m_lbm_defs[lbm_def->name] = lbm_def;
}
void LBMManager::loadIntroductionTimes(const std::string &times,
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 (std::map<std::string, LoadingBlockModifierDef *>::iterator it =
m_lbm_defs.begin(); it != m_lbm_defs.end(); ++it) {
if (it->second->run_at_every_load) {
lbms_running_always.addLBM(it->second, gamedef);
} else {
lbms_we_introduce_now.addLBM(it->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 == false,
"attempted to query on non fully set up LBMManager");
std::ostringstream oss;
for (lbm_lookup_map::iterator it = m_lbm_lookup.begin();
it != m_lbm_lookup.end(); ++it) {
u32 time = it->first;
std::vector<LoadingBlockModifierDef *> &lbm_list = it->second.lbm_list;
for (std::vector<LoadingBlockModifierDef *>::iterator iit = lbm_list.begin();
iit != lbm_list.end(); ++iit) {
// Don't add if the LBM runs at every load,
// then introducement time is hardcoded
// and doesn't need to be stored
if ((*iit)->run_at_every_load)
continue;
oss << (*iit)->name << "~" << time << ";";
}
}
return oss.str();
}
void LBMManager::applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp)
{
// Precondition, we need m_lbm_lookup to be initialized
FATAL_ERROR_IF(m_query_mode == false,
"attempted to query on non fully set up LBMManager");
v3s16 pos_of_block = block->getPosRelative();
v3s16 pos;
MapNode n;
content_t c;
lbm_lookup_map::const_iterator it = getLBMsIntroducedAfter(stamp);
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->getNodeNoEx(pos);
c = n.getContent();
for (LBMManager::lbm_lookup_map::const_iterator iit = it;
iit != m_lbm_lookup.end(); ++iit) {
const std::vector<LoadingBlockModifierDef *> *lbm_list =
iit->second.lookup(c);
if (!lbm_list)
continue;
for (std::vector<LoadingBlockModifierDef *>::const_iterator iit =
lbm_list->begin(); iit != lbm_list->end(); ++iit) {
(*iit)->trigger(env, pos + pos_of_block, n);
}
}
}
}
/*
ActiveBlockList
*/
@ -505,6 +724,9 @@ void ServerEnvironment::saveMeta()
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.writeLines(ss);
ss<<"EnvArgsEnd\n";
@ -555,6 +777,26 @@ void ServerEnvironment::loadMeta()
// If missing, do as if clearObjects was never called
m_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_gamedef, m_game_time);
}
void ServerEnvironment::loadDefaultMeta()
{
m_lbm_mgr.loadIntroductionTimes("", m_gamedef, m_game_time);
}
struct ActiveABM
@ -770,6 +1012,9 @@ void ServerEnvironment::activateBlock(MapBlock *block, u32 additional_dtime)
// Activate stored objects
activateObjects(block, dtime_s);
/* Handle LoadingBlockModifiers */
m_lbm_mgr.applyLBMs(this, block, stamp);
// Run node timers
std::map<v3s16, NodeTimer> elapsed_timers =
block->m_node_timers.step((float)dtime_s);
@ -795,6 +1040,11 @@ void ServerEnvironment::addActiveBlockModifier(ActiveBlockModifier *abm)
m_abms.push_back(ABMWithState(abm));
}
void ServerEnvironment::addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm)
{
m_lbm_mgr.addLBMDef(lbm);
}
bool ServerEnvironment::setNode(v3s16 p, const MapNode &n)
{
INodeDefManager *ndef = m_gamedef->ndef();

@ -139,7 +139,7 @@ private:
};
/*
Active block modifier interface.
{Active, Loading} block modifier interface.
These are fed into ServerEnvironment at initialization time;
ServerEnvironment handles deleting them.
@ -177,6 +177,77 @@ struct ABMWithState
ABMWithState(ActiveBlockModifier *abm_);
};
struct LoadingBlockModifierDef
{
// Set of contents to trigger on
std::set<std::string> trigger_contents;
std::string name;
bool run_at_every_load;
virtual ~LoadingBlockModifierDef() {}
virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){};
};
struct LBMContentMapping
{
typedef std::map<content_t, std::vector<LoadingBlockModifierDef *> > container_map;
container_map map;
std::vector<LoadingBlockModifierDef *> lbm_list;
// Needs to be separate method (not inside destructor),
// because the LBMContentMapping may be copied and destructed
// many times during operation in the lbm_lookup_map.
void deleteContents();
void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef);
const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const;
};
class LBMManager
{
public:
LBMManager():
m_query_mode(false)
{}
~LBMManager();
// Don't call this after loadIntroductionTimes() ran.
void addLBMDef(LoadingBlockModifierDef *lbm_def);
void loadIntroductionTimes(const std::string &times,
IGameDef *gamedef, u32 now);
// Don't call this before loadIntroductionTimes() ran.
std::string createIntroductionTimesString();
// Don't call this before loadIntroductionTimes() ran.
void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp);
// Warning: do not make this std::unordered_map, order is relevant here
typedef std::map<u32, LBMContentMapping> lbm_lookup_map;
private:
// Once we set this to true, we can only query,
// not modify
bool m_query_mode;
// For m_query_mode == false:
// The key of the map is the LBM def's name.
// TODO make this std::unordered_map
std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs;
// For m_query_mode == true:
// The key of the map is the LBM def's first introduction time.
lbm_lookup_map m_lbm_lookup;
// Returns an iterator to the LBMs that were introduced
// after the given time. This is guaranteed to return
// valid values for everything
lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time)
{ return m_lbm_lookup.lower_bound(time); }
};
/*
List of active blocks, used by ServerEnvironment
*/
@ -254,6 +325,9 @@ public:
*/
void saveMeta();
void loadMeta();
// to be called instead of loadMeta if
// env_meta.txt doesn't exist (e.g. new world)
void loadDefaultMeta();
/*
External ActiveObject interface
@ -312,11 +386,12 @@ public:
void activateBlock(MapBlock *block, u32 additional_dtime=0);
/*
ActiveBlockModifiers
{Active,Loading}BlockModifiers
-------------------------------------------
*/
void addActiveBlockModifier(ActiveBlockModifier *abm);
void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm);
/*
Other stuff
@ -427,6 +502,7 @@ private:
u32 m_last_clear_objects_time;
// Active block modifiers
std::vector<ABMWithState> m_abms;
LBMManager m_lbm_mgr;
// An interval for generally sending object positions and stuff
float m_recommended_send_interval;
// Estimate for general maximum lag as determined by server.

@ -419,7 +419,7 @@ public:
inline virtual const ContentFeatures& get(const MapNode &n) const;
virtual bool getId(const std::string &name, content_t &result) const;
virtual content_t getId(const std::string &name) const;
virtual void getIds(const std::string &name, std::set<content_t> &result) const;
virtual bool getIds(const std::string &name, std::set<content_t> &result) const;
virtual const ContentFeatures& get(const std::string &name) const;
content_t allocateId();
virtual content_t set(const std::string &name, const ContentFeatures &def);
@ -603,22 +603,23 @@ content_t CNodeDefManager::getId(const std::string &name) const
}
void CNodeDefManager::getIds(const std::string &name,
bool CNodeDefManager::getIds(const std::string &name,
std::set<content_t> &result) const
{
//TimeTaker t("getIds", NULL, PRECISION_MICRO);
if (name.substr(0,6) != "group:") {
content_t id = CONTENT_IGNORE;
if(getId(name, id))
bool exists = getId(name, id);
if (exists)
result.insert(id);
return;
return exists;
}
std::string group = name.substr(6);
std::map<std::string, GroupItems>::const_iterator
i = m_group_to_items.find(group);
if (i == m_group_to_items.end())
return;
return true;
const GroupItems &items = i->second;
for (GroupItems::const_iterator j = items.begin();
@ -627,6 +628,7 @@ void CNodeDefManager::getIds(const std::string &name,
result.insert((*j).first);
}
//printf("getIds: %dus\n", t.stop());
return true;
}

@ -303,7 +303,8 @@ public:
virtual bool getId(const std::string &name, content_t &result) const=0;
virtual content_t getId(const std::string &name) const=0;
// Allows "group:name" in addition to regular node names
virtual void getIds(const std::string &name, std::set<content_t> &result)
// returns false if node name not found, true otherwise
virtual bool getIds(const std::string &name, std::set<content_t> &result)
const=0;
virtual const ContentFeatures &get(const std::string &name) const=0;
@ -327,7 +328,7 @@ public:
// If not found, returns CONTENT_IGNORE
virtual content_t getId(const std::string &name) const=0;
// Allows "group:name" in addition to regular node names
virtual void getIds(const std::string &name, std::set<content_t> &result)
virtual bool getIds(const std::string &name, std::set<content_t> &result)
const=0;
// If not found, returns the features of CONTENT_UNKNOWN
virtual const ContentFeatures &get(const std::string &name) const=0;

@ -83,6 +83,7 @@ public:
protected:
friend class LuaABM;
friend class LuaLBM;
friend class InvRef;
friend class ObjectRef;
friend class NodeMetaRef;

@ -86,13 +86,12 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env)
setEnv(env);
/*
Add ActiveBlockModifiers to environment
Add {Loading,Active}BlockModifiers to environment
*/
// Get core.registered_abms
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_abms");
luaL_checktype(L, -1, LUA_TTABLE);
int registered_abms = lua_gettop(L);
if(lua_istable(L, registered_abms)){
@ -154,6 +153,58 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env)
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
throw LuaError("core.registered_abms was not a lua table, as expected.");
}
lua_pop(L, 1);
// Get core.registered_lbms
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_lbms");
int registered_lbms = lua_gettop(L);
if (!lua_istable(L, registered_lbms)) {
lua_pop(L, 1);
throw LuaError("core.registered_lbms was not a lua table, as expected.");
}
lua_pushnil(L);
while (lua_next(L, registered_lbms)) {
// key at index -2 and value at index -1
int id = lua_tonumber(L, -2);
int current_lbm = lua_gettop(L);
std::set<std::string> trigger_contents;
lua_getfield(L, current_lbm, "nodenames");
if (lua_istable(L, -1)) {
int table = lua_gettop(L);
lua_pushnil(L);
while (lua_next(L, table)) {
// key at index -2 and value at index -1
luaL_checktype(L, -1, LUA_TSTRING);
trigger_contents.insert(lua_tostring(L, -1));
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
} else if (lua_isstring(L, -1)) {
trigger_contents.insert(lua_tostring(L, -1));
}
lua_pop(L, 1);
std::string name;
getstringfield(L, current_lbm, "name", name);
bool run_at_every_load = getboolfield_default(L, current_lbm,
"run_at_every_load", false);
LuaLBM *lbm = new LuaLBM(L, id, trigger_contents, name,
run_at_every_load);
env->addLoadingBlockModifierDef(lbm);
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
lua_pop(L, 1);
}

@ -90,6 +90,46 @@ void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
lua_pop(L, 1); // Pop error handler
}
void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n)
{
GameScripting *scriptIface = env->getScriptIface();
scriptIface->realityCheck();
lua_State *L = scriptIface->getStack();
sanity_check(lua_checkstack(L, 20));
StackUnroller stack_unroller(L);
int error_handler = PUSH_ERROR_HANDLER(L);
// Get registered_lbms
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_lbms");
luaL_checktype(L, -1, LUA_TTABLE);
lua_remove(L, -2); // Remove core
// Get registered_lbms[m_id]
lua_pushnumber(L, m_id);
lua_gettable(L, -2);
FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table");
lua_remove(L, -2); // Remove registered_lbms
scriptIface->setOriginFromTable(-1);
// Call action
luaL_checktype(L, -1, LUA_TTABLE);
lua_getfield(L, -1, "action");
luaL_checktype(L, -1, LUA_TFUNCTION);
lua_remove(L, -2); // Remove registered_lbms[m_id]
push_v3s16(L, p);
pushnode(L, n, env->getGameDef()->ndef());
int result = lua_pcall(L, 2, 0, error_handler);
if (result)
scriptIface->scriptError(result, "LuaLBM::trigger");
lua_pop(L, 1); // Pop error handler
}
void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param)
{
ScriptCallbackState *state = (ScriptCallbackState *)param;

@ -220,6 +220,24 @@ public:
u32 active_object_count, u32 active_object_count_wider);
};
class LuaLBM : public LoadingBlockModifierDef
{
private:
int m_id;
public:
LuaLBM(lua_State *L, int id,
const std::set<std::string> &trigger_contents,
const std::string &name,
bool run_at_every_load):
m_id(id)
{
this->run_at_every_load = run_at_every_load;
this->trigger_contents = trigger_contents;
this->name = name;
}
virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n);
};
struct ScriptCallbackState {
GameScripting *script;
int callback_ref;

@ -344,10 +344,11 @@ Server::Server(
servermap->addEventReceiver(this);
// If file exists, load environment metadata
if(fs::PathExists(m_path_world + DIR_DELIM "env_meta.txt"))
{
infostream<<"Server: Loading environment metadata"<<std::endl;
if (fs::PathExists(m_path_world + DIR_DELIM "env_meta.txt")) {
infostream << "Server: Loading environment metadata" << std::endl;
m_env->loadMeta();
} else {
m_env->loadDefaultMeta();
}
// Add some test ActiveBlockModifiers to environment

@ -299,15 +299,6 @@ inline s32 mystoi(const std::string &str, s32 min, s32 max)
}
/// Returns a 64-bit value represented by the string \p str (decimal).
inline s64 stoi64(const std::string &str)
{
std::stringstream tmp(str);
s64 t;
tmp >> t;
return t;
}
// MSVC2010 includes it's own versions of these
//#if !defined(_MSC_VER) || _MSC_VER < 1600
@ -346,9 +337,22 @@ inline float mystof(const std::string &str)
#define stoi mystoi
#define stof mystof
/// Returns a value represented by the string \p val.
template <typename T>
inline T from_string(const std::string &str)
{
std::stringstream tmp(str);
T t;
tmp >> t;
return t;
}
/// Returns a 64-bit signed value represented by the string \p str (decimal).
inline s64 stoi64(const std::string &str) { return from_string<s64>(str); }
// TODO: Replace with C++11 std::to_string.
/// Returns A string representing the value \p val.
/// Returns a string representing the value \p val.
template <typename T>
inline std::string to_string(T val)
{