#include "server.h"
#include "utility.h"
#include <iostream>
+#include <queue>
#include "clientserver.h"
#include "map.h"
#include "jmutexautolock.h"
#include "scriptapi.h"
#include "nodedef.h"
#include "tooldef.h"
+#include "craftdef.h"
+#include "craftitemdef.h"
+#include "mapgen.h"
+#include "content_abm.h"
#define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
/*
Do not generate over-limit
*/
- if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
- || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
- || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
- || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
- || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
- || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE)
+ if(blockpos_over_limit(p))
continue;
//infostream<<"EmergeThread::Thread(): running"<<std::endl;
ServerMap &map = ((ServerMap&)m_server->m_env->getMap());
- //core::map<v3s16, MapBlock*> changed_blocks;
- //core::map<v3s16, MapBlock*> lighting_invalidated_blocks;
-
MapBlock *block = NULL;
bool got_block = true;
core::map<v3s16, MapBlock*> modified_blocks;
-
+
/*
- Fetch block from map or generate a single block
+ Try to fetch block from memory or disk.
+ If not found and asked to generate, initialize generator.
*/
+
+ bool started_generate = false;
+ mapgen::BlockMakeData data;
+
{
JMutexAutoLock envlock(m_server->m_env_mutex);
// Load sector if it isn't loaded
if(map.getSectorNoGenerateNoEx(p2d) == NULL)
- //map.loadSectorFull(p2d);
map.loadSectorMeta(p2d);
-
+
+ // Attempt to load block
block = map.getBlockNoCreateNoEx(p);
if(!block || block->isDummy() || !block->isGenerated())
{
if(enable_mapgen_debug_info)
- infostream<<"EmergeThread: not in memory, loading"<<std::endl;
-
- // Get, load or create sector
- /*ServerMapSector *sector =
- (ServerMapSector*)map.createSector(p2d);*/
-
- // Load/generate block
-
- /*block = map.emergeBlock(p, sector, changed_blocks,
- lighting_invalidated_blocks);*/
+ infostream<<"EmergeThread: not in memory, "
+ <<"attempting to load from disk"<<std::endl;
block = map.loadBlock(p);
-
- if(only_from_disk == false)
- {
- if(block == NULL || block->isGenerated() == false)
- {
- if(enable_mapgen_debug_info)
- infostream<<"EmergeThread: generating"<<std::endl;
- block = map.generateBlock(p, modified_blocks);
- }
- }
-
+ }
+
+ // If could not load and allowed to generate, start generation
+ // inside this same envlock
+ if(only_from_disk == false &&
+ (block == NULL || block->isGenerated() == false)){
if(enable_mapgen_debug_info)
- infostream<<"EmergeThread: ended up with: "
- <<analyze_block(block)<<std::endl;
+ infostream<<"EmergeThread: generating"<<std::endl;
+ started_generate = true;
- if(block == NULL)
- {
- got_block = false;
- }
- else
- {
- /*
- Ignore map edit events, they will not need to be
- sent to anybody because the block hasn't been sent
- to anybody
- */
- MapEditEventIgnorer ign(&m_server->m_ignore_map_edit_events);
-
- // Activate objects and stuff
- m_server->m_env->activateBlock(block, 3600);
- }
- }
- else
- {
- /*if(block->getLightingExpired()){
- lighting_invalidated_blocks[block->getPos()] = block;
- }*/
+ map.initBlockMake(&data, p);
}
-
- // TODO: Some additional checking and lighting updating,
- // see emergeBlock
}
- {//envlock
- JMutexAutoLock envlock(m_server->m_env_mutex);
-
- if(got_block)
+ /*
+ If generator was initialized, generate now when envlock is free.
+ */
+ if(started_generate)
{
- /*
- Collect a list of blocks that have been modified in
- addition to the fetched one.
- */
-
-#if 0
- if(lighting_invalidated_blocks.size() > 0)
{
- /*infostream<<"lighting "<<lighting_invalidated_blocks.size()
- <<" blocks"<<std::endl;*/
+ ScopeProfiler sp(g_profiler, "EmergeThread: mapgen::make_block",
+ SPT_AVG);
+ TimeTaker t("mapgen::make_block()");
+
+ mapgen::make_block(&data);
+
+ if(enable_mapgen_debug_info == false)
+ t.stop(true); // Hide output
+ }
- // 50-100ms for single block generation
- //TimeTaker timer("** EmergeThread updateLighting");
+ {
+ // Lock environment again to access the map
+ JMutexAutoLock envlock(m_server->m_env_mutex);
- // Update lighting without locking the environment mutex,
- // add modified blocks to changed blocks
- map.updateLighting(lighting_invalidated_blocks, modified_blocks);
- }
+ ScopeProfiler sp(g_profiler, "EmergeThread: after "
+ "mapgen::make_block (envlock)", SPT_AVG);
+
+ // Blit data back on map, update lighting, add mobs and
+ // whatever this does
+ map.finishBlockMake(&data, modified_blocks);
+
+ // Get central block
+ block = map.getBlockNoCreateNoEx(p);
+
+ /*
+ Do some post-generate stuff
+ */
- // Add all from changed_blocks to modified_blocks
- for(core::map<v3s16, MapBlock*>::Iterator i = changed_blocks.getIterator();
- i.atEnd() == false; i++)
- {
- MapBlock *block = i.getNode()->getValue();
- modified_blocks.insert(block->getPos(), block);
+ v3s16 minp = block->getPos()*MAP_BLOCKSIZE;
+ v3s16 maxp = minp + v3s16(1,1,1)*(MAP_BLOCKSIZE-1);
+ scriptapi_environment_on_generated(m_server->m_lua,
+ minp, maxp);
+
+ if(enable_mapgen_debug_info)
+ infostream<<"EmergeThread: ended up with: "
+ <<analyze_block(block)<<std::endl;
+
+ /*
+ Ignore map edit events, they will not need to be
+ sent to anybody because the block hasn't been sent
+ to anybody
+ */
+ MapEditEventIgnorer ign(&m_server->m_ignore_map_edit_events);
+
+ // Activate objects and stuff
+ m_server->m_env->activateBlock(block, 0);
}
-#endif
- }
- // If we got no block, there should be no invalidated blocks
- else
- {
- //assert(lighting_invalidated_blocks.size() == 0);
}
- }//envlock
-
+ if(block == NULL)
+ got_block = false;
+
/*
Set sent status of modified blocks on clients
*/
END_DEBUG_EXCEPTION_HANDLER(errorstream)
+ log_deregister_thread();
+
return NULL;
}
//if(server->m_emerge_queue.peerItemCount(peer_id) < 1)
// Allow two blocks in queue per client
//if(server->m_emerge_queue.peerItemCount(peer_id) < 2)
- if(server->m_emerge_queue.peerItemCount(peer_id) < 25)
+ u32 max_emerge = 25;
+ // Make it more responsive when needing to generate stuff
+ if(surely_not_found_on_disk)
+ max_emerge = 5;
+ if(server->m_emerge_queue.peerItemCount(peer_id) < max_emerge)
{
//infostream<<"Adding block to emerge queue"<<std::endl;
return checksum;
}
+/*
+ Mods
+*/
+
struct ModSpec
{
std::string name;
std::string path;
+ std::set<std::string> depends;
+ std::set<std::string> unsatisfied_depends;
- ModSpec(const std::string &name_="", const std::string path_=""):
+ ModSpec(const std::string &name_="", const std::string path_="",
+ const std::set<std::string> &depends_=std::set<std::string>()):
name(name_),
- path(path_)
+ path(path_),
+ depends(depends_),
+ unsatisfied_depends(depends_)
{}
};
+// Get a dependency-sorted list of ModSpecs
static core::list<ModSpec> getMods(core::list<std::string> &modspaths)
{
- core::list<ModSpec> mods;
+ std::queue<ModSpec> mods_satisfied;
+ core::list<ModSpec> mods_unsorted;
+ core::list<ModSpec> mods_sorted;
for(core::list<std::string>::Iterator i = modspaths.begin();
i != modspaths.end(); i++){
std::string modspath = *i;
continue;
std::string modname = dirlist[j].name;
std::string modpath = modspath + DIR_DELIM + modname;
- mods.push_back(ModSpec(modname, modpath));
+ std::set<std::string> depends;
+ std::ifstream is((modpath+DIR_DELIM+"depends.txt").c_str(),
+ std::ios_base::binary);
+ while(is.good()){
+ std::string dep;
+ std::getline(is, dep);
+ dep = trim(dep);
+ if(dep != "")
+ depends.insert(dep);
+ }
+ ModSpec spec(modname, modpath, depends);
+ mods_unsorted.push_back(spec);
+ if(depends.empty())
+ mods_satisfied.push(spec);
+ }
+ }
+ // Sort by depencencies
+ while(!mods_satisfied.empty()){
+ ModSpec mod = mods_satisfied.front();
+ mods_satisfied.pop();
+ mods_sorted.push_back(mod);
+ for(core::list<ModSpec>::Iterator i = mods_unsorted.begin();
+ i != mods_unsorted.end(); i++){
+ ModSpec &mod2 = *i;
+ if(mod2.unsatisfied_depends.empty())
+ continue;
+ mod2.unsatisfied_depends.erase(mod.name);
+ if(!mod2.unsatisfied_depends.empty())
+ continue;
+ mods_satisfied.push(mod2);
+ }
+ }
+ // Check unsatisfied dependencies
+ for(core::list<ModSpec>::Iterator i = mods_unsorted.begin();
+ i != mods_unsorted.end(); i++){
+ ModSpec &mod = *i;
+ if(mod.unsatisfied_depends.empty())
+ continue;
+ errorstream<<"mod \""<<mod.name
+ <<"\" has unsatisfied dependencies:";
+ for(std::set<std::string>::iterator
+ i = mod.unsatisfied_depends.begin();
+ i != mod.unsatisfied_depends.end(); i++){
+ errorstream<<" \""<<(*i)<<"\"";
}
+ errorstream<<". Loading nevertheless."<<std::endl;
+ mods_sorted.push_back(mod);
}
- return mods;
+ return mods_sorted;
}
/*
m_banmanager(mapsavedir+DIR_DELIM+"ipban.txt"),
m_lua(NULL),
m_toolmgr(createToolDefManager()),
- m_nodemgr(createNodeDefManager()),
+ m_nodedef(createNodeDefManager()),
+ m_craftdef(createCraftDefManager()),
+ m_craftitemdef(createCraftItemDefManager()),
m_thread(this),
m_emergethread(this),
m_time_counter(0),
JMutexAutoLock envlock(m_env_mutex);
JMutexAutoLock conlock(m_con_mutex);
- infostream<<"m_nodemgr="<<m_nodemgr<<std::endl;
-
- // Initialize default node definitions
- content_mapnode_init(m_nodemgr);
+ infostream<<"m_nodedef="<<m_nodedef<<std::endl;
+ // Path to builtin.lua
+ std::string builtinpath = porting::path_data + DIR_DELIM + "builtin.lua";
// Add default global mod path
m_modspaths.push_back(porting::path_data + DIR_DELIM + "mods");
assert(m_lua);
// Export API
scriptapi_export(m_lua, this);
- // Load and run scripts
+ // Load and run builtin.lua
+ infostream<<"Server: Loading builtin Lua stuff from \""<<builtinpath
+ <<"\""<<std::endl;
+ bool success = script_load(m_lua, builtinpath.c_str());
+ if(!success){
+ errorstream<<"Server: Failed to load and run "
+ <<builtinpath<<std::endl;
+ assert(0);
+ }
+ // Load and run "mod" scripts
core::list<ModSpec> mods = getMods(m_modspaths);
for(core::list<ModSpec>::Iterator i = mods.begin();
i != mods.end(); i++){
// Initialize Environment
- m_env = new ServerEnvironment(new ServerMap(mapsavedir, this), m_lua, this);
+ m_env = new ServerEnvironment(new ServerMap(mapsavedir, this), m_lua,
+ this, this);
// Give environment reference to scripting api
scriptapi_add_environment(m_lua, m_env);
// Load players
infostream<<"Server: Loading players"<<std::endl;
m_env->deSerializePlayers(m_mapsavedir);
+
+ /*
+ Add some test ActiveBlockModifiers to environment
+ */
+ add_legacy_abms(m_env, m_nodedef);
}
Server::~Server()
delete m_env;
delete m_toolmgr;
- delete m_nodemgr;
+ delete m_nodedef;
+ delete m_craftdef;
+ delete m_craftitemdef;
// Deinitialize scripting
infostream<<"Server: Deinitializing scripting"<<std::endl;
m_env->step(dtime);
}
- const float map_timer_and_unload_dtime = 5.15;
+ const float map_timer_and_unload_dtime = 2.92;
if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime))
{
JMutexAutoLock lock(m_env_mutex);
/*
Do background stuff
*/
-
+
/*
- Transform liquids
+ Handle players
*/
+ {
+ JMutexAutoLock lock(m_env_mutex);
+ JMutexAutoLock lock2(m_con_mutex);
+
+ //float player_max_speed = BS * 4.0; // Normal speed
+ float player_max_speed = BS * 20; // Fast speed
+ float player_max_speed_up = BS * 20;
+
+ player_max_speed *= 2.5; // Tolerance
+ player_max_speed_up *= 2.5;
+
+ for(core::map<u16, RemoteClient*>::Iterator
+ i = m_clients.getIterator();
+ i.atEnd() == false; i++)
+ {
+ RemoteClient *client = i.getNode()->getValue();
+ ServerRemotePlayer *player =
+ static_cast<ServerRemotePlayer*>
+ (m_env->getPlayer(client->peer_id));
+ if(player==NULL)
+ continue;
+
+ /*
+ Check player movements
+
+ NOTE: Actually the server should handle player physics like the
+ client does and compare player's position to what is calculated
+ on our side. This is required when eg. players fly due to an
+ explosion.
+ */
+ player->m_last_good_position_age += dtime;
+ if(player->m_last_good_position_age >= 2.0){
+ float age = player->m_last_good_position_age;
+ v3f diff = (player->getPosition() - player->m_last_good_position);
+ float d_vert = diff.Y;
+ diff.Y = 0;
+ float d_horiz = diff.getLength();
+ /*infostream<<player->getName()<<"'s horizontal speed is "
+ <<(d_horiz/age)<<std::endl;*/
+ if(d_horiz <= age * player_max_speed &&
+ (d_vert < 0 || d_vert < age * player_max_speed_up)){
+ player->m_last_good_position = player->getPosition();
+ } else {
+ actionstream<<"Player "<<player->getName()
+ <<" moved too fast; resetting position"
+ <<std::endl;
+ player->setPosition(player->m_last_good_position);
+ SendMovePlayer(player);
+ }
+ player->m_last_good_position_age = 0;
+ }
+
+ /*
+ Send player inventories and HPs if necessary
+ */
+ if(player->m_inventory_not_sent){
+ UpdateCrafting(player->peer_id);
+ SendInventory(player->peer_id);
+ }
+ if(player->m_hp_not_sent){
+ SendPlayerHP(player);
+ }
+ }
+ }
+
+ /* Transform liquids */
m_liquid_transform_timer += dtime;
if(m_liquid_transform_timer >= 1.00)
{
// Map
JMutexAutoLock lock(m_env_mutex);
- /*// Unload unused data (delete from memory)
- m_env->getMap().unloadUnusedData(
- g_settings->getFloat("server_unload_unused_sectors_timeout"));
- */
- /*u32 deleted_count = m_env->getMap().unloadUnusedData(
- g_settings->getFloat("server_unload_unused_sectors_timeout"));
- */
-
- // Save only changed parts
- m_env->getMap().save(true);
-
- /*if(deleted_count > 0)
- {
- infostream<<"Server: Unloaded "<<deleted_count
- <<" blocks from memory"<<std::endl;
- }*/
+ // Save changed parts of map
+ m_env->getMap().save(MOD_STATE_WRITE_NEEDED);
// Save players
m_env->serializePlayers(m_mapsavedir);
infostream<<"Server: Cannot negotiate "
"serialization version with peer "
<<peer_id<<std::endl;
- SendAccessDenied(m_con, peer_id,
- L"Your client is too old (map format)");
+ SendAccessDenied(m_con, peer_id, std::wstring(
+ L"Your client's version is not supported.\n"
+ L"Server version is ")
+ + narrow_to_wide(VERSION_STRING) + L"."
+ );
return;
}
if(net_proto_version == 0)
{
- SendAccessDenied(m_con, peer_id,
- L"Your client is too old. Please upgrade.");
+ SendAccessDenied(m_con, peer_id, std::wstring(
+ L"Your client's version is not supported.\n"
+ L"Server version is ")
+ + narrow_to_wide(VERSION_STRING) + L"."
+ );
return;
}
- /* Uhh... this should actually be a warning but let's do it like this */
if(g_settings->getBool("strict_protocol_version_checking"))
{
- if(net_proto_version < PROTOCOL_VERSION)
+ if(net_proto_version != PROTOCOL_VERSION)
{
- SendAccessDenied(m_con, peer_id,
- L"Your client is too old. Please upgrade.");
+ SendAccessDenied(m_con, peer_id, std::wstring(
+ L"Your client's version is not supported.\n"
+ L"Server version is ")
+ + narrow_to_wide(VERSION_STRING) + L"."
+ );
return;
}
}
Send some initialization data
*/
- // Send textures
- SendTextures(peer_id);
-
// Send tool definitions
SendToolDef(m_con, peer_id, m_toolmgr);
+ // Send node definitions
+ SendNodeDef(m_con, peer_id, m_nodedef);
+
+ // Send CraftItem definitions
+ SendCraftItemDef(m_con, peer_id, m_craftitemdef);
+
+ // Send textures
+ SendTextures(peer_id);
+
// Send player info to all players
SendPlayerInfos();
}
Player *player = m_env->getPlayer(peer_id);
+ ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
if(player == NULL){
infostream<<"Server::ProcessData(): Cancelling: "
}
else if(command == TOSERVER_CLICK_ACTIVEOBJECT)
{
- if(datasize < 7)
- return;
+ infostream<<"Server: CLICK_ACTIVEOBJECT not supported anymore"<<std::endl;
+ return;
+ }
+ else if(command == TOSERVER_GROUND_ACTION)
+ {
+ infostream<<"Server: GROUND_ACTION not supported anymore"<<std::endl;
+ return;
+ }
+ else if(command == TOSERVER_RELEASE)
+ {
+ infostream<<"Server: RELEASE not supported anymore"<<std::endl;
+ return;
+ }
+ else if(command == TOSERVER_SIGNTEXT)
+ {
+ infostream<<"Server: SIGNTEXT not supported anymore"
+ <<std::endl;
+ return;
+ }
+ else if(command == TOSERVER_SIGNNODETEXT)
+ {
if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
return;
-
/*
- length: 7
- [0] u16 command
- [2] u8 button (0=left, 1=right)
- [3] u16 id
- [5] u16 item
+ u16 command
+ v3s16 p
+ u16 textlen
+ textdata
*/
- u8 button = readU8(&data[2]);
- u16 id = readS16(&data[3]);
- u16 item_i = readU16(&data[5]);
-
- ServerActiveObject *obj = m_env->getActiveObject(id);
-
- if(obj == NULL)
+ std::string datastring((char*)&data[2], datasize-2);
+ std::istringstream is(datastring, std::ios_base::binary);
+ u8 buf[6];
+ // Read stuff
+ is.read((char*)buf, 6);
+ v3s16 p = readV3S16(buf);
+ is.read((char*)buf, 2);
+ u16 textlen = readU16(buf);
+ std::string text;
+ for(u16 i=0; i<textlen; i++)
{
- infostream<<"Server: CLICK_ACTIVEOBJECT: object not found"
- <<std::endl;
- return;
+ is.read((char*)buf, 1);
+ text += (char)buf[0];
}
- // Skip if object has been removed
- if(obj->m_removed)
+ NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
+ if(!meta)
return;
-
- //TODO: Check that object is reasonably close
-
- // Get ServerRemotePlayer
- ServerRemotePlayer *srp = (ServerRemotePlayer*)player;
- // Update wielded item
- srp->wieldItem(item_i);
+ meta->setText(text);
- // Left click, pick/punch
- if(button == 0)
+ actionstream<<player->getName()<<" writes \""<<text<<"\" to sign"
+ <<" at "<<PP(p)<<std::endl;
+
+ v3s16 blockpos = getNodeBlockPos(p);
+ MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
+ if(block)
{
- actionstream<<player->getName()<<" punches object "
- <<obj->getId()<<std::endl;
-
- // Do stuff
- obj->punch(srp);
-
-#if 0
+ block->raiseModified(MOD_STATE_WRITE_NEEDED,
+ "sign node text");
+ }
+
+ setBlockNotSent(blockpos);
+ }
+ else if(command == TOSERVER_INVENTORY_ACTION)
+ {
+ /*// Ignore inventory changes if in creative mode
+ if(g_settings->getBool("creative_mode") == true)
+ {
+ infostream<<"TOSERVER_INVENTORY_ACTION: ignoring in creative mode"
+ <<std::endl;
+ return;
+ }*/
+ // Strip command and create a stream
+ std::string datastring((char*)&data[2], datasize-2);
+ infostream<<"TOSERVER_INVENTORY_ACTION: data="<<datastring<<std::endl;
+ std::istringstream is(datastring, std::ios_base::binary);
+ // Create an action
+ InventoryAction *a = InventoryAction::deSerialize(is);
+ if(a == NULL)
+ {
+ infostream<<"TOSERVER_INVENTORY_ACTION: "
+ <<"InventoryAction::deSerialize() returned NULL"
+ <<std::endl;
+ return;
+ }
+ // Create context
+ InventoryContext c;
+ c.current_player = player;
+
+ /*
+ Handle restrictions and special cases of the move action
+ */
+ if(a->getType() == IACTION_MOVE
+ && g_settings->getBool("creative_mode") == false)
+ {
+ InventoryList *rlist = player->inventory.getList("craftresult");
+ assert(rlist);
+ InventoryList *clist = player->inventory.getList("craft");
+ assert(clist);
+ InventoryList *mlist = player->inventory.getList("main");
+ assert(mlist);
+
+ IMoveAction *ma = (IMoveAction*)a;
+
/*
- Try creating inventory item
+ Disable moving items into craftresult from elsewhere
*/
- InventoryItem *item = obj->createPickedUpItem();
-
- if(item)
+ if(ma->to_inv == "current_player"
+ && ma->to_list == "craftresult"
+ && (ma->from_inv != "current_player"
+ || ma->from_list != "craftresult"))
{
- InventoryList *ilist = player->inventory.getList("main");
- if(ilist != NULL)
- {
- actionstream<<player->getName()<<" picked up "
- <<item->getName()<<std::endl;
- if(g_settings->getBool("creative_mode") == false)
- {
- // Skip if inventory has no free space
- if(ilist->roomForItem(item) == false)
- {
- infostream<<"Player inventory has no free space"<<std::endl;
- return;
- }
-
- // Add to inventory and send inventory
- ilist->addItem(item);
- UpdateCrafting(player->peer_id);
- SendInventory(player->peer_id);
- }
-
- // Remove object from environment
- obj->m_removed = true;
- }
+ infostream<<"Ignoring IMoveAction from "
+ <<ma->from_inv<<":"<<ma->from_list
+ <<" to "<<ma->to_inv<<":"<<ma->to_list
+ <<" because dst is craftresult"
+ <<" and src isn't craftresult"<<std::endl;
+ delete a;
+ return;
}
- else
+
+ /*
+ Handle crafting (source is craftresult, which is preview)
+ */
+ if(ma->from_inv == "current_player"
+ && ma->from_list == "craftresult"
+ && player->craftresult_is_preview)
{
/*
- Item cannot be picked up. Punch it instead.
+ If the craftresult is placed on itself, crafting takes
+ place and result is moved into main list
*/
+ if(ma->to_inv == "current_player"
+ && ma->to_list == "craftresult")
+ {
+ // Except if main list doesn't have free slots
+ if(mlist->getFreeSlots() == 0){
+ infostream<<"Cannot craft: Main list doesn't have"
+ <<" free slots"<<std::endl;
+ delete a;
+ return;
+ }
+
+ player->craftresult_is_preview = false;
+ clist->decrementMaterials(1);
- actionstream<<player->getName()<<" punches object "
- <<obj->getId()<<std::endl;
+ InventoryItem *item1 = rlist->changeItem(0, NULL);
+ mlist->addItem(item1);
- ToolItem *titem = NULL;
- std::string toolname = "";
+ srp->m_inventory_not_sent = true;
- InventoryList *mlist = player->inventory.getList("main");
- if(mlist != NULL)
- {
- InventoryItem *item = mlist->getItem(item_i);
- if(item && (std::string)item->getName() == "ToolItem")
- {
- titem = (ToolItem*)item;
- toolname = titem->getToolName();
- }
+ delete a;
+ return;
}
+ /*
+ Disable action if there are no free slots in
+ destination
+
+ If the item is placed on an item that is not of the
+ same kind, the existing item will be first moved to
+ craftresult and immediately moved to the free slot.
+ */
+ do{
+ Inventory *inv_to = getInventory(&c, ma->to_inv);
+ if(!inv_to) break;
+ InventoryList *list_to = inv_to->getList(ma->to_list);
+ if(!list_to) break;
+ if(list_to->getFreeSlots() == 0){
+ infostream<<"Cannot craft: Destination doesn't have"
+ <<" free slots"<<std::endl;
+ delete a;
+ return;
+ }
+ }while(0); // Allow break
- v3f playerpos = player->getPosition();
- v3f objpos = obj->getBasePosition();
- v3f dir = (objpos - playerpos).normalize();
+ /*
+ Ok, craft normally.
+ */
+ player->craftresult_is_preview = false;
+ clist->decrementMaterials(1);
- u16 wear = obj->punch(toolname, dir, player->getName());
+ /* Print out action */
+ InventoryItem *item = rlist->getItem(0);
+ std::string itemstring = "NULL";
+ if(item)
+ itemstring = item->getItemString();
+ actionstream<<player->getName()<<" crafts "
+ <<itemstring<<std::endl;
+
+ // Do the action
+ a->apply(&c, this, m_env);
- if(titem)
- {
- bool weared_out = titem->addWear(wear);
- if(weared_out)
- mlist->deleteItem(item_i);
- SendInventory(player->peer_id);
- }
+ delete a;
+ return;
}
-#endif
- }
- // Right click, do something with object
- if(button == 1)
- {
- actionstream<<player->getName()<<" right clicks object "
- <<obj->getId()<<std::endl;
-
- // Do stuff
- obj->rightClick(srp);
- }
- /*
- Update player state to client
- */
- SendPlayerHP(player);
- UpdateCrafting(player->peer_id);
- SendInventory(player->peer_id);
- }
- else if(command == TOSERVER_GROUND_ACTION)
- {
- if(datasize < 17)
- return;
- /*
- length: 17
- [0] u16 command
- [2] u8 action
- [3] v3s16 nodepos_undersurface
- [9] v3s16 nodepos_abovesurface
- [15] u16 item
- actions:
- 0: start digging
- 1: place block
- 2: stop digging (all parameters ignored)
- 3: digging completed
- */
- u8 action = readU8(&data[2]);
- v3s16 p_under;
- p_under.X = readS16(&data[3]);
- p_under.Y = readS16(&data[5]);
- p_under.Z = readS16(&data[7]);
- v3s16 p_over;
- p_over.X = readS16(&data[9]);
- p_over.Y = readS16(&data[11]);
- p_over.Z = readS16(&data[13]);
- u16 item_i = readU16(&data[15]);
-
- //TODO: Check that target is reasonably close
-
- /*
- 0: start digging
- */
- if(action == 0)
- {
/*
- NOTE: This can be used in the future to check if
- somebody is cheating, by checking the timing.
+ Non-crafting move
*/
- } // action == 0
-
- /*
- 2: stop digging
- */
- else if(action == 2)
- {
-#if 0
- RemoteClient *client = getClient(peer_id);
- JMutexAutoLock digmutex(client->m_dig_mutex);
- client->m_dig_tool_item = -1;
-#endif
- }
-
- /*
- 3: Digging completed
- */
- else if(action == 3)
- {
- // Mandatory parameter; actually used for nothing
- core::map<v3s16, MapBlock*> modified_blocks;
-
- content_t material = CONTENT_IGNORE;
- u8 mineral = MINERAL_NONE;
-
- bool cannot_remove_node = false;
+
+ // Disallow moving items in elsewhere than player's inventory
+ // if not allowed to build
+ if((getPlayerPrivs(player) & PRIV_BUILD) == 0
+ && (ma->from_inv != "current_player"
+ || ma->to_inv != "current_player"))
+ {
+ infostream<<"Cannot move outside of player's inventory: "
+ <<"No build privilege"<<std::endl;
+ delete a;
+ return;
+ }
- try
+ // If player is not an admin, check for ownership of src
+ if(ma->from_inv != "current_player"
+ && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
{
- MapNode n = m_env->getMap().getNode(p_under);
- // Get mineral
- mineral = n.getMineral(m_nodemgr);
- // Get material at position
- material = n.getContent();
- // If not yet cancelled
- if(cannot_remove_node == false)
+ Strfnd fn(ma->from_inv);
+ std::string id0 = fn.next(":");
+ if(id0 == "nodemeta")
{
- // If it's not diggable, do nothing
- if(m_nodemgr->get(material).diggable == false)
+ v3s16 p;
+ p.X = stoi(fn.next(","));
+ p.Y = stoi(fn.next(","));
+ p.Z = stoi(fn.next(","));
+ NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
+ if(meta->getOwner() != "" &&
+ meta->getOwner() != player->getName())
{
- infostream<<"Server: Not finishing digging: "
- <<"Node not diggable"
+ infostream<<"Cannot move item: "
+ "not owner of metadata"
<<std::endl;
- cannot_remove_node = true;
+ delete a;
+ return;
}
}
- // If not yet cancelled
- if(cannot_remove_node == false)
+ }
+ // If player is not an admin, check for ownership of dst
+ if(ma->to_inv != "current_player"
+ && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
+ {
+ Strfnd fn(ma->to_inv);
+ std::string id0 = fn.next(":");
+ if(id0 == "nodemeta")
{
- // Get node metadata
- NodeMetadata *meta = m_env->getMap().getNodeMetadata(p_under);
- if(meta && meta->nodeRemovalDisabled() == true)
+ v3s16 p;
+ p.X = stoi(fn.next(","));
+ p.Y = stoi(fn.next(","));
+ p.Z = stoi(fn.next(","));
+ NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
+ if(meta->getOwner() != "" &&
+ meta->getOwner() != player->getName())
{
- infostream<<"Server: Not finishing digging: "
- <<"Node metadata disables removal"
+ infostream<<"Cannot move item: "
+ "not owner of metadata"
<<std::endl;
- cannot_remove_node = true;
+ delete a;
+ return;
}
}
}
- catch(InvalidPositionException &e)
- {
- infostream<<"Server: Not finishing digging: Node not found."
- <<" Adding block to emerge queue."
- <<std::endl;
- m_emerge_queue.addBlock(peer_id,
- getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
- cannot_remove_node = true;
- }
-
- // Make sure the player is allowed to do it
+ }
+ /*
+ Handle restrictions and special cases of the drop action
+ */
+ else if(a->getType() == IACTION_DROP)
+ {
+ IDropAction *da = (IDropAction*)a;
+ // Disallow dropping items if not allowed to build
if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
{
- infostream<<"Player "<<player->getName()<<" cannot remove node"
- <<" because privileges are "<<getPlayerPrivs(player)
- <<std::endl;
- cannot_remove_node = true;
- }
-
- /*
- If node can't be removed, set block to be re-sent to
- client and quit.
- */
- if(cannot_remove_node)
- {
- infostream<<"Server: Not finishing digging."<<std::endl;
-
- // Client probably has wrong data.
- // Set block not sent, so that client will get
- // a valid one.
- infostream<<"Client "<<peer_id<<" tried to dig "
- <<"node; but node cannot be removed."
- <<" setting MapBlock not sent."<<std::endl;
- RemoteClient *client = getClient(peer_id);
- v3s16 blockpos = getNodeBlockPos(p_under);
- client->SetBlockNotSent(blockpos);
-
+ delete a;
return;
}
-
- actionstream<<player->getName()<<" digs "<<PP(p_under)
- <<", gets material "<<(int)material<<", mineral "
- <<(int)mineral<<std::endl;
-
- /*
- Send the removal to all close-by players.
- - If other player is close, send REMOVENODE
- - Otherwise set blocks not sent
- */
- core::list<u16> far_players;
- sendRemoveNode(p_under, peer_id, &far_players, 30);
-
- /*
- Update and send inventory
- */
-
- if(g_settings->getBool("creative_mode") == false)
+ // If player is not an admin, check for ownership
+ else if (da->from_inv != "current_player"
+ && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
{
- /*
- Wear out tool
- */
- InventoryList *mlist = player->inventory.getList("main");
- if(mlist != NULL)
- {
- InventoryItem *item = mlist->getItem(item_i);
- if(item && (std::string)item->getName() == "ToolItem")
- {
- ToolItem *titem = (ToolItem*)item;
- std::string toolname = titem->getToolName();
-
- // Get digging properties for material and tool
- ToolDiggingProperties tp =
- m_toolmgr->getDiggingProperties(toolname);
- DiggingProperties prop =
- getDiggingProperties(material, &tp, m_nodemgr);
-
- if(prop.diggable == false)
- {
- infostream<<"Server: WARNING: Player digged"
- <<" with impossible material + tool"
- <<" combination"<<std::endl;
- }
-
- bool weared_out = titem->addWear(prop.wear);
-
- if(weared_out)
- {
- mlist->deleteItem(item_i);
- }
- }
- }
-
- /*
- Add dug item to inventory
- */
-
- InventoryItem *item = NULL;
-
- if(mineral != MINERAL_NONE)
- item = getDiggedMineralItem(mineral, this);
-
- // If not mineral
- if(item == NULL)
- {
- const std::string &dug_s = m_nodemgr->get(material).dug_item;
- if(dug_s != "")
- {
- std::istringstream is(dug_s, std::ios::binary);
- item = InventoryItem::deSerialize(is, this);
- }
- }
-
- if(item != NULL)
- {
- // Add a item to inventory
- player->inventory.addItem("main", item);
-
- // Send inventory
- UpdateCrafting(player->peer_id);
- SendInventory(player->peer_id);
- }
-
- item = NULL;
-
- if(mineral != MINERAL_NONE)
- item = getDiggedMineralItem(mineral, this);
-
- // If not mineral
- if(item == NULL)
+ Strfnd fn(da->from_inv);
+ std::string id0 = fn.next(":");
+ if(id0 == "nodemeta")
{
- const std::string &extra_dug_s = m_nodemgr->get(material).extra_dug_item;
- s32 extra_rarity = m_nodemgr->get(material).extra_dug_item_rarity;
- if(extra_dug_s != "" && extra_rarity != 0
- && myrand() % extra_rarity == 0)
+ v3s16 p;
+ p.X = stoi(fn.next(","));
+ p.Y = stoi(fn.next(","));
+ p.Z = stoi(fn.next(","));
+ NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
+ if(meta->getOwner() != "" &&
+ meta->getOwner() != player->getName())
{
- std::istringstream is(extra_dug_s, std::ios::binary);
- item = InventoryItem::deSerialize(is, this);
+ infostream<<"Cannot move item: "
+ "not owner of metadata"
+ <<std::endl;
+ delete a;
+ return;
}
}
-
- if(item != NULL)
- {
- // Add a item to inventory
- player->inventory.addItem("main", item);
-
- // Send inventory
- UpdateCrafting(player->peer_id);
- SendInventory(player->peer_id);
- }
- }
-
- /*
- Remove the node
- (this takes some time so it is done after the quick stuff)
- */
- {
- MapEditEventIgnorer ign(&m_ignore_map_edit_events);
-
- m_env->getMap().removeNodeAndUpdate(p_under, modified_blocks);
- }
- /*
- Set blocks not sent to far players
- */
- for(core::list<u16>::Iterator
- i = far_players.begin();
- i != far_players.end(); i++)
- {
- u16 peer_id = *i;
- RemoteClient *client = getClient(peer_id);
- if(client==NULL)
- continue;
- client->SetBlocksNotSent(modified_blocks);
}
}
+ // Do the action
+ a->apply(&c, this, m_env);
+ // Eat the action
+ delete a;
+ }
+ else if(command == TOSERVER_CHAT_MESSAGE)
+ {
/*
- 1: place block
+ u16 command
+ u16 length
+ wstring message
*/
- else if(action == 1)
+ u8 buf[6];
+ std::string datastring((char*)&data[2], datasize-2);
+ std::istringstream is(datastring, std::ios_base::binary);
+
+ // Read stuff
+ is.read((char*)buf, 2);
+ u16 len = readU16(buf);
+
+ std::wstring message;
+ for(u16 i=0; i<len; i++)
{
+ is.read((char*)buf, 2);
+ message += (wchar_t)readU16(buf);
+ }
+
+ // Get player name of this client
+ std::wstring name = narrow_to_wide(player->getName());
+
+ // Run script hook
+ bool ate = scriptapi_on_chat_message(m_lua, player->getName(),
+ wide_to_narrow(message));
+ // If script ate the message, don't proceed
+ if(ate)
+ return;
+
+ // Line to send to players
+ std::wstring line;
+ // Whether to send to the player that sent the line
+ bool send_to_sender = false;
+ // Whether to send to other players
+ bool send_to_others = false;
+
+ // Local player gets all privileges regardless of
+ // what's set on their account.
+ u64 privs = getPlayerPrivs(player);
+
+ // Parse commands
+ if(message[0] == L'/')
+ {
+ size_t strip_size = 1;
+ if (message[1] == L'#') // support old-style commans
+ ++strip_size;
+ message = message.substr(strip_size);
+
+ WStrfnd f1(message);
+ f1.next(L" "); // Skip over /#whatever
+ std::wstring paramstring = f1.next(L"");
+
+ ServerCommandContext *ctx = new ServerCommandContext(
+ str_split(message, L' '),
+ paramstring,
+ this,
+ m_env,
+ player,
+ privs);
+
+ std::wstring reply(processServerCommand(ctx));
+ send_to_sender = ctx->flags & SEND_TO_SENDER;
+ send_to_others = ctx->flags & SEND_TO_OTHERS;
+
+ if (ctx->flags & SEND_NO_PREFIX)
+ line += reply;
+ else
+ line += L"Server: " + reply;
+
+ delete ctx;
+
+ }
+ else
+ {
+ if(privs & PRIV_SHOUT)
+ {
+ line += L"<";
+ line += name;
+ line += L"> ";
+ line += message;
+ send_to_others = true;
+ }
+ else
+ {
+ line += L"Server: You are not allowed to shout";
+ send_to_sender = true;
+ }
+ }
+
+ if(line != L"")
+ {
+ if(send_to_others)
+ actionstream<<"CHAT: "<<wide_to_narrow(line)<<std::endl;
- InventoryList *ilist = player->inventory.getList("main");
- if(ilist == NULL)
- return;
-
- // Get item
- InventoryItem *item = ilist->getItem(item_i);
-
- // If there is no item, it is not possible to add it anywhere
- if(item == NULL)
- return;
-
/*
- Handle material items
+ Send the message to clients
*/
- if(std::string("MaterialItem") == item->getName())
+ for(core::map<u16, RemoteClient*>::Iterator
+ i = m_clients.getIterator();
+ i.atEnd() == false; i++)
{
- try{
- // Don't add a node if this is not a free space
- MapNode n2 = m_env->getMap().getNode(p_over);
- bool no_enough_privs =
- ((getPlayerPrivs(player) & PRIV_BUILD)==0);
- if(no_enough_privs)
- infostream<<"Player "<<player->getName()<<" cannot add node"
- <<" because privileges are "<<getPlayerPrivs(player)
- <<std::endl;
+ // Get client and check that it is valid
+ RemoteClient *client = i.getNode()->getValue();
+ assert(client->peer_id == i.getNode()->getKey());
+ if(client->serialization_version == SER_FMT_VER_INVALID)
+ continue;
- if(m_nodemgr->get(n2).buildable_to == false
- || no_enough_privs)
- {
- // Client probably has wrong data.
- // Set block not sent, so that client will get
- // a valid one.
- infostream<<"Client "<<peer_id<<" tried to place"
- <<" node in invalid position; setting"
- <<" MapBlock not sent."<<std::endl;
- RemoteClient *client = getClient(peer_id);
- v3s16 blockpos = getNodeBlockPos(p_over);
- client->SetBlockNotSent(blockpos);
- return;
- }
- }
- catch(InvalidPositionException &e)
- {
- infostream<<"Server: Ignoring ADDNODE: Node not found"
- <<" Adding block to emerge queue."
- <<std::endl;
- m_emerge_queue.addBlock(peer_id,
- getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
- return;
- }
+ // Filter recipient
+ bool sender_selected = (peer_id == client->peer_id);
+ if(sender_selected == true && send_to_sender == false)
+ continue;
+ if(sender_selected == false && send_to_others == false)
+ continue;
- // Reset build time counter
- getClient(peer_id)->m_time_from_building = 0.0;
+ SendChatMessage(client->peer_id, line);
+ }
+ }
+ }
+ else if(command == TOSERVER_DAMAGE)
+ {
+ std::string datastring((char*)&data[2], datasize-2);
+ std::istringstream is(datastring, std::ios_base::binary);
+ u8 damage = readU8(is);
+
+ if(g_settings->getBool("enable_damage"))
+ {
+ actionstream<<player->getName()<<" damaged by "
+ <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
+ <<std::endl;
- // Create node data
- MaterialItem *mitem = (MaterialItem*)item;
- MapNode n;
- n.setContent(mitem->getMaterial());
-
- actionstream<<player->getName()<<" places material "
- <<(int)mitem->getMaterial()
- <<" at "<<PP(p_under)<<std::endl;
-
- // Calculate direction for wall mounted stuff
- if(m_nodemgr->get(n).wall_mounted)
- n.param2 = packDir(p_under - p_over);
+ HandlePlayerHP(player, damage);
+ }
+ else
+ {
+ SendPlayerHP(player);
+ }
+ }
+ else if(command == TOSERVER_PASSWORD)
+ {
+ /*
+ [0] u16 TOSERVER_PASSWORD
+ [2] u8[28] old password
+ [30] u8[28] new password
+ */
- // Calculate the direction for furnaces and chests and stuff
- if(m_nodemgr->get(n).param_type == CPT_FACEDIR_SIMPLE)
- {
- v3f playerpos = player->getPosition();
- v3f blockpos = intToFloat(p_over, BS) - playerpos;
- blockpos = blockpos.normalize();
- n.param1 = 0;
- if (fabs(blockpos.X) > fabs(blockpos.Z)) {
- if (blockpos.X < 0)
- n.param1 = 3;
- else
- n.param1 = 1;
- } else {
- if (blockpos.Z < 0)
- n.param1 = 2;
- else
- n.param1 = 0;
- }
- }
+ if(datasize != 2+PASSWORD_SIZE*2)
+ return;
+ /*char password[PASSWORD_SIZE];
+ for(u32 i=0; i<PASSWORD_SIZE-1; i++)
+ password[i] = data[2+i];
+ password[PASSWORD_SIZE-1] = 0;*/
+ std::string oldpwd;
+ for(u32 i=0; i<PASSWORD_SIZE-1; i++)
+ {
+ char c = data[2+i];
+ if(c == 0)
+ break;
+ oldpwd += c;
+ }
+ std::string newpwd;
+ for(u32 i=0; i<PASSWORD_SIZE-1; i++)
+ {
+ char c = data[2+PASSWORD_SIZE+i];
+ if(c == 0)
+ break;
+ newpwd += c;
+ }
+ infostream<<"Server: Client requests a password change from "
+ <<"'"<<oldpwd<<"' to '"<<newpwd<<"'"<<std::endl;
+
+ std::string playername = player->getName();
+
+ if(m_authmanager.exists(playername) == false)
+ {
+ infostream<<"Server: playername not found in authmanager"<<std::endl;
+ // Wrong old password supplied!!
+ SendChatMessage(peer_id, L"playername not found in authmanager");
+ return;
+ }
+
+ std::string checkpwd = m_authmanager.getPassword(playername);
+
+ if(oldpwd != checkpwd)
+ {
+ infostream<<"Server: invalid old password"<<std::endl;
+ // Wrong old password supplied!!
+ SendChatMessage(peer_id, L"Invalid old password supplied. Password NOT changed.");
+ return;
+ }
+
+ actionstream<<player->getName()<<" changes password"<<std::endl;
+
+ m_authmanager.setPassword(playername, newpwd);
+
+ infostream<<"Server: password change successful for "<<playername
+ <<std::endl;
+ SendChatMessage(peer_id, L"Password change successful");
+ }
+ else if(command == TOSERVER_PLAYERITEM)
+ {
+ if (datasize < 2+2)
+ return;
+
+ u16 item = readU16(&data[2]);
+ player->wieldItem(item);
+ SendWieldedItem(player);
+ }
+ else if(command == TOSERVER_RESPAWN)
+ {
+ if(player->hp != 0)
+ return;
+
+ RespawnPlayer(player);
+
+ actionstream<<player->getName()<<" respawns at "
+ <<PP(player->getPosition()/BS)<<std::endl;
+ }
+ else if(command == TOSERVER_INTERACT)
+ {
+ std::string datastring((char*)&data[2], datasize-2);
+ std::istringstream is(datastring, std::ios_base::binary);
+
+ /*
+ [0] u16 command
+ [2] u8 action
+ [3] u16 item
+ [5] u32 length of the next item
+ [9] serialized PointedThing
+ actions:
+ 0: start digging (from undersurface) or use
+ 1: stop digging (all parameters ignored)
+ 2: digging completed
+ 3: place block or item (to abovesurface)
+ 4: use item
+ */
+ u8 action = readU8(is);
+ u16 item_i = readU16(is);
+ std::istringstream tmp_is(deSerializeLongString(is), std::ios::binary);
+ PointedThing pointed;
+ pointed.deSerialize(tmp_is);
+
+ infostream<<"TOSERVER_INTERACT: action="<<(int)action<<", item="<<item_i<<", pointed="<<pointed.dump()<<std::endl;
+
+ v3f player_pos = srp->m_last_good_position;
+
+ // Update wielded item
+ srp->wieldItem(item_i);
+
+ // Get pointed to node (undefined if not POINTEDTYPE_NODE)
+ v3s16 p_under = pointed.node_undersurface;
+ v3s16 p_above = pointed.node_abovesurface;
+
+ // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
+ ServerActiveObject *pointed_object = NULL;
+ if(pointed.type == POINTEDTHING_OBJECT)
+ {
+ pointed_object = m_env->getActiveObject(pointed.object_id);
+ if(pointed_object == NULL)
+ {
+ infostream<<"TOSERVER_INTERACT: "
+ "pointed object is NULL"<<std::endl;
+ return;
+ }
+
+ }
+
+ /*
+ Check that target is reasonably close
+ (only when digging or placing things)
+ */
+ if(action == 0 || action == 2 || action == 3)
+ {
+ v3f pointed_pos = player_pos;
+ if(pointed.type == POINTEDTHING_NODE)
+ {
+ pointed_pos = intToFloat(p_under, BS);
+ }
+ else if(pointed.type == POINTEDTHING_OBJECT)
+ {
+ pointed_pos = pointed_object->getBasePosition();
+ }
+
+ float d = player_pos.getDistanceFrom(pointed_pos);
+ float max_d = BS * 10; // Just some large enough value
+ if(d > max_d){
+ actionstream<<"Player "<<player->getName()
+ <<" tried to access "<<pointed.dump()
+ <<" from too far: "
+ <<"d="<<d<<", max_d="<<max_d
+ <<". ignoring."<<std::endl;
+ // Re-send block to revert change on client-side
+ RemoteClient *client = getClient(peer_id);
+ v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos, BS));
+ client->SetBlockNotSent(blockpos);
+ // Do nothing else
+ return;
+ }
+ }
+
+ /*
+ Make sure the player is allowed to do it
+ */
+ bool build_priv = (getPlayerPrivs(player) & PRIV_BUILD) != 0;
+ if(!build_priv)
+ {
+ infostream<<"Ignoring interaction from player "<<player->getName()
+ <<" because privileges are "<<getPlayerPrivs(player)
+ <<std::endl;
+ // NOTE: no return; here, fall through
+ }
+
+ /*
+ 0: start digging or punch object
+ */
+ if(action == 0)
+ {
+ if(pointed.type == POINTEDTHING_NODE)
+ {
/*
- Send to all close-by players
- */
- core::list<u16> far_players;
- sendAddNode(p_over, n, 0, &far_players, 30);
-
- /*
- Handle inventory
- */
- InventoryList *ilist = player->inventory.getList("main");
- if(g_settings->getBool("creative_mode") == false && ilist)
- {
- // Remove from inventory and send inventory
- if(mitem->getCount() == 1)
- ilist->deleteItem(item_i);
- else
- mitem->remove(1);
- // Send inventory
- UpdateCrafting(peer_id);
- SendInventory(peer_id);
- }
-
- /*
- Add node.
-
- This takes some time so it is done after the quick stuff
+ NOTE: This can be used in the future to check if
+ somebody is cheating, by checking the timing.
*/
- core::map<v3s16, MapBlock*> modified_blocks;
- {
- MapEditEventIgnorer ign(&m_ignore_map_edit_events);
+ bool cannot_punch_node = !build_priv;
- std::string p_name = std::string(player->getName());
- m_env->getMap().addNodeAndUpdate(p_over, n, modified_blocks, p_name);
+ MapNode n(CONTENT_IGNORE);
+
+ try
+ {
+ n = m_env->getMap().getNode(p_under);
}
- /*
- Set blocks not sent to far players
- */
- for(core::list<u16>::Iterator
- i = far_players.begin();
- i != far_players.end(); i++)
+ catch(InvalidPositionException &e)
{
- u16 peer_id = *i;
- RemoteClient *client = getClient(peer_id);
- if(client==NULL)
- continue;
- client->SetBlocksNotSent(modified_blocks);
+ infostream<<"Server: Not punching: Node not found."
+ <<" Adding block to emerge queue."
+ <<std::endl;
+ m_emerge_queue.addBlock(peer_id,
+ getNodeBlockPos(p_above), BLOCK_EMERGE_FLAG_FROMDISK);
+ cannot_punch_node = true;
}
+ if(cannot_punch_node)
+ return;
+
/*
- Calculate special events
+ Run script hook
*/
-
- /*if(n.d == CONTENT_MESE)
+ scriptapi_environment_on_punchnode(m_lua, p_under, n, srp);
+ }
+ else if(pointed.type == POINTEDTHING_OBJECT)
+ {
+ if(!build_priv)
+ return;
+
+ // Skip if object has been removed
+ if(pointed_object->m_removed)
+ return;
+
+ actionstream<<player->getName()<<" punches object "
+ <<pointed.object_id<<std::endl;
+
+ // Do stuff
+ pointed_object->punch(srp);
+ }
+
+ } // action == 0
+
+ /*
+ 1: stop digging
+ */
+ else if(action == 1)
+ {
+ } // action == 1
+
+ /*
+ 2: Digging completed
+ */
+ else if(action == 2)
+ {
+ // Only complete digging of nodes
+ if(pointed.type != POINTEDTHING_NODE)
+ return;
+
+ // Mandatory parameter; actually used for nothing
+ core::map<v3s16, MapBlock*> modified_blocks;
+
+ content_t material = CONTENT_IGNORE;
+ u8 mineral = MINERAL_NONE;
+
+ bool cannot_remove_node = !build_priv;
+
+ MapNode n(CONTENT_IGNORE);
+ try
+ {
+ n = m_env->getMap().getNode(p_under);
+ // Get mineral
+ mineral = n.getMineral(m_nodedef);
+ // Get material at position
+ material = n.getContent();
+ // If not yet cancelled
+ if(cannot_remove_node == false)
{
- u32 count = 0;
- for(s16 z=-1; z<=1; z++)
- for(s16 y=-1; y<=1; y++)
- for(s16 x=-1; x<=1; x++)
+ // If it's not diggable, do nothing
+ if(m_nodedef->get(material).diggable == false)
{
-
+ infostream<<"Server: Not finishing digging: "
+ <<"Node not diggable"
+ <<std::endl;
+ cannot_remove_node = true;
}
- }*/
+ }
+ // If not yet cancelled
+ if(cannot_remove_node == false)
+ {
+ // Get node metadata
+ NodeMetadata *meta = m_env->getMap().getNodeMetadata(p_under);
+ if(meta && meta->nodeRemovalDisabled() == true)
+ {
+ infostream<<"Server: Not finishing digging: "
+ <<"Node metadata disables removal"
+ <<std::endl;
+ cannot_remove_node = true;
+ }
+ }
+ }
+ catch(InvalidPositionException &e)
+ {
+ infostream<<"Server: Not finishing digging: Node not found."
+ <<" Adding block to emerge queue."
+ <<std::endl;
+ m_emerge_queue.addBlock(peer_id,
+ getNodeBlockPos(p_above), BLOCK_EMERGE_FLAG_FROMDISK);
+ cannot_remove_node = true;
}
+
/*
- Place other item (not a block)
+ If node can't be removed, set block to be re-sent to
+ client and quit.
*/
- else
+ if(cannot_remove_node)
{
- v3s16 blockpos = getNodeBlockPos(p_over);
-
- /*
- Check that the block is loaded so that the item
- can properly be added to the static list too
- */
- MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
- if(block==NULL)
- {
- infostream<<"Error while placing object: "
- "block not found"<<std::endl;
- return;
- }
+ infostream<<"Server: Not finishing digging."<<std::endl;
+
+ // Client probably has wrong data.
+ // Set block not sent, so that client will get
+ // a valid one.
+ infostream<<"Client "<<peer_id<<" tried to dig "
+ <<"node; but node cannot be removed."
+ <<" setting MapBlock not sent."<<std::endl;
+ RemoteClient *client = getClient(peer_id);
+ v3s16 blockpos = getNodeBlockPos(p_under);
+ client->SetBlockNotSent(blockpos);
+
+ return;
+ }
+
+ actionstream<<player->getName()<<" digs "<<PP(p_under)
+ <<", gets material "<<(int)material<<", mineral "
+ <<(int)mineral<<std::endl;
+
+ /*
+ Send the removal to all close-by players.
+ - If other player is close, send REMOVENODE
+ - Otherwise set blocks not sent
+ */
+ core::list<u16> far_players;
+ sendRemoveNode(p_under, peer_id, &far_players, 30);
+
+ /*
+ Update and send inventory
+ */
+ if(g_settings->getBool("creative_mode") == false)
+ {
/*
- If in creative mode, item dropping is disabled unless
- player has build privileges
+ Wear out tool
*/
- if(g_settings->getBool("creative_mode") &&
- (getPlayerPrivs(player) & PRIV_BUILD) == 0)
+ InventoryList *mlist = player->inventory.getList("main");
+ if(mlist != NULL)
{
- infostream<<"Not allowing player to drop item: "
- "creative mode and no build privs"<<std::endl;
- return;
- }
+ InventoryItem *item = mlist->getItem(item_i);
+ if(item && (std::string)item->getName() == "ToolItem")
+ {
+ ToolItem *titem = (ToolItem*)item;
+ std::string toolname = titem->getToolName();
+
+ // Get digging properties for material and tool
+ ToolDiggingProperties tp =
+ m_toolmgr->getDiggingProperties(toolname);
+ DiggingProperties prop =
+ getDiggingProperties(material, &tp, m_nodedef);
+
+ if(prop.diggable == false)
+ {
+ infostream<<"Server: WARNING: Player digged"
+ <<" with impossible material + tool"
+ <<" combination"<<std::endl;
+ }
+
+ bool weared_out = titem->addWear(prop.wear);
+
+ if(weared_out)
+ {
+ mlist->deleteItem(item_i);
+ }
- // Calculate a position for it
- v3f pos = intToFloat(p_over, BS);
- //pos.Y -= BS*0.45;
- /*pos.Y -= BS*0.25; // let it drop a bit
- // Randomize a bit
- pos.X += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
- pos.Z += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;*/
+ srp->m_inventory_not_sent = true;
+ }
+ }
/*
- Create the object
+ Add dug item to inventory
*/
- ServerActiveObject *obj = item->createSAO(m_env, 0, pos);
- if(obj == NULL)
+ InventoryItem *item = NULL;
+
+ if(mineral != MINERAL_NONE)
+ item = getDiggedMineralItem(mineral, this);
+
+ // If not mineral
+ if(item == NULL)
{
- infostream<<"WARNING: item resulted in NULL object, "
- <<"not placing onto map"
- <<std::endl;
+ const std::string &dug_s = m_nodedef->get(material).dug_item;
+ if(dug_s != "")
+ {
+ std::istringstream is(dug_s, std::ios::binary);
+ item = InventoryItem::deSerialize(is, this);
+ }
}
- else
- {
- actionstream<<player->getName()<<" places "<<item->getName()
- <<" at "<<PP(p_over)<<std::endl;
- // Add the object to the environment
- m_env->addActiveObject(obj);
-
- infostream<<"Placed object"<<std::endl;
+ if(item != NULL)
+ {
+ // Add a item to inventory
+ player->inventory.addItem("main", item);
+ srp->m_inventory_not_sent = true;
+ }
+
+ item = NULL;
- if(g_settings->getBool("creative_mode") == false)
+ if(mineral != MINERAL_NONE)
+ item = getDiggedMineralItem(mineral, this);
+
+ // If not mineral
+ if(item == NULL)
+ {
+ const std::string &extra_dug_s = m_nodedef->get(material).extra_dug_item;
+ s32 extra_rarity = m_nodedef->get(material).extra_dug_item_rarity;
+ if(extra_dug_s != "" && extra_rarity != 0
+ && myrand() % extra_rarity == 0)
{
- // Delete the right amount of items from the slot
- u16 dropcount = item->getDropCount();
-
- // Delete item if all gone
- if(item->getCount() <= dropcount)
- {
- if(item->getCount() < dropcount)
- infostream<<"WARNING: Server: dropped more items"
- <<" than the slot contains"<<std::endl;
-
- InventoryList *ilist = player->inventory.getList("main");
- if(ilist)
- // Remove from inventory and send inventory
- ilist->deleteItem(item_i);
- }
- // Else decrement it
- else
- item->remove(dropcount);
-
- // Send inventory
- UpdateCrafting(peer_id);
- SendInventory(peer_id);
+ std::istringstream is(extra_dug_s, std::ios::binary);
+ item = InventoryItem::deSerialize(is, this);
}
}
- }
-
- } // action == 1
-
- /*
- Catch invalid actions
- */
- else
- {
- infostream<<"WARNING: Server: Invalid action "
- <<action<<std::endl;
- }
- }
-#if 0
- else if(command == TOSERVER_RELEASE)
- {
- if(datasize < 3)
- return;
- /*
- length: 3
- [0] u16 command
- [2] u8 button
- */
- infostream<<"TOSERVER_RELEASE ignored"<<std::endl;
- }
-#endif
- else if(command == TOSERVER_SIGNTEXT)
- {
- infostream<<"Server: TOSERVER_SIGNTEXT not supported anymore"
- <<std::endl;
- return;
- }
- else if(command == TOSERVER_SIGNNODETEXT)
- {
- if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
- return;
- /*
- u16 command
- v3s16 p
- u16 textlen
- textdata
- */
- std::string datastring((char*)&data[2], datasize-2);
- std::istringstream is(datastring, std::ios_base::binary);
- u8 buf[6];
- // Read stuff
- is.read((char*)buf, 6);
- v3s16 p = readV3S16(buf);
- is.read((char*)buf, 2);
- u16 textlen = readU16(buf);
- std::string text;
- for(u16 i=0; i<textlen; i++)
- {
- is.read((char*)buf, 1);
- text += (char)buf[0];
- }
+
+ if(item != NULL)
+ {
+ // Add a item to inventory
+ player->inventory.addItem("main", item);
+ srp->m_inventory_not_sent = true;
+ }
+ }
- NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
- if(!meta)
- return;
- if(meta->typeId() != CONTENT_SIGN_WALL)
- return;
- SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
- signmeta->setText(text);
-
- actionstream<<player->getName()<<" writes \""<<text<<"\" to sign "
- <<" at "<<PP(p)<<std::endl;
-
- v3s16 blockpos = getNodeBlockPos(p);
- MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
- if(block)
- {
- block->setChangedFlag();
- }
+ /*
+ Remove the node
+ (this takes some time so it is done after the quick stuff)
+ */
+ {
+ MapEditEventIgnorer ign(&m_ignore_map_edit_events);
- for(core::map<u16, RemoteClient*>::Iterator
- i = m_clients.getIterator();
- i.atEnd()==false; i++)
- {
- RemoteClient *client = i.getNode()->getValue();
- client->SetBlockNotSent(blockpos);
- }
- }
- else if(command == TOSERVER_INVENTORY_ACTION)
- {
- /*// Ignore inventory changes if in creative mode
- if(g_settings->getBool("creative_mode") == true)
- {
- infostream<<"TOSERVER_INVENTORY_ACTION: ignoring in creative mode"
- <<std::endl;
- return;
- }*/
- // Strip command and create a stream
- std::string datastring((char*)&data[2], datasize-2);
- infostream<<"TOSERVER_INVENTORY_ACTION: data="<<datastring<<std::endl;
- std::istringstream is(datastring, std::ios_base::binary);
- // Create an action
- InventoryAction *a = InventoryAction::deSerialize(is);
- if(a != NULL)
- {
- // Create context
- InventoryContext c;
- c.current_player = player;
+ m_env->getMap().removeNodeAndUpdate(p_under, modified_blocks);
+ }
+ /*
+ Set blocks not sent to far players
+ */
+ for(core::list<u16>::Iterator
+ i = far_players.begin();
+ i != far_players.end(); i++)
+ {
+ u16 peer_id = *i;
+ RemoteClient *client = getClient(peer_id);
+ if(client==NULL)
+ continue;
+ client->SetBlocksNotSent(modified_blocks);
+ }
/*
- Handle craftresult specially if not in creative mode
+ Run script hook
*/
- bool disable_action = false;
- if(a->getType() == IACTION_MOVE
- && g_settings->getBool("creative_mode") == false)
+ scriptapi_environment_on_dignode(m_lua, p_under, n, srp);
+ } // action == 2
+
+ /*
+ 3: place block or right-click object
+ */
+ else if(action == 3)
+ {
+ if(pointed.type == POINTEDTHING_NODE)
{
- IMoveAction *ma = (IMoveAction*)a;
- if(ma->to_inv == "current_player" &&
- ma->from_inv == "current_player")
+ InventoryList *ilist = player->inventory.getList("main");
+ if(ilist == NULL)
+ return;
+
+ // Get item
+ InventoryItem *item = ilist->getItem(item_i);
+
+ // If there is no item, it is not possible to add it anywhere
+ if(item == NULL)
+ return;
+
+ /*
+ Handle material items
+ */
+ if(std::string("MaterialItem") == item->getName())
{
- InventoryList *rlist = player->inventory.getList("craftresult");
- assert(rlist);
- InventoryList *clist = player->inventory.getList("craft");
- assert(clist);
- InventoryList *mlist = player->inventory.getList("main");
- assert(mlist);
+ bool cannot_place_node = !build_priv;
+
+ try{
+ // Don't add a node if this is not a free space
+ MapNode n2 = m_env->getMap().getNode(p_above);
+ if(m_nodedef->get(n2).buildable_to == false)
+ {
+ infostream<<"Client "<<peer_id<<" tried to place"
+ <<" node in invalid position."<<std::endl;
+ cannot_place_node = true;
+ }
+ }
+ catch(InvalidPositionException &e)
+ {
+ infostream<<"Server: Ignoring ADDNODE: Node not found"
+ <<" Adding block to emerge queue."
+ <<std::endl;
+ m_emerge_queue.addBlock(peer_id,
+ getNodeBlockPos(p_above), BLOCK_EMERGE_FLAG_FROMDISK);
+ cannot_place_node = true;
+ }
+
+ if(cannot_place_node)
+ {
+ // Client probably has wrong data.
+ // Set block not sent, so that client will get
+ // a valid one.
+ RemoteClient *client = getClient(peer_id);
+ v3s16 blockpos = getNodeBlockPos(p_above);
+ client->SetBlockNotSent(blockpos);
+ return;
+ }
+
+ // Reset build time counter
+ getClient(peer_id)->m_time_from_building = 0.0;
+
+ // Create node data
+ MaterialItem *mitem = (MaterialItem*)item;
+ MapNode n;
+ n.setContent(mitem->getMaterial());
+
+ actionstream<<player->getName()<<" places material "
+ <<(int)mitem->getMaterial()
+ <<" at "<<PP(p_under)<<std::endl;
+
+ // Calculate direction for wall mounted stuff
+ if(m_nodedef->get(n).wall_mounted)
+ n.param2 = packDir(p_under - p_above);
+
+ // Calculate the direction for furnaces and chests and stuff
+ if(m_nodedef->get(n).param_type == CPT_FACEDIR_SIMPLE)
+ {
+ v3f playerpos = player->getPosition();
+ v3f blockpos = intToFloat(p_above, BS) - playerpos;
+ blockpos = blockpos.normalize();
+ n.param1 = 0;
+ if (fabs(blockpos.X) > fabs(blockpos.Z)) {
+ if (blockpos.X < 0)
+ n.param1 = 3;
+ else
+ n.param1 = 1;
+ } else {
+ if (blockpos.Z < 0)
+ n.param1 = 2;
+ else
+ n.param1 = 0;
+ }
+ }
+
+ /*
+ Send to all close-by players
+ */
+ core::list<u16> far_players;
+ sendAddNode(p_above, n, 0, &far_players, 30);
+
/*
- Craftresult is no longer preview if something
- is moved into it
+ Handle inventory
*/
- if(ma->to_list == "craftresult"
- && ma->from_list != "craftresult")
+ InventoryList *ilist = player->inventory.getList("main");
+ if(g_settings->getBool("creative_mode") == false && ilist)
{
- // If it currently is a preview, remove
- // its contents
- if(player->craftresult_is_preview)
- {
- rlist->deleteItem(0);
- }
- player->craftresult_is_preview = false;
+ // Remove from inventory and send inventory
+ if(mitem->getCount() <= 1)
+ ilist->deleteItem(item_i);
+ else
+ mitem->remove(1);
+ srp->m_inventory_not_sent = true;
}
+
/*
- Crafting takes place if this condition is true.
+ Add node.
+
+ This takes some time so it is done after the quick stuff
*/
- if(player->craftresult_is_preview &&
- ma->from_list == "craftresult")
+ core::map<v3s16, MapBlock*> modified_blocks;
{
- player->craftresult_is_preview = false;
- clist->decrementMaterials(1);
-
- /* Print out action */
- InventoryList *list =
- player->inventory.getList("craftresult");
- assert(list);
- InventoryItem *item = list->getItem(0);
- std::string itemname = "NULL";
- if(item)
- itemname = item->getName();
- actionstream<<player->getName()<<" crafts "
- <<itemname<<std::endl;
+ MapEditEventIgnorer ign(&m_ignore_map_edit_events);
+
+ std::string p_name = std::string(player->getName());
+ m_env->getMap().addNodeAndUpdate(p_above, n, modified_blocks, p_name);
}
/*
- If the craftresult is placed on itself, move it to
- main inventory instead of doing the action
+ Set blocks not sent to far players
*/
- if(ma->to_list == "craftresult"
- && ma->from_list == "craftresult")
+ for(core::list<u16>::Iterator
+ i = far_players.begin();
+ i != far_players.end(); i++)
{
- disable_action = true;
-
- InventoryItem *item1 = rlist->changeItem(0, NULL);
- mlist->addItem(item1);
+ u16 peer_id = *i;
+ RemoteClient *client = getClient(peer_id);
+ if(client==NULL)
+ continue;
+ client->SetBlocksNotSent(modified_blocks);
}
- }
- // Disallow moving items if not allowed to build
- else if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
- {
- return;
- }
- // if it's a locking chest, only allow the owner or server admins to move items
- else if (ma->from_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
- {
- Strfnd fn(ma->from_inv);
- std::string id0 = fn.next(":");
- if(id0 == "nodemeta")
+
+ /*
+ Run script hook
+ */
+ scriptapi_environment_on_placenode(m_lua, p_above, n, srp);
+
+ /*
+ Calculate special events
+ */
+
+ /*if(n.d == LEGN(m_nodedef, "CONTENT_MESE"))
{
- v3s16 p;
- p.X = stoi(fn.next(","));
- p.Y = stoi(fn.next(","));
- p.Z = stoi(fn.next(","));
- NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
- if(meta && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
- LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
- if (lcm->getOwner() != player->getName())
- return;
+ u32 count = 0;
+ for(s16 z=-1; z<=1; z++)
+ for(s16 y=-1; y<=1; y++)
+ for(s16 x=-1; x<=1; x++)
+ {
+
}
- }
+ }*/
}
- else if (ma->to_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
+ /*
+ Place other item (not a block)
+ */
+ else
{
- Strfnd fn(ma->to_inv);
- std::string id0 = fn.next(":");
- if(id0 == "nodemeta")
+ if(!build_priv)
{
- v3s16 p;
- p.X = stoi(fn.next(","));
- p.Y = stoi(fn.next(","));
- p.Z = stoi(fn.next(","));
- NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
- if(meta && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
- LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
- if (lcm->getOwner() != player->getName())
- return;
- }
+ infostream<<"Not allowing player to place item: "
+ "no build privileges"<<std::endl;
+ return;
}
- }
- }
-
- if(disable_action == false)
- {
- // Feed action to player inventory
- a->apply(&c, this);
- // Eat the action
- delete a;
- }
- else
- {
- // Send inventory
- UpdateCrafting(player->peer_id);
- SendInventory(player->peer_id);
- }
- }
- else
- {
- infostream<<"TOSERVER_INVENTORY_ACTION: "
- <<"InventoryAction::deSerialize() returned NULL"
- <<std::endl;
- }
- }
- else if(command == TOSERVER_CHAT_MESSAGE)
- {
- /*
- u16 command
- u16 length
- wstring message
- */
- u8 buf[6];
- std::string datastring((char*)&data[2], datasize-2);
- std::istringstream is(datastring, std::ios_base::binary);
-
- // Read stuff
- is.read((char*)buf, 2);
- u16 len = readU16(buf);
-
- std::wstring message;
- for(u16 i=0; i<len; i++)
- {
- is.read((char*)buf, 2);
- message += (wchar_t)readU16(buf);
- }
-
- // Get player name of this client
- std::wstring name = narrow_to_wide(player->getName());
-
- // Line to send to players
- std::wstring line;
- // Whether to send to the player that sent the line
- bool send_to_sender = false;
- // Whether to send to other players
- bool send_to_others = false;
-
- // Local player gets all privileges regardless of
- // what's set on their account.
- u64 privs = getPlayerPrivs(player);
-
- // Parse commands
- if(message[0] == L'/')
- {
- size_t strip_size = 1;
- if (message[1] == L'#') // support old-style commans
- ++strip_size;
- message = message.substr(strip_size);
-
- WStrfnd f1(message);
- f1.next(L" "); // Skip over /#whatever
- std::wstring paramstring = f1.next(L"");
- ServerCommandContext *ctx = new ServerCommandContext(
- str_split(message, L' '),
- paramstring,
- this,
- m_env,
- player,
- privs);
+ // Calculate a position for it
+ v3f pos = player_pos;
+ if(pointed.type == POINTEDTHING_NOTHING)
+ {
+ infostream<<"Not allowing player to place item: "
+ "pointing to nothing"<<std::endl;
+ return;
+ }
+ else if(pointed.type == POINTEDTHING_NODE)
+ {
+ pos = intToFloat(p_above, BS);
+ }
+ else if(pointed.type == POINTEDTHING_OBJECT)
+ {
+ pos = pointed_object->getBasePosition();
- std::wstring reply(processServerCommand(ctx));
- send_to_sender = ctx->flags & SEND_TO_SENDER;
- send_to_others = ctx->flags & SEND_TO_OTHERS;
+ // Randomize a bit
+ pos.X += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
+ pos.Z += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
+ }
- if (ctx->flags & SEND_NO_PREFIX)
- line += reply;
- else
- line += L"Server: " + reply;
+ //pos.Y -= BS*0.45;
+ //pos.Y -= BS*0.25; // let it drop a bit
- delete ctx;
+ /*
+ Check that the block is loaded so that the item
+ can properly be added to the static list too
+ */
+ v3s16 blockpos = getNodeBlockPos(floatToInt(pos, BS));
+ MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
+ if(block==NULL)
+ {
+ infostream<<"Error while placing item: "
+ "block not found"<<std::endl;
+ return;
+ }
- }
- else
- {
- if(privs & PRIV_SHOUT)
- {
- line += L"<";
- line += name;
- line += L"> ";
- line += message;
- send_to_others = true;
- }
- else
- {
- line += L"Server: You are not allowed to shout";
- send_to_sender = true;
- }
- }
-
- if(line != L"")
- {
- if(send_to_others)
- actionstream<<"CHAT: "<<wide_to_narrow(line)<<std::endl;
+ actionstream<<player->getName()<<" places "<<item->getName()
+ <<" at "<<PP(pos)<<std::endl;
- /*
- Send the message to clients
- */
- for(core::map<u16, RemoteClient*>::Iterator
- i = m_clients.getIterator();
- i.atEnd() == false; i++)
+ /*
+ Place the item
+ */
+ bool remove = item->dropOrPlace(m_env, srp, pos, true, -1);
+ if(remove && g_settings->getBool("creative_mode") == false)
+ {
+ InventoryList *ilist = player->inventory.getList("main");
+ if(ilist){
+ // Remove from inventory and send inventory
+ ilist->deleteItem(item_i);
+ srp->m_inventory_not_sent = true;
+ }
+ }
+ }
+ }
+ else if(pointed.type == POINTEDTHING_OBJECT)
{
- // Get client and check that it is valid
- RemoteClient *client = i.getNode()->getValue();
- assert(client->peer_id == i.getNode()->getKey());
- if(client->serialization_version == SER_FMT_VER_INVALID)
- continue;
+ // Right click object
- // Filter recipient
- bool sender_selected = (peer_id == client->peer_id);
- if(sender_selected == true && send_to_sender == false)
- continue;
- if(sender_selected == false && send_to_others == false)
- continue;
+ if(!build_priv)
+ return;
- SendChatMessage(client->peer_id, line);
+ // Skip if object has been removed
+ if(pointed_object->m_removed)
+ return;
+
+ actionstream<<player->getName()<<" right-clicks object "
+ <<pointed.object_id<<std::endl;
+
+ // Do stuff
+ pointed_object->rightClick(srp);
}
- }
- }
- else if(command == TOSERVER_DAMAGE)
- {
- std::string datastring((char*)&data[2], datasize-2);
- std::istringstream is(datastring, std::ios_base::binary);
- u8 damage = readU8(is);
- if(g_settings->getBool("enable_damage"))
- {
- actionstream<<player->getName()<<" damaged by "
- <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
- <<std::endl;
-
- HandlePlayerHP(player, damage);
- }
- else
- {
- SendPlayerHP(player);
- }
- }
- else if(command == TOSERVER_PASSWORD)
- {
+ } // action == 3
+
/*
- [0] u16 TOSERVER_PASSWORD
- [2] u8[28] old password
- [30] u8[28] new password
+ 4: use
*/
-
- if(datasize != 2+PASSWORD_SIZE*2)
- return;
- /*char password[PASSWORD_SIZE];
- for(u32 i=0; i<PASSWORD_SIZE-1; i++)
- password[i] = data[2+i];
- password[PASSWORD_SIZE-1] = 0;*/
- std::string oldpwd;
- for(u32 i=0; i<PASSWORD_SIZE-1; i++)
- {
- char c = data[2+i];
- if(c == 0)
- break;
- oldpwd += c;
- }
- std::string newpwd;
- for(u32 i=0; i<PASSWORD_SIZE-1; i++)
+ else if(action == 4)
{
- char c = data[2+PASSWORD_SIZE+i];
- if(c == 0)
- break;
- newpwd += c;
- }
+ InventoryList *ilist = player->inventory.getList("main");
+ if(ilist == NULL)
+ return;
- infostream<<"Server: Client requests a password change from "
- <<"'"<<oldpwd<<"' to '"<<newpwd<<"'"<<std::endl;
+ // Get item
+ InventoryItem *item = ilist->getItem(item_i);
+
+ // If there is no item, it is not possible to add it anywhere
+ if(item == NULL)
+ return;
- std::string playername = player->getName();
+ // Requires build privs
+ if(!build_priv)
+ {
+ infostream<<"Not allowing player to use item: "
+ "no build privileges"<<std::endl;
+ return;
+ }
- if(m_authmanager.exists(playername) == false)
- {
- infostream<<"Server: playername not found in authmanager"<<std::endl;
- // Wrong old password supplied!!
- SendChatMessage(peer_id, L"playername not found in authmanager");
- return;
- }
+ actionstream<<player->getName()<<" uses "<<item->getName()
+ <<", pointing at "<<pointed.dump()<<std::endl;
- std::string checkpwd = m_authmanager.getPassword(playername);
+ bool remove = item->use(m_env, srp, pointed);
+
+ if(remove && g_settings->getBool("creative_mode") == false)
+ {
+ InventoryList *ilist = player->inventory.getList("main");
+ if(ilist){
+ // Remove from inventory and send inventory
+ ilist->deleteItem(item_i);
+ srp->m_inventory_not_sent = true;
+ }
+ }
- if(oldpwd != checkpwd)
+ } // action == 4
+
+ /*
+ Catch invalid actions
+ */
+ else
{
- infostream<<"Server: invalid old password"<<std::endl;
- // Wrong old password supplied!!
- SendChatMessage(peer_id, L"Invalid old password supplied. Password NOT changed.");
- return;
+ infostream<<"WARNING: Server: Invalid action "
+ <<action<<std::endl;
}
- actionstream<<player->getName()<<" changes password"<<std::endl;
-
- m_authmanager.setPassword(playername, newpwd);
-
- infostream<<"Server: password change successful for "<<playername
- <<std::endl;
- SendChatMessage(peer_id, L"Password change successful");
- }
- else if(command == TOSERVER_PLAYERITEM)
- {
- if (datasize < 2+2)
- return;
-
- u16 item = readU16(&data[2]);
- player->wieldItem(item);
- SendWieldedItem(player);
- }
- else if(command == TOSERVER_RESPAWN)
- {
- if(player->hp != 0)
- return;
-
- RespawnPlayer(player);
-
- actionstream<<player->getName()<<" respawns at "
- <<PP(player->getPosition()/BS)<<std::endl;
+ // Complete add_to_inventory_later
+ srp->completeAddToInventoryLater(item_i);
}
else
{
if(id == "current_player")
{
assert(c->current_player);
- // Send inventory
- UpdateCrafting(c->current_player->peer_id);
- SendInventory(c->current_player->peer_id);
+ ServerRemotePlayer *srp =
+ static_cast<ServerRemotePlayer*>(c->current_player);
+ srp->m_inventory_not_sent = true;
return;
}
NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
if(meta)
meta->inventoryModified();
-
- for(core::map<u16, RemoteClient*>::Iterator
- i = m_clients.getIterator();
- i.atEnd()==false; i++)
- {
- RemoteClient *client = i.getNode()->getValue();
- client->SetBlockNotSent(blockpos);
- }
+
+ MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
+ if(block)
+ block->raiseModified(MOD_STATE_WRITE_NEEDED);
+
+ setBlockNotSent(blockpos);
return;
}
// Make data buffer
std::string s = os.str();
+ infostream<<"Server::SendToolDef(): Sending tool definitions: size="
+ <<s.size()<<std::endl;
+ SharedBuffer<u8> data((u8*)s.c_str(), s.size());
+ // Send as reliable
+ con.Send(peer_id, 0, data, true);
+}
+
+void Server::SendNodeDef(con::Connection &con, u16 peer_id,
+ INodeDefManager *nodedef)
+{
+ DSTACK(__FUNCTION_NAME);
+ std::ostringstream os(std::ios_base::binary);
+
+ /*
+ u16 command
+ u32 length of the next item
+ serialized NodeDefManager
+ */
+ writeU16(os, TOCLIENT_NODEDEF);
+ std::ostringstream tmp_os(std::ios::binary);
+ nodedef->serialize(tmp_os);
+ os<<serializeLongString(tmp_os.str());
+
+ // Make data buffer
+ std::string s = os.str();
+ infostream<<"Server::SendNodeDef(): Sending node definitions: size="
+ <<s.size()<<std::endl;
+ SharedBuffer<u8> data((u8*)s.c_str(), s.size());
+ // Send as reliable
+ con.Send(peer_id, 0, data, true);
+}
+
+void Server::SendCraftItemDef(con::Connection &con, u16 peer_id,
+ ICraftItemDefManager *craftitemdef)
+{
+ DSTACK(__FUNCTION_NAME);
+ std::ostringstream os(std::ios_base::binary);
+
+ /*
+ u16 command
+ u32 length of the next item
+ serialized CraftItemDefManager
+ */
+ writeU16(os, TOCLIENT_CRAFTITEMDEF);
+ std::ostringstream tmp_os(std::ios::binary);
+ craftitemdef->serialize(tmp_os);
+ os<<serializeLongString(tmp_os.str());
+
+ // Make data buffer
+ std::string s = os.str();
+ infostream<<"Server::SendCraftItemDef(): Sending craft item definitions: size="
+ <<s.size()<<std::endl;
SharedBuffer<u8> data((u8*)s.c_str(), s.size());
// Send as reliable
con.Send(peer_id, 0, data, true);
{
DSTACK(__FUNCTION_NAME);
- Player* player = m_env->getPlayer(peer_id);
+ ServerRemotePlayer* player =
+ static_cast<ServerRemotePlayer*>(m_env->getPlayer(peer_id));
assert(player);
+ player->m_inventory_not_sent = false;
+
/*
Serialize it
*/
/* Read textures */
- core::list<SendableTexture> textures;
+ // Put 5kB in one bunch (this is not accurate)
+ u32 bytes_per_bunch = 5000;
+
+ core::array< core::list<SendableTexture> > texture_bunches;
+ texture_bunches.push_back(core::list<SendableTexture>());
+
+ u32 texture_size_bunch_total = 0;
core::list<ModSpec> mods = getMods(m_modspaths);
for(core::list<ModSpec>::Iterator i = mods.begin();
i != mods.end(); i++){
fis.read(buf, 1024);
std::streamsize len = fis.gcount();
tmp_os.write(buf, len);
+ texture_size_bunch_total += len;
if(fis.eof())
break;
if(!fis.good()){
<<tname<<"\""<<std::endl;
continue;
}
- errorstream<<"Server::SendTextures(): Loaded \""
- <<tname<<"\""<<std::endl;
+ /*infostream<<"Server::SendTextures(): Loaded \""
+ <<tname<<"\""<<std::endl;*/
// Put in list
- textures.push_back(SendableTexture(tname, tpath, tmp_os.str()));
+ texture_bunches[texture_bunches.size()-1].push_back(
+ SendableTexture(tname, tpath, tmp_os.str()));
+
+ // Start next bunch if got enough data
+ if(texture_size_bunch_total >= bytes_per_bunch){
+ texture_bunches.push_back(core::list<SendableTexture>());
+ texture_size_bunch_total = 0;
+ }
}
}
- /* Create and send packet */
+ /* Create and send packets */
+
+ u32 num_bunches = texture_bunches.size();
+ for(u32 i=0; i<num_bunches; i++)
+ {
+ /*
+ u16 command
+ u16 total number of texture bunches
+ u16 index of this bunch
+ u32 number of textures in this bunch
+ for each texture {
+ u16 length of name
+ string name
+ u32 length of data
+ data
+ }
+ */
+ std::ostringstream os(std::ios_base::binary);
- /*
- u16 command
- u32 number of textures
- for each texture {
- u16 length of name
- string name
- u32 length of data
- data
+ writeU16(os, TOCLIENT_TEXTURES);
+ writeU16(os, num_bunches);
+ writeU16(os, i);
+ writeU32(os, texture_bunches[i].size());
+
+ for(core::list<SendableTexture>::Iterator
+ j = texture_bunches[i].begin();
+ j != texture_bunches[i].end(); j++){
+ os<<serializeString(j->name);
+ os<<serializeLongString(j->data);
}
- */
- std::ostringstream os(std::ios_base::binary);
-
- writeU16(os, TOCLIENT_TEXTURES);
- writeU32(os, textures.size());
-
- for(core::list<SendableTexture>::Iterator i = textures.begin();
- i != textures.end(); i++){
- os<<serializeString(i->name);
- os<<serializeLongString(i->data);
+
+ // Make data buffer
+ std::string s = os.str();
+ infostream<<"Server::SendTextures(): bunch "<<i<<"/"<<num_bunches
+ <<" textures="<<texture_bunches[i].size()
+ <<" size=" <<s.size()<<std::endl;
+ SharedBuffer<u8> data((u8*)s.c_str(), s.size());
+ // Send as reliable
+ m_con.Send(peer_id, 0, data, true);
}
-
- // Make data buffer
- std::string s = os.str();
- infostream<<"Server::SendTextures(): number of textures: "
- <<textures.size()<<", data size: "<<s.size()<<std::endl;
- SharedBuffer<u8> data((u8*)s.c_str(), s.size());
- // Send as reliable
- m_con.Send(peer_id, 0, data, true);
}
/*
void Server::RespawnPlayer(Player *player)
{
- v3f pos = findSpawnPos(m_env->getServerMap());
- player->setPosition(pos);
player->hp = 20;
+ ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
+ bool repositioned = scriptapi_on_respawnplayer(m_lua, srp);
+ if(!repositioned){
+ v3f pos = findSpawnPos(m_env->getServerMap());
+ player->setPosition(pos);
+ srp->m_last_good_position = pos;
+ srp->m_last_good_position_age = 0;
+ }
SendMovePlayer(player);
SendPlayerHP(player);
}
Player* player = m_env->getPlayer(peer_id);
assert(player);
+ ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
- /*
- Calculate crafting stuff
- */
- if(g_settings->getBool("creative_mode") == false)
+ // No crafting in creative mode
+ if(g_settings->getBool("creative_mode"))
+ return;
+
+ // Get the InventoryLists of the player in which we will operate
+ InventoryList *clist = player->inventory.getList("craft");
+ assert(clist);
+ InventoryList *rlist = player->inventory.getList("craftresult");
+ assert(rlist);
+ InventoryList *mlist = player->inventory.getList("main");
+ assert(mlist);
+
+ // If the result list is not a preview and is not empty, try to
+ // throw the item into main list
+ if(!player->craftresult_is_preview && rlist->getUsedSlots() != 0)
{
- InventoryList *clist = player->inventory.getList("craft");
- InventoryList *rlist = player->inventory.getList("craftresult");
-
- if(rlist && rlist->getUsedSlots() == 0)
- player->craftresult_is_preview = true;
+ // Grab item out of craftresult
+ InventoryItem *item = rlist->changeItem(0, NULL);
+ // Try to put in main
+ InventoryItem *leftover = mlist->addItem(item);
+ // If there are leftovers, put them back to craftresult and
+ // delete leftovers
+ delete rlist->addItem(leftover);
+ // Inventory was modified
+ srp->m_inventory_not_sent = true;
+ }
+
+ // If result list is empty, we will make it preview what would be
+ // crafted
+ if(rlist->getUsedSlots() == 0)
+ player->craftresult_is_preview = true;
+
+ // If it is a preview, clear the possible old preview in it
+ if(player->craftresult_is_preview)
+ rlist->clearItems();
- if(rlist && player->craftresult_is_preview)
- {
- rlist->clearItems();
- }
- if(clist && rlist && player->craftresult_is_preview)
- {
- InventoryItem *items[9];
- for(u16 i=0; i<9; i++)
- {
- items[i] = clist->getItem(i);
- }
-
- // Get result of crafting grid
- InventoryItem *result = craft_get_result(items, this);
- if(result)
- rlist->addItem(result);
+ // If it is a preview, find out what is the crafting result
+ // and put it in
+ if(player->craftresult_is_preview)
+ {
+ // Mangle crafting grid to an another format
+ std::vector<InventoryItem*> items;
+ for(u16 i=0; i<9; i++){
+ if(clist->getItem(i) == NULL)
+ items.push_back(NULL);
+ else
+ items.push_back(clist->getItem(i)->clone());
}
-
- } // if creative_mode == false
+ CraftPointerInput cpi(3, items);
+
+ // Find out what is crafted and add it to result item slot
+ InventoryItem *result = m_craftdef->getCraftResult(cpi, this);
+ if(result)
+ rlist->addItem(result);
+ }
}
RemoteClient* Server::getClient(u16 peer_id)
BroadcastChatMessage(msg);
}
+void Server::queueBlockEmerge(v3s16 blockpos, bool allow_generate)
+{
+ u8 flags = 0;
+ if(!allow_generate)
+ flags |= BLOCK_EMERGE_FLAG_FROMDISK;
+ m_emerge_queue.addBlock(PEER_ID_INEXISTENT, blockpos, flags);
+}
+
// IGameDef interface
// Under envlock
IToolDefManager* Server::getToolDefManager()
}
INodeDefManager* Server::getNodeDefManager()
{
- return m_nodemgr;
+ return m_nodedef;
+}
+ICraftDefManager* Server::getCraftDefManager()
+{
+ return m_craftdef;
+}
+ICraftItemDefManager* Server::getCraftItemDefManager()
+{
+ return m_craftitemdef;
}
ITextureSource* Server::getTextureSource()
{
return NULL;
}
+u16 Server::allocateUnknownNodeId(const std::string &name)
+{
+ return m_nodedef->allocateDummy(name);
+}
IWritableToolDefManager* Server::getWritableToolDefManager()
{
}
IWritableNodeDefManager* Server::getWritableNodeDefManager()
{
- return m_nodemgr;
+ return m_nodedef;
+}
+IWritableCraftDefManager* Server::getWritableCraftDefManager()
+{
+ return m_craftdef;
+}
+IWritableCraftItemDefManager* Server::getWritableCraftItemDefManager()
+{
+ return m_craftitemdef;
}
v3f findSpawnPos(ServerMap &map)
m_authmanager.setPrivs(name,
stringToPrivs(g_settings->get("default_privs")));
- /*
- Set player position
- */
+ /* Set player position */
infostream<<"Server: Finding spawn place for player \""
<<name<<"\""<<std::endl;
player = new ServerRemotePlayer(m_env, pos, peer_id, name);
- /*
- Add player to environment
- */
-
+ /* Add player to environment */
m_env->addPlayer(player);
- /*
- Add stuff to inventory
- */
-
+ /* Run scripts */
+ ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
+ scriptapi_on_newplayer(m_lua, srp);
+
+ /* Add stuff to inventory */
if(g_settings->getBool("creative_mode"))
{
// Warning: double code above
// Set creative inventory
craft_set_creative_inventory(player, this);
}
- else if(g_settings->getBool("give_initial_stuff"))
- {
- craft_give_initial_stuff(player, this);
- }
return player;