code
string | repo_name
string | path
string | language
string | license
string | size
int64 |
---|---|---|---|---|---|
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
enum ModifiedState
{
// Has not been modified.
MOD_STATE_CLEAN = 0,
MOD_RESERVED1 = 1,
// Has been modified, and will be saved when being unloaded.
MOD_STATE_WRITE_AT_UNLOAD = 2,
MOD_RESERVED3 = 3,
// Has been modified, and will be saved as soon as possible.
MOD_STATE_WRITE_NEEDED = 4,
MOD_RESERVED5 = 5,
};
| pgimeno/minetest | src/modifiedstate.h | C++ | mit | 1,117 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "nameidmapping.h"
#include "exceptions.h"
#include "util/serialize.h"
void NameIdMapping::serialize(std::ostream &os) const
{
writeU8(os, 0); // version
writeU16(os, m_id_to_name.size());
for (const auto &i : m_id_to_name) {
writeU16(os, i.first);
os << serializeString(i.second);
}
}
void NameIdMapping::deSerialize(std::istream &is)
{
int version = readU8(is);
if (version != 0)
throw SerializationError("unsupported NameIdMapping version");
u32 count = readU16(is);
m_id_to_name.clear();
m_name_to_id.clear();
for (u32 i = 0; i < count; i++) {
u16 id = readU16(is);
std::string name = deSerializeString(is);
m_id_to_name[id] = name;
m_name_to_id[name] = id;
}
}
| pgimeno/minetest | src/nameidmapping.cpp | C++ | mit | 1,486 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include <string>
#include <iostream>
#include <set>
#include <unordered_map>
#include "irrlichttypes_bloated.h"
typedef std::unordered_map<u16, std::string> IdToNameMap;
typedef std::unordered_map<std::string, u16> NameToIdMap;
class NameIdMapping
{
public:
void serialize(std::ostream &os) const;
void deSerialize(std::istream &is);
void clear()
{
m_id_to_name.clear();
m_name_to_id.clear();
}
void set(u16 id, const std::string &name)
{
m_id_to_name[id] = name;
m_name_to_id[name] = id;
}
void removeId(u16 id)
{
std::string name;
bool found = getName(id, name);
if (!found)
return;
m_id_to_name.erase(id);
m_name_to_id.erase(name);
}
void eraseName(const std::string &name)
{
u16 id;
bool found = getId(name, id);
if (!found)
return;
m_id_to_name.erase(id);
m_name_to_id.erase(name);
}
bool getName(u16 id, std::string &result) const
{
IdToNameMap::const_iterator i;
i = m_id_to_name.find(id);
if (i == m_id_to_name.end())
return false;
result = i->second;
return true;
}
bool getId(const std::string &name, u16 &result) const
{
NameToIdMap::const_iterator i;
i = m_name_to_id.find(name);
if (i == m_name_to_id.end())
return false;
result = i->second;
return true;
}
u16 size() const { return m_id_to_name.size(); }
private:
IdToNameMap m_id_to_name;
NameToIdMap m_name_to_id;
};
| pgimeno/minetest | src/nameidmapping.h | C++ | mit | 2,173 |
set(common_network_SRCS
${CMAKE_CURRENT_SOURCE_DIR}/address.cpp
${CMAKE_CURRENT_SOURCE_DIR}/connection.cpp
${CMAKE_CURRENT_SOURCE_DIR}/connectionthreads.cpp
${CMAKE_CURRENT_SOURCE_DIR}/networkpacket.cpp
${CMAKE_CURRENT_SOURCE_DIR}/serverpackethandler.cpp
${CMAKE_CURRENT_SOURCE_DIR}/serveropcodes.cpp
${CMAKE_CURRENT_SOURCE_DIR}/socket.cpp
PARENT_SCOPE
)
if (BUILD_CLIENT)
set(client_network_SRCS
${CMAKE_CURRENT_SOURCE_DIR}/clientopcodes.cpp
${CMAKE_CURRENT_SOURCE_DIR}/clientpackethandler.cpp
PARENT_SCOPE
)
endif()
# Haiku networking support
if(HAIKU)
set(PLATFORM_LIBS -lnetwork ${PLATFORM_LIBS})
endif()
| pgimeno/minetest | src/network/CMakeLists.txt | Text | mit | 628 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "address.h"
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <sstream>
#include <iomanip>
#include "network/networkexceptions.h"
#include "util/string.h"
#include "util/numeric.h"
#include "constants.h"
#include "debug.h"
#include "settings.h"
#include "log.h"
#ifdef _WIN32
// Without this some of the network functions are not found on mingw
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#define LAST_SOCKET_ERR() WSAGetLastError()
typedef SOCKET socket_t;
typedef int socklen_t;
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#define LAST_SOCKET_ERR() (errno)
typedef int socket_t;
#endif
/*
Address
*/
Address::Address()
{
memset(&m_address, 0, sizeof(m_address));
}
Address::Address(u32 address, u16 port)
{
memset(&m_address, 0, sizeof(m_address));
setAddress(address);
setPort(port);
}
Address::Address(u8 a, u8 b, u8 c, u8 d, u16 port)
{
memset(&m_address, 0, sizeof(m_address));
setAddress(a, b, c, d);
setPort(port);
}
Address::Address(const IPv6AddressBytes *ipv6_bytes, u16 port)
{
memset(&m_address, 0, sizeof(m_address));
setAddress(ipv6_bytes);
setPort(port);
}
// Equality (address family, address and port must be equal)
bool Address::operator==(const Address &address)
{
if (address.m_addr_family != m_addr_family || address.m_port != m_port)
return false;
if (m_addr_family == AF_INET) {
return m_address.ipv4.sin_addr.s_addr ==
address.m_address.ipv4.sin_addr.s_addr;
}
if (m_addr_family == AF_INET6) {
return memcmp(m_address.ipv6.sin6_addr.s6_addr,
address.m_address.ipv6.sin6_addr.s6_addr, 16) == 0;
}
return false;
}
bool Address::operator!=(const Address &address)
{
return !(*this == address);
}
void Address::Resolve(const char *name)
{
if (!name || name[0] == 0) {
if (m_addr_family == AF_INET) {
setAddress((u32)0);
} else if (m_addr_family == AF_INET6) {
setAddress((IPv6AddressBytes *)0);
}
return;
}
struct addrinfo *resolved, hints;
memset(&hints, 0, sizeof(hints));
// Setup hints
hints.ai_socktype = 0;
hints.ai_protocol = 0;
hints.ai_flags = 0;
if (g_settings->getBool("enable_ipv6")) {
// AF_UNSPEC allows both IPv6 and IPv4 addresses to be returned
hints.ai_family = AF_UNSPEC;
} else {
hints.ai_family = AF_INET;
}
// Do getaddrinfo()
int e = getaddrinfo(name, NULL, &hints, &resolved);
if (e != 0)
throw ResolveError(gai_strerror(e));
// Copy data
if (resolved->ai_family == AF_INET) {
struct sockaddr_in *t = (struct sockaddr_in *)resolved->ai_addr;
m_addr_family = AF_INET;
m_address.ipv4 = *t;
} else if (resolved->ai_family == AF_INET6) {
struct sockaddr_in6 *t = (struct sockaddr_in6 *)resolved->ai_addr;
m_addr_family = AF_INET6;
m_address.ipv6 = *t;
} else {
freeaddrinfo(resolved);
throw ResolveError("");
}
freeaddrinfo(resolved);
}
// IP address -> textual representation
std::string Address::serializeString() const
{
// windows XP doesnt have inet_ntop, maybe use better func
#ifdef _WIN32
if (m_addr_family == AF_INET) {
u8 a, b, c, d;
u32 addr;
addr = ntohl(m_address.ipv4.sin_addr.s_addr);
a = (addr & 0xFF000000) >> 24;
b = (addr & 0x00FF0000) >> 16;
c = (addr & 0x0000FF00) >> 8;
d = (addr & 0x000000FF);
return itos(a) + "." + itos(b) + "." + itos(c) + "." + itos(d);
} else if (m_addr_family == AF_INET6) {
std::ostringstream os;
for (int i = 0; i < 16; i += 2) {
u16 section = (m_address.ipv6.sin6_addr.s6_addr[i] << 8) |
(m_address.ipv6.sin6_addr.s6_addr[i + 1]);
os << std::hex << section;
if (i < 14)
os << ":";
}
return os.str();
} else
return std::string("");
#else
char str[INET6_ADDRSTRLEN];
if (inet_ntop(m_addr_family,
(m_addr_family == AF_INET)
? (void *)&(m_address.ipv4.sin_addr)
: (void *)&(m_address.ipv6.sin6_addr),
str, INET6_ADDRSTRLEN) == NULL) {
return std::string("");
}
return std::string(str);
#endif
}
struct sockaddr_in Address::getAddress() const
{
return m_address.ipv4; // NOTE: NO PORT INCLUDED, use getPort()
}
struct sockaddr_in6 Address::getAddress6() const
{
return m_address.ipv6; // NOTE: NO PORT INCLUDED, use getPort()
}
u16 Address::getPort() const
{
return m_port;
}
int Address::getFamily() const
{
return m_addr_family;
}
bool Address::isIPv6() const
{
return m_addr_family == AF_INET6;
}
bool Address::isZero() const
{
if (m_addr_family == AF_INET) {
return m_address.ipv4.sin_addr.s_addr == 0;
}
if (m_addr_family == AF_INET6) {
static const char zero[16] = {0};
return memcmp(m_address.ipv6.sin6_addr.s6_addr, zero, 16) == 0;
}
return false;
}
void Address::setAddress(u32 address)
{
m_addr_family = AF_INET;
m_address.ipv4.sin_family = AF_INET;
m_address.ipv4.sin_addr.s_addr = htonl(address);
}
void Address::setAddress(u8 a, u8 b, u8 c, u8 d)
{
m_addr_family = AF_INET;
m_address.ipv4.sin_family = AF_INET;
u32 addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
m_address.ipv4.sin_addr.s_addr = addr;
}
void Address::setAddress(const IPv6AddressBytes *ipv6_bytes)
{
m_addr_family = AF_INET6;
m_address.ipv6.sin6_family = AF_INET6;
if (ipv6_bytes)
memcpy(m_address.ipv6.sin6_addr.s6_addr, ipv6_bytes->bytes, 16);
else
memset(m_address.ipv6.sin6_addr.s6_addr, 0, 16);
}
void Address::setPort(u16 port)
{
m_port = port;
}
void Address::print(std::ostream *s) const
{
if (m_addr_family == AF_INET6)
*s << "[" << serializeString() << "]:" << m_port;
else
*s << serializeString() << ":" << m_port;
}
bool Address::isLocalhost() const
{
if (isIPv6()) {
static const unsigned char localhost_bytes[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
static const unsigned char mapped_ipv4_localhost[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x7f, 0, 0, 0};
auto addr = m_address.ipv6.sin6_addr.s6_addr;
return memcmp(addr, localhost_bytes, 16) == 0 ||
memcmp(addr, mapped_ipv4_localhost, 13) == 0;
}
return (m_address.ipv4.sin_addr.s_addr & 0xFF) == 0x7f;
}
| pgimeno/minetest | src/network/address.cpp | C++ | mit | 6,985 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#ifdef _WIN32
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <netinet/in.h>
#include <sys/socket.h>
#endif
#include <ostream>
#include <cstring>
#include "irrlichttypes.h"
#include "networkexceptions.h"
class IPv6AddressBytes
{
public:
u8 bytes[16];
IPv6AddressBytes() { memset(bytes, 0, 16); }
};
class Address
{
public:
Address();
Address(u32 address, u16 port);
Address(u8 a, u8 b, u8 c, u8 d, u16 port);
Address(const IPv6AddressBytes *ipv6_bytes, u16 port);
bool operator==(const Address &address);
bool operator!=(const Address &address);
// Resolve() may throw ResolveError (address is unchanged in this case)
void Resolve(const char *name);
struct sockaddr_in getAddress() const;
unsigned short getPort() const;
void setAddress(u32 address);
void setAddress(u8 a, u8 b, u8 c, u8 d);
void setAddress(const IPv6AddressBytes *ipv6_bytes);
struct sockaddr_in6 getAddress6() const;
int getFamily() const;
bool isIPv6() const;
bool isZero() const;
void setPort(unsigned short port);
void print(std::ostream *s) const;
std::string serializeString() const;
bool isLocalhost() const;
private:
unsigned int m_addr_family = 0;
union
{
struct sockaddr_in ipv4;
struct sockaddr_in6 ipv6;
} m_address;
u16 m_port = 0; // Port is separate from sockaddr structures
};
| pgimeno/minetest | src/network/address.h | C++ | mit | 2,184 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "clientopcodes.h"
const static ToClientCommandHandler null_command_handler = {"TOCLIENT_NULL", TOCLIENT_STATE_ALL, &Client::handleCommand_Null};
const ToClientCommandHandler toClientCommandTable[TOCLIENT_NUM_MSG_TYPES] =
{
null_command_handler, // 0x00 (never use this)
null_command_handler, // 0x01
{ "TOCLIENT_HELLO", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_Hello }, // 0x02
{ "TOCLIENT_AUTH_ACCEPT", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_AuthAccept }, // 0x03
{ "TOCLIENT_ACCEPT_SUDO_MODE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_AcceptSudoMode}, // 0x04
{ "TOCLIENT_DENY_SUDO_MODE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_DenySudoMode}, // 0x05
null_command_handler, // 0x06
null_command_handler, // 0x07
null_command_handler, // 0x08
null_command_handler, // 0x09
{ "TOCLIENT_ACCESS_DENIED", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_AccessDenied }, // 0x0A
null_command_handler, // 0x0B
null_command_handler, // 0x0C
null_command_handler, // 0x0D
null_command_handler, // 0x0E
null_command_handler, // 0x0F
null_command_handler, // 0x10
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
{ "TOCLIENT_BLOCKDATA", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_BlockData }, // 0x20
{ "TOCLIENT_ADDNODE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_AddNode }, // 0x21
{ "TOCLIENT_REMOVENODE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_RemoveNode }, // 0x22
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
{ "TOCLIENT_INVENTORY", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Inventory }, // 0x27
null_command_handler,
{ "TOCLIENT_TIME_OF_DAY", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_TimeOfDay }, // 0x29
{ "TOCLIENT_CSM_RESTRICTION_FLAGS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_CSMRestrictionFlags }, // 0x2A
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
{ "TOCLIENT_CHAT_MESSAGE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ChatMessage }, // 0x2F
null_command_handler, // 0x30
{ "TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ActiveObjectRemoveAdd }, // 0x31
{ "TOCLIENT_ACTIVE_OBJECT_MESSAGES", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ActiveObjectMessages }, // 0x32
{ "TOCLIENT_HP", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HP }, // 0x33
{ "TOCLIENT_MOVE_PLAYER", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_MovePlayer }, // 0x34
{ "TOCLIENT_ACCESS_DENIED_LEGACY", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_AccessDenied }, // 0x35
null_command_handler,
{ "TOCLIENT_DEATHSCREEN", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_DeathScreen }, // 0x37
{ "TOCLIENT_MEDIA", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Media }, // 0x38
null_command_handler,
{ "TOCLIENT_NODEDEF", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_NodeDef }, // 0x3a
null_command_handler,
{ "TOCLIENT_ANNOUNCE_MEDIA", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_AnnounceMedia }, // 0x3c
{ "TOCLIENT_ITEMDEF", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ItemDef }, // 0x3d
null_command_handler,
{ "TOCLIENT_PLAY_SOUND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_PlaySound }, // 0x3f
{ "TOCLIENT_STOP_SOUND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_StopSound }, // 0x40
{ "TOCLIENT_PRIVILEGES", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Privileges }, // 0x41
{ "TOCLIENT_INVENTORY_FORMSPEC", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_InventoryFormSpec }, // 0x42
{ "TOCLIENT_DETACHED_INVENTORY", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_DetachedInventory }, // 0x43
{ "TOCLIENT_SHOW_FORMSPEC", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ShowFormSpec }, // 0x44
{ "TOCLIENT_MOVEMENT", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Movement }, // 0x45
{ "TOCLIENT_SPAWN_PARTICLE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_SpawnParticle }, // 0x46
{ "TOCLIENT_ADD_PARTICLESPAWNER", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_AddParticleSpawner }, // 0x47
null_command_handler,
{ "TOCLIENT_HUDADD", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudAdd }, // 0x49
{ "TOCLIENT_HUDRM", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudRemove }, // 0x4a
{ "TOCLIENT_HUDCHANGE", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudChange }, // 0x4b
{ "TOCLIENT_HUD_SET_FLAGS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetFlags }, // 0x4c
{ "TOCLIENT_HUD_SET_PARAM", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetParam }, // 0x4d
{ "TOCLIENT_BREATH", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_Breath }, // 0x4e
{ "TOCLIENT_SET_SKY", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_HudSetSky }, // 0x4f
{ "TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_OverrideDayNightRatio }, // 0x50
{ "TOCLIENT_LOCAL_PLAYER_ANIMATIONS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_LocalPlayerAnimations }, // 0x51
{ "TOCLIENT_EYE_OFFSET", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_EyeOffset }, // 0x52
{ "TOCLIENT_DELETE_PARTICLESPAWNER", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_DeleteParticleSpawner }, // 0x53
{ "TOCLIENT_CLOUD_PARAMS", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_CloudParams }, // 0x54
{ "TOCLIENT_FADE_SOUND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_FadeSound }, // 0x55
{ "TOCLIENT_UPDATE_PLAYER_LIST", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_UpdatePlayerList }, // 0x56
{ "TOCLIENT_MODCHANNEL_MSG", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ModChannelMsg }, // 0x57
{ "TOCLIENT_MODCHANNEL_SIGNAL", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_ModChannelSignal }, // 0x58
{ "TOCLIENT_NODEMETA_CHANGED", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_NodemetaChanged }, // 0x59
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
null_command_handler,
{ "TOCLIENT_SRP_BYTES_S_B", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_SrpBytesSandB }, // 0x60
{ "TOCLIENT_FORMSPEC_PREPEND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_FormspecPrepend }, // 0x61,
};
const static ServerCommandFactory null_command_factory = { "TOSERVER_NULL", 0, false };
const ServerCommandFactory serverCommandFactoryTable[TOSERVER_NUM_MSG_TYPES] =
{
null_command_factory, // 0x00
null_command_factory, // 0x01
{ "TOSERVER_INIT", 1, false }, // 0x02
null_command_factory, // 0x03
null_command_factory, // 0x04
null_command_factory, // 0x05
null_command_factory, // 0x06
null_command_factory, // 0x07
null_command_factory, // 0x08
null_command_factory, // 0x09
null_command_factory, // 0x0a
null_command_factory, // 0x0b
null_command_factory, // 0x0c
null_command_factory, // 0x0d
null_command_factory, // 0x0e
null_command_factory, // 0x0F
null_command_factory, // 0x10
{ "TOSERVER_INIT2", 1, true }, // 0x11
null_command_factory, // 0x12
null_command_factory, // 0x13
null_command_factory, // 0x14
null_command_factory, // 0x15
null_command_factory, // 0x16
{ "TOSERVER_MODCHANNEL_JOIN", 0, true }, // 0x17
{ "TOSERVER_MODCHANNEL_LEAVE", 0, true }, // 0x18
{ "TOSERVER_MODCHANNEL_MSG", 0, true }, // 0x19
null_command_factory, // 0x1a
null_command_factory, // 0x1b
null_command_factory, // 0x1c
null_command_factory, // 0x1d
null_command_factory, // 0x1e
null_command_factory, // 0x1f
null_command_factory, // 0x20
null_command_factory, // 0x21
null_command_factory, // 0x22
{ "TOSERVER_PLAYERPOS", 0, false }, // 0x23
{ "TOSERVER_GOTBLOCKS", 2, true }, // 0x24
{ "TOSERVER_DELETEDBLOCKS", 2, true }, // 0x25
null_command_factory, // 0x26
null_command_factory, // 0x27
null_command_factory, // 0x28
null_command_factory, // 0x29
null_command_factory, // 0x2a
null_command_factory, // 0x2b
null_command_factory, // 0x2c
null_command_factory, // 0x2d
null_command_factory, // 0x2e
null_command_factory, // 0x2f
null_command_factory, // 0x30
{ "TOSERVER_INVENTORY_ACTION", 0, true }, // 0x31
{ "TOSERVER_CHAT_MESSAGE", 0, true }, // 0x32
null_command_factory, // 0x33
null_command_factory, // 0x34
{ "TOSERVER_DAMAGE", 0, true }, // 0x35
null_command_factory, // 0x36
{ "TOSERVER_PLAYERITEM", 0, true }, // 0x37
{ "TOSERVER_RESPAWN", 0, true }, // 0x38
{ "TOSERVER_INTERACT", 0, true }, // 0x39
{ "TOSERVER_REMOVED_SOUNDS", 1, true }, // 0x3a
{ "TOSERVER_NODEMETA_FIELDS", 0, true }, // 0x3b
{ "TOSERVER_INVENTORY_FIELDS", 0, true }, // 0x3c
null_command_factory, // 0x3d
null_command_factory, // 0x3e
null_command_factory, // 0x3f
{ "TOSERVER_REQUEST_MEDIA", 1, true }, // 0x40
null_command_factory, // 0x41
{ "TOSERVER_BREATH", 0, true }, // 0x42 old TOSERVER_BREATH. Ignored by servers
{ "TOSERVER_CLIENT_READY", 0, true }, // 0x43
null_command_factory, // 0x44
null_command_factory, // 0x45
null_command_factory, // 0x46
null_command_factory, // 0x47
null_command_factory, // 0x48
null_command_factory, // 0x49
null_command_factory, // 0x4a
null_command_factory, // 0x4b
null_command_factory, // 0x4c
null_command_factory, // 0x4d
null_command_factory, // 0x4e
null_command_factory, // 0x4f
{ "TOSERVER_FIRST_SRP", 1, true }, // 0x50
{ "TOSERVER_SRP_BYTES_A", 1, true }, // 0x51
{ "TOSERVER_SRP_BYTES_M", 1, true }, // 0x52
};
| pgimeno/minetest | src/network/clientopcodes.cpp | C++ | mit | 11,255 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "client/client.h"
#include "networkprotocol.h"
class NetworkPacket;
enum ToClientConnectionState {
TOCLIENT_STATE_NOT_CONNECTED,
TOCLIENT_STATE_CONNECTED,
TOCLIENT_STATE_ALL,
};
struct ToClientCommandHandler
{
const char* name;
ToClientConnectionState state;
void (Client::*handler)(NetworkPacket* pkt);
};
struct ServerCommandFactory
{
const char* name;
u8 channel;
bool reliable;
};
extern const ToClientCommandHandler toClientCommandTable[TOCLIENT_NUM_MSG_TYPES];
extern const ServerCommandFactory serverCommandFactoryTable[TOSERVER_NUM_MSG_TYPES];
| pgimeno/minetest | src/network/clientopcodes.h | C++ | mit | 1,453 |
/*
Minetest
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "client/client.h"
#include "util/base64.h"
#include "chatmessage.h"
#include "client/clientmedia.h"
#include "log.h"
#include "map.h"
#include "mapsector.h"
#include "client/minimap.h"
#include "modchannels.h"
#include "nodedef.h"
#include "serialization.h"
#include "server.h"
#include "util/strfnd.h"
#include "client/clientevent.h"
#include "client/sound.h"
#include "network/clientopcodes.h"
#include "network/connection.h"
#include "script/scripting_client.h"
#include "util/serialize.h"
#include "util/srp.h"
#include "tileanimation.h"
#include "gettext.h"
void Client::handleCommand_Deprecated(NetworkPacket* pkt)
{
infostream << "Got deprecated command "
<< toClientCommandTable[pkt->getCommand()].name << " from peer "
<< pkt->getPeerId() << "!" << std::endl;
}
void Client::handleCommand_Hello(NetworkPacket* pkt)
{
if (pkt->getSize() < 1)
return;
u8 serialization_ver;
u16 proto_ver;
u16 compression_mode;
u32 auth_mechs;
std::string username_legacy; // for case insensitivity
*pkt >> serialization_ver >> compression_mode >> proto_ver
>> auth_mechs >> username_legacy;
// Chose an auth method we support
AuthMechanism chosen_auth_mechanism = choseAuthMech(auth_mechs);
infostream << "Client: TOCLIENT_HELLO received with "
<< "serialization_ver=" << (u32)serialization_ver
<< ", auth_mechs=" << auth_mechs
<< ", proto_ver=" << proto_ver
<< ", compression_mode=" << compression_mode
<< ". Doing auth with mech " << chosen_auth_mechanism << std::endl;
if (!ser_ver_supported(serialization_ver)) {
infostream << "Client: TOCLIENT_HELLO: Server sent "
<< "unsupported ser_fmt_ver"<< std::endl;
return;
}
m_server_ser_ver = serialization_ver;
m_proto_ver = proto_ver;
//TODO verify that username_legacy matches sent username, only
// differs in casing (make both uppercase and compare)
// This is only neccessary though when we actually want to add casing support
if (m_chosen_auth_mech != AUTH_MECHANISM_NONE) {
// we recieved a TOCLIENT_HELLO while auth was already going on
errorstream << "Client: TOCLIENT_HELLO while auth was already going on"
<< "(chosen_mech=" << m_chosen_auth_mech << ")." << std::endl;
if (m_chosen_auth_mech == AUTH_MECHANISM_SRP ||
m_chosen_auth_mech == AUTH_MECHANISM_LEGACY_PASSWORD) {
srp_user_delete((SRPUser *) m_auth_data);
m_auth_data = 0;
}
}
// Authenticate using that method, or abort if there wasn't any method found
if (chosen_auth_mechanism != AUTH_MECHANISM_NONE) {
if (chosen_auth_mechanism == AUTH_MECHANISM_FIRST_SRP &&
!m_simple_singleplayer_mode &&
!getServerAddress().isLocalhost() &&
g_settings->getBool("enable_register_confirmation")) {
promptConfirmRegistration(chosen_auth_mechanism);
} else {
startAuth(chosen_auth_mechanism);
}
} else {
m_chosen_auth_mech = AUTH_MECHANISM_NONE;
m_access_denied = true;
m_access_denied_reason = "Unknown";
m_con->Disconnect();
}
}
void Client::handleCommand_AuthAccept(NetworkPacket* pkt)
{
deleteAuthData();
v3f playerpos;
*pkt >> playerpos >> m_map_seed >> m_recommended_send_interval
>> m_sudo_auth_methods;
playerpos -= v3f(0, BS / 2, 0);
// Set player position
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
player->setPosition(playerpos);
infostream << "Client: received map seed: " << m_map_seed << std::endl;
infostream << "Client: received recommended send interval "
<< m_recommended_send_interval<<std::endl;
// Reply to server
std::string lang = gettext("LANG_CODE");
if (lang == "LANG_CODE")
lang = "";
NetworkPacket resp_pkt(TOSERVER_INIT2, sizeof(u16) + lang.size());
resp_pkt << lang;
Send(&resp_pkt);
m_state = LC_Init;
}
void Client::handleCommand_AcceptSudoMode(NetworkPacket* pkt)
{
deleteAuthData();
m_password = m_new_password;
verbosestream << "Client: Recieved TOCLIENT_ACCEPT_SUDO_MODE." << std::endl;
// send packet to actually set the password
startAuth(AUTH_MECHANISM_FIRST_SRP);
// reset again
m_chosen_auth_mech = AUTH_MECHANISM_NONE;
}
void Client::handleCommand_DenySudoMode(NetworkPacket* pkt)
{
ChatMessage *chatMessage = new ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
L"Password change denied. Password NOT changed.");
pushToChatQueue(chatMessage);
// reset everything and be sad
deleteAuthData();
}
void Client::handleCommand_AccessDenied(NetworkPacket* pkt)
{
// The server didn't like our password. Note, this needs
// to be processed even if the serialisation format has
// not been agreed yet, the same as TOCLIENT_INIT.
m_access_denied = true;
m_access_denied_reason = "Unknown";
if (pkt->getCommand() != TOCLIENT_ACCESS_DENIED) {
// 13/03/15 Legacy code from 0.4.12 and lesser but is still used
// in some places of the server code
if (pkt->getSize() >= 2) {
std::wstring wide_reason;
*pkt >> wide_reason;
m_access_denied_reason = wide_to_utf8(wide_reason);
}
return;
}
if (pkt->getSize() < 1)
return;
u8 denyCode = SERVER_ACCESSDENIED_UNEXPECTED_DATA;
*pkt >> denyCode;
if (denyCode == SERVER_ACCESSDENIED_SHUTDOWN ||
denyCode == SERVER_ACCESSDENIED_CRASH) {
*pkt >> m_access_denied_reason;
if (m_access_denied_reason.empty()) {
m_access_denied_reason = accessDeniedStrings[denyCode];
}
u8 reconnect;
*pkt >> reconnect;
m_access_denied_reconnect = reconnect & 1;
} else if (denyCode == SERVER_ACCESSDENIED_CUSTOM_STRING) {
*pkt >> m_access_denied_reason;
} else if (denyCode < SERVER_ACCESSDENIED_MAX) {
m_access_denied_reason = accessDeniedStrings[denyCode];
} else {
// Allow us to add new error messages to the
// protocol without raising the protocol version, if we want to.
// Until then (which may be never), this is outside
// of the defined protocol.
*pkt >> m_access_denied_reason;
if (m_access_denied_reason.empty()) {
m_access_denied_reason = "Unknown";
}
}
}
void Client::handleCommand_RemoveNode(NetworkPacket* pkt)
{
if (pkt->getSize() < 6)
return;
v3s16 p;
*pkt >> p;
removeNode(p);
}
void Client::handleCommand_AddNode(NetworkPacket* pkt)
{
if (pkt->getSize() < 6 + MapNode::serializedLength(m_server_ser_ver))
return;
v3s16 p;
*pkt >> p;
MapNode n;
n.deSerialize(pkt->getU8Ptr(6), m_server_ser_ver);
bool remove_metadata = true;
u32 index = 6 + MapNode::serializedLength(m_server_ser_ver);
if ((pkt->getSize() >= index + 1) && pkt->getU8(index)) {
remove_metadata = false;
}
addNode(p, n, remove_metadata);
}
void Client::handleCommand_NodemetaChanged(NetworkPacket *pkt)
{
if (pkt->getSize() < 1)
return;
std::istringstream is(pkt->readLongString(), std::ios::binary);
std::stringstream sstr;
decompressZlib(is, sstr);
NodeMetadataList meta_updates_list(false);
meta_updates_list.deSerialize(sstr, m_itemdef, true);
Map &map = m_env.getMap();
for (NodeMetadataMap::const_iterator i = meta_updates_list.begin();
i != meta_updates_list.end(); ++i) {
v3s16 pos = i->first;
if (map.isValidPosition(pos) &&
map.setNodeMetadata(pos, i->second))
continue; // Prevent from deleting metadata
// Meta couldn't be set, unused metadata
delete i->second;
}
}
void Client::handleCommand_BlockData(NetworkPacket* pkt)
{
// Ignore too small packet
if (pkt->getSize() < 6)
return;
v3s16 p;
*pkt >> p;
std::string datastring(pkt->getString(6), pkt->getSize() - 6);
std::istringstream istr(datastring, std::ios_base::binary);
MapSector *sector;
MapBlock *block;
v2s16 p2d(p.X, p.Z);
sector = m_env.getMap().emergeSector(p2d);
assert(sector->getPos() == p2d);
block = sector->getBlockNoCreateNoEx(p.Y);
if (block) {
/*
Update an existing block
*/
block->deSerialize(istr, m_server_ser_ver, false);
block->deSerializeNetworkSpecific(istr);
}
else {
/*
Create a new block
*/
block = new MapBlock(&m_env.getMap(), p, this);
block->deSerialize(istr, m_server_ser_ver, false);
block->deSerializeNetworkSpecific(istr);
sector->insertBlock(block);
}
if (m_localdb) {
ServerMap::saveBlock(block, m_localdb);
}
/*
Add it to mesh update queue and set it to be acknowledged after update.
*/
addUpdateMeshTaskWithEdge(p, true);
}
void Client::handleCommand_Inventory(NetworkPacket* pkt)
{
if (pkt->getSize() < 1)
return;
std::string datastring(pkt->getString(0), pkt->getSize());
std::istringstream is(datastring, std::ios_base::binary);
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
player->inventory.deSerialize(is);
m_inventory_updated = true;
delete m_inventory_from_server;
m_inventory_from_server = new Inventory(player->inventory);
m_inventory_from_server_age = 0.0;
}
void Client::handleCommand_TimeOfDay(NetworkPacket* pkt)
{
if (pkt->getSize() < 2)
return;
u16 time_of_day;
*pkt >> time_of_day;
time_of_day = time_of_day % 24000;
float time_speed = 0;
if (pkt->getSize() >= 2 + 4) {
*pkt >> time_speed;
}
else {
// Old message; try to approximate speed of time by ourselves
float time_of_day_f = (float)time_of_day / 24000.0f;
float tod_diff_f = 0;
if (time_of_day_f < 0.2 && m_last_time_of_day_f > 0.8)
tod_diff_f = time_of_day_f - m_last_time_of_day_f + 1.0f;
else
tod_diff_f = time_of_day_f - m_last_time_of_day_f;
m_last_time_of_day_f = time_of_day_f;
float time_diff = m_time_of_day_update_timer;
m_time_of_day_update_timer = 0;
if (m_time_of_day_set) {
time_speed = (3600.0f * 24.0f) * tod_diff_f / time_diff;
infostream << "Client: Measured time_of_day speed (old format): "
<< time_speed << " tod_diff_f=" << tod_diff_f
<< " time_diff=" << time_diff << std::endl;
}
}
// Update environment
m_env.setTimeOfDay(time_of_day);
m_env.setTimeOfDaySpeed(time_speed);
m_time_of_day_set = true;
u32 dr = m_env.getDayNightRatio();
infostream << "Client: time_of_day=" << time_of_day
<< " time_speed=" << time_speed
<< " dr=" << dr << std::endl;
}
void Client::handleCommand_ChatMessage(NetworkPacket *pkt)
{
/*
u8 version
u8 message_type
u16 sendername length
wstring sendername
u16 length
wstring message
*/
ChatMessage *chatMessage = new ChatMessage();
u8 version, message_type;
*pkt >> version >> message_type;
if (version != 1 || message_type >= CHATMESSAGE_TYPE_MAX) {
delete chatMessage;
return;
}
u64 timestamp;
*pkt >> chatMessage->sender >> chatMessage->message >> timestamp;
chatMessage->timestamp = static_cast<std::time_t>(timestamp);
chatMessage->type = (ChatMessageType) message_type;
// @TODO send this to CSM using ChatMessage object
if (moddingEnabled() && m_script->on_receiving_message(
wide_to_utf8(chatMessage->message))) {
// Message was consumed by CSM and should not be handled by client
delete chatMessage;
} else {
pushToChatQueue(chatMessage);
}
}
void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt)
{
/*
u16 count of removed objects
for all removed objects {
u16 id
}
u16 count of added objects
for all added objects {
u16 id
u8 type
u32 initialization data length
string initialization data
}
*/
try {
u8 type;
u16 removed_count, added_count, id;
// Read removed objects
*pkt >> removed_count;
for (u16 i = 0; i < removed_count; i++) {
*pkt >> id;
m_env.removeActiveObject(id);
}
// Read added objects
*pkt >> added_count;
for (u16 i = 0; i < added_count; i++) {
*pkt >> id >> type;
m_env.addActiveObject(id, type, pkt->readLongString());
}
} catch (PacketError &e) {
infostream << "handleCommand_ActiveObjectRemoveAdd: " << e.what()
<< ". The packet is unreliable, ignoring" << std::endl;
}
}
void Client::handleCommand_ActiveObjectMessages(NetworkPacket* pkt)
{
/*
for all objects
{
u16 id
u16 message length
string message
}
*/
std::string datastring(pkt->getString(0), pkt->getSize());
std::istringstream is(datastring, std::ios_base::binary);
try {
while (is.good()) {
u16 id = readU16(is);
if (!is.good())
break;
std::string message = deSerializeString(is);
// Pass on to the environment
m_env.processActiveObjectMessage(id, message);
}
} catch (SerializationError &e) {
errorstream << "Client::handleCommand_ActiveObjectMessages: "
<< "caught SerializationError: " << e.what() << std::endl;
}
}
void Client::handleCommand_Movement(NetworkPacket* pkt)
{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
float mad, maa, maf, msw, mscr, msf, mscl, msj, lf, lfs, ls, g;
*pkt >> mad >> maa >> maf >> msw >> mscr >> msf >> mscl >> msj
>> lf >> lfs >> ls >> g;
player->movement_acceleration_default = mad * BS;
player->movement_acceleration_air = maa * BS;
player->movement_acceleration_fast = maf * BS;
player->movement_speed_walk = msw * BS;
player->movement_speed_crouch = mscr * BS;
player->movement_speed_fast = msf * BS;
player->movement_speed_climb = mscl * BS;
player->movement_speed_jump = msj * BS;
player->movement_liquid_fluidity = lf * BS;
player->movement_liquid_fluidity_smooth = lfs * BS;
player->movement_liquid_sink = ls * BS;
player->movement_gravity = g * BS;
}
void Client::handleCommand_HP(NetworkPacket* pkt)
{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
u16 oldhp = player->hp;
u16 hp;
*pkt >> hp;
player->hp = hp;
if (moddingEnabled()) {
m_script->on_hp_modification(hp);
}
if (hp < oldhp) {
// Add to ClientEvent queue
ClientEvent *event = new ClientEvent();
event->type = CE_PLAYER_DAMAGE;
event->player_damage.amount = oldhp - hp;
m_client_event_queue.push(event);
}
}
void Client::handleCommand_Breath(NetworkPacket* pkt)
{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
u16 breath;
*pkt >> breath;
player->setBreath(breath);
}
void Client::handleCommand_MovePlayer(NetworkPacket* pkt)
{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
v3f pos;
f32 pitch, yaw;
*pkt >> pos >> pitch >> yaw;
player->setPosition(pos);
infostream << "Client got TOCLIENT_MOVE_PLAYER"
<< " pos=(" << pos.X << "," << pos.Y << "," << pos.Z << ")"
<< " pitch=" << pitch
<< " yaw=" << yaw
<< std::endl;
/*
Add to ClientEvent queue.
This has to be sent to the main program because otherwise
it would just force the pitch and yaw values to whatever
the camera points to.
*/
ClientEvent *event = new ClientEvent();
event->type = CE_PLAYER_FORCE_MOVE;
event->player_force_move.pitch = pitch;
event->player_force_move.yaw = yaw;
m_client_event_queue.push(event);
}
void Client::handleCommand_DeathScreen(NetworkPacket* pkt)
{
bool set_camera_point_target;
v3f camera_point_target;
*pkt >> set_camera_point_target;
*pkt >> camera_point_target;
ClientEvent *event = new ClientEvent();
event->type = CE_DEATHSCREEN;
event->deathscreen.set_camera_point_target = set_camera_point_target;
event->deathscreen.camera_point_target_x = camera_point_target.X;
event->deathscreen.camera_point_target_y = camera_point_target.Y;
event->deathscreen.camera_point_target_z = camera_point_target.Z;
m_client_event_queue.push(event);
}
void Client::handleCommand_AnnounceMedia(NetworkPacket* pkt)
{
u16 num_files;
*pkt >> num_files;
infostream << "Client: Received media announcement: packet size: "
<< pkt->getSize() << std::endl;
if (m_media_downloader == NULL ||
m_media_downloader->isStarted()) {
const char *problem = m_media_downloader ?
"we already saw another announcement" :
"all media has been received already";
errorstream << "Client: Received media announcement but "
<< problem << "! "
<< " files=" << num_files
<< " size=" << pkt->getSize() << std::endl;
return;
}
// Mesh update thread must be stopped while
// updating content definitions
sanity_check(!m_mesh_update_thread.isRunning());
for (u16 i = 0; i < num_files; i++) {
std::string name, sha1_base64;
*pkt >> name >> sha1_base64;
std::string sha1_raw = base64_decode(sha1_base64);
m_media_downloader->addFile(name, sha1_raw);
}
try {
std::string str;
*pkt >> str;
Strfnd sf(str);
while(!sf.at_end()) {
std::string baseurl = trim(sf.next(","));
if (!baseurl.empty())
m_media_downloader->addRemoteServer(baseurl);
}
}
catch(SerializationError& e) {
// not supported by server or turned off
}
m_media_downloader->step(this);
}
void Client::handleCommand_Media(NetworkPacket* pkt)
{
/*
u16 command
u16 total number of file bunches
u16 index of this bunch
u32 number of files in this bunch
for each file {
u16 length of name
string name
u32 length of data
data
}
*/
u16 num_bunches;
u16 bunch_i;
u32 num_files;
*pkt >> num_bunches >> bunch_i >> num_files;
infostream << "Client: Received files: bunch " << bunch_i << "/"
<< num_bunches << " files=" << num_files
<< " size=" << pkt->getSize() << std::endl;
if (num_files == 0)
return;
if (!m_media_downloader || !m_media_downloader->isStarted()) {
const char *problem = m_media_downloader ?
"media has not been requested" :
"all media has been received already";
errorstream << "Client: Received media but "
<< problem << "! "
<< " bunch " << bunch_i << "/" << num_bunches
<< " files=" << num_files
<< " size=" << pkt->getSize() << std::endl;
return;
}
// Mesh update thread must be stopped while
// updating content definitions
sanity_check(!m_mesh_update_thread.isRunning());
for (u32 i=0; i < num_files; i++) {
std::string name;
*pkt >> name;
std::string data = pkt->readLongString();
m_media_downloader->conventionalTransferDone(
name, data, this);
}
}
void Client::handleCommand_NodeDef(NetworkPacket* pkt)
{
infostream << "Client: Received node definitions: packet size: "
<< pkt->getSize() << std::endl;
// Mesh update thread must be stopped while
// updating content definitions
sanity_check(!m_mesh_update_thread.isRunning());
// Decompress node definitions
std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
std::ostringstream tmp_os;
decompressZlib(tmp_is, tmp_os);
// Deserialize node definitions
std::istringstream tmp_is2(tmp_os.str());
m_nodedef->deSerialize(tmp_is2);
m_nodedef_received = true;
}
void Client::handleCommand_ItemDef(NetworkPacket* pkt)
{
infostream << "Client: Received item definitions: packet size: "
<< pkt->getSize() << std::endl;
// Mesh update thread must be stopped while
// updating content definitions
sanity_check(!m_mesh_update_thread.isRunning());
// Decompress item definitions
std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
std::ostringstream tmp_os;
decompressZlib(tmp_is, tmp_os);
// Deserialize node definitions
std::istringstream tmp_is2(tmp_os.str());
m_itemdef->deSerialize(tmp_is2);
m_itemdef_received = true;
}
void Client::handleCommand_PlaySound(NetworkPacket* pkt)
{
/*
[0] u32 server_id
[4] u16 name length
[6] char name[len]
[ 6 + len] f32 gain
[10 + len] u8 type
[11 + len] (f32 * 3) pos
[23 + len] u16 object_id
[25 + len] bool loop
[26 + len] f32 fade
[30 + len] f32 pitch
*/
s32 server_id;
std::string name;
float gain;
u8 type; // 0=local, 1=positional, 2=object
v3f pos;
u16 object_id;
bool loop;
float fade = 0.0f;
float pitch = 1.0f;
*pkt >> server_id >> name >> gain >> type >> pos >> object_id >> loop;
try {
*pkt >> fade;
*pkt >> pitch;
} catch (PacketError &e) {};
// Start playing
int client_id = -1;
switch(type) {
case 0: // local
client_id = m_sound->playSound(name, loop, gain, fade, pitch);
break;
case 1: // positional
client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch);
break;
case 2:
{ // object
ClientActiveObject *cao = m_env.getActiveObject(object_id);
if (cao)
pos = cao->getPosition();
client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch);
// TODO: Set up sound to move with object
break;
}
default:
break;
}
if (client_id != -1) {
m_sounds_server_to_client[server_id] = client_id;
m_sounds_client_to_server[client_id] = server_id;
if (object_id != 0)
m_sounds_to_objects[client_id] = object_id;
}
}
void Client::handleCommand_StopSound(NetworkPacket* pkt)
{
s32 server_id;
*pkt >> server_id;
std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.find(server_id);
if (i != m_sounds_server_to_client.end()) {
int client_id = i->second;
m_sound->stopSound(client_id);
}
}
void Client::handleCommand_FadeSound(NetworkPacket *pkt)
{
s32 sound_id;
float step;
float gain;
*pkt >> sound_id >> step >> gain;
std::unordered_map<s32, int>::const_iterator i =
m_sounds_server_to_client.find(sound_id);
if (i != m_sounds_server_to_client.end())
m_sound->fadeSound(i->second, step, gain);
}
void Client::handleCommand_Privileges(NetworkPacket* pkt)
{
m_privileges.clear();
infostream << "Client: Privileges updated: ";
u16 num_privileges;
*pkt >> num_privileges;
for (u16 i = 0; i < num_privileges; i++) {
std::string priv;
*pkt >> priv;
m_privileges.insert(priv);
infostream << priv << " ";
}
infostream << std::endl;
}
void Client::handleCommand_InventoryFormSpec(NetworkPacket* pkt)
{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
// Store formspec in LocalPlayer
player->inventory_formspec = pkt->readLongString();
}
void Client::handleCommand_DetachedInventory(NetworkPacket* pkt)
{
std::string name;
bool keep_inv = true;
*pkt >> name >> keep_inv;
infostream << "Client: Detached inventory update: \"" << name
<< "\", mode=" << (keep_inv ? "update" : "remove") << std::endl;
const auto &inv_it = m_detached_inventories.find(name);
if (!keep_inv) {
if (inv_it != m_detached_inventories.end()) {
delete inv_it->second;
m_detached_inventories.erase(inv_it);
}
return;
}
Inventory *inv = nullptr;
if (inv_it == m_detached_inventories.end()) {
inv = new Inventory(m_itemdef);
m_detached_inventories[name] = inv;
} else {
inv = inv_it->second;
}
u16 ignore;
*pkt >> ignore; // this used to be the length of the following string, ignore it
std::string contents = pkt->getRemainingString();
std::istringstream is(contents, std::ios::binary);
inv->deSerialize(is);
}
void Client::handleCommand_ShowFormSpec(NetworkPacket* pkt)
{
std::string formspec = pkt->readLongString();
std::string formname;
*pkt >> formname;
ClientEvent *event = new ClientEvent();
event->type = CE_SHOW_FORMSPEC;
// pointer is required as event is a struct only!
// adding a std:string to a struct isn't possible
event->show_formspec.formspec = new std::string(formspec);
event->show_formspec.formname = new std::string(formname);
m_client_event_queue.push(event);
}
void Client::handleCommand_SpawnParticle(NetworkPacket* pkt)
{
std::string datastring(pkt->getString(0), pkt->getSize());
std::istringstream is(datastring, std::ios_base::binary);
v3f pos = readV3F32(is);
v3f vel = readV3F32(is);
v3f acc = readV3F32(is);
float expirationtime = readF32(is);
float size = readF32(is);
bool collisiondetection = readU8(is);
std::string texture = deSerializeLongString(is);
bool vertical = false;
bool collision_removal = false;
TileAnimationParams animation;
animation.type = TAT_NONE;
u8 glow = 0;
bool object_collision = false;
try {
vertical = readU8(is);
collision_removal = readU8(is);
animation.deSerialize(is, m_proto_ver);
glow = readU8(is);
object_collision = readU8(is);
} catch (...) {}
ClientEvent *event = new ClientEvent();
event->type = CE_SPAWN_PARTICLE;
event->spawn_particle.pos = new v3f (pos);
event->spawn_particle.vel = new v3f (vel);
event->spawn_particle.acc = new v3f (acc);
event->spawn_particle.expirationtime = expirationtime;
event->spawn_particle.size = size;
event->spawn_particle.collisiondetection = collisiondetection;
event->spawn_particle.collision_removal = collision_removal;
event->spawn_particle.object_collision = object_collision;
event->spawn_particle.vertical = vertical;
event->spawn_particle.texture = new std::string(texture);
event->spawn_particle.animation = animation;
event->spawn_particle.glow = glow;
m_client_event_queue.push(event);
}
void Client::handleCommand_AddParticleSpawner(NetworkPacket* pkt)
{
u16 amount;
float spawntime;
v3f minpos;
v3f maxpos;
v3f minvel;
v3f maxvel;
v3f minacc;
v3f maxacc;
float minexptime;
float maxexptime;
float minsize;
float maxsize;
bool collisiondetection;
u32 server_id;
*pkt >> amount >> spawntime >> minpos >> maxpos >> minvel >> maxvel
>> minacc >> maxacc >> minexptime >> maxexptime >> minsize
>> maxsize >> collisiondetection;
std::string texture = pkt->readLongString();
*pkt >> server_id;
bool vertical = false;
bool collision_removal = false;
u16 attached_id = 0;
TileAnimationParams animation;
animation.type = TAT_NONE;
u8 glow = 0;
bool object_collision = false;
try {
*pkt >> vertical;
*pkt >> collision_removal;
*pkt >> attached_id;
// This is horrible but required (why are there two ways to deserialize pkts?)
std::string datastring(pkt->getRemainingString(), pkt->getRemainingBytes());
std::istringstream is(datastring, std::ios_base::binary);
animation.deSerialize(is, m_proto_ver);
glow = readU8(is);
object_collision = readU8(is);
} catch (...) {}
auto event = new ClientEvent();
event->type = CE_ADD_PARTICLESPAWNER;
event->add_particlespawner.amount = amount;
event->add_particlespawner.spawntime = spawntime;
event->add_particlespawner.minpos = new v3f (minpos);
event->add_particlespawner.maxpos = new v3f (maxpos);
event->add_particlespawner.minvel = new v3f (minvel);
event->add_particlespawner.maxvel = new v3f (maxvel);
event->add_particlespawner.minacc = new v3f (minacc);
event->add_particlespawner.maxacc = new v3f (maxacc);
event->add_particlespawner.minexptime = minexptime;
event->add_particlespawner.maxexptime = maxexptime;
event->add_particlespawner.minsize = minsize;
event->add_particlespawner.maxsize = maxsize;
event->add_particlespawner.collisiondetection = collisiondetection;
event->add_particlespawner.collision_removal = collision_removal;
event->add_particlespawner.object_collision = object_collision;
event->add_particlespawner.attached_id = attached_id;
event->add_particlespawner.vertical = vertical;
event->add_particlespawner.texture = new std::string(texture);
event->add_particlespawner.id = server_id;
event->add_particlespawner.animation = animation;
event->add_particlespawner.glow = glow;
m_client_event_queue.push(event);
}
void Client::handleCommand_DeleteParticleSpawner(NetworkPacket* pkt)
{
u32 server_id;
*pkt >> server_id;
ClientEvent *event = new ClientEvent();
event->type = CE_DELETE_PARTICLESPAWNER;
event->delete_particlespawner.id = server_id;
m_client_event_queue.push(event);
}
void Client::handleCommand_HudAdd(NetworkPacket* pkt)
{
std::string datastring(pkt->getString(0), pkt->getSize());
std::istringstream is(datastring, std::ios_base::binary);
u32 server_id;
u8 type;
v2f pos;
std::string name;
v2f scale;
std::string text;
u32 number;
u32 item;
u32 dir;
v2f align;
v2f offset;
v3f world_pos;
v2s32 size;
*pkt >> server_id >> type >> pos >> name >> scale >> text >> number >> item
>> dir >> align >> offset;
try {
*pkt >> world_pos;
}
catch(SerializationError &e) {};
try {
*pkt >> size;
} catch(SerializationError &e) {};
ClientEvent *event = new ClientEvent();
event->type = CE_HUDADD;
event->hudadd.server_id = server_id;
event->hudadd.type = type;
event->hudadd.pos = new v2f(pos);
event->hudadd.name = new std::string(name);
event->hudadd.scale = new v2f(scale);
event->hudadd.text = new std::string(text);
event->hudadd.number = number;
event->hudadd.item = item;
event->hudadd.dir = dir;
event->hudadd.align = new v2f(align);
event->hudadd.offset = new v2f(offset);
event->hudadd.world_pos = new v3f(world_pos);
event->hudadd.size = new v2s32(size);
m_client_event_queue.push(event);
}
void Client::handleCommand_HudRemove(NetworkPacket* pkt)
{
u32 server_id;
*pkt >> server_id;
auto i = m_hud_server_to_client.find(server_id);
if (i != m_hud_server_to_client.end()) {
int client_id = i->second;
m_hud_server_to_client.erase(i);
ClientEvent *event = new ClientEvent();
event->type = CE_HUDRM;
event->hudrm.id = client_id;
m_client_event_queue.push(event);
}
}
void Client::handleCommand_HudChange(NetworkPacket* pkt)
{
std::string sdata;
v2f v2fdata;
v3f v3fdata;
u32 intdata = 0;
v2s32 v2s32data;
u32 server_id;
u8 stat;
*pkt >> server_id >> stat;
if (stat == HUD_STAT_POS || stat == HUD_STAT_SCALE ||
stat == HUD_STAT_ALIGN || stat == HUD_STAT_OFFSET)
*pkt >> v2fdata;
else if (stat == HUD_STAT_NAME || stat == HUD_STAT_TEXT)
*pkt >> sdata;
else if (stat == HUD_STAT_WORLD_POS)
*pkt >> v3fdata;
else if (stat == HUD_STAT_SIZE )
*pkt >> v2s32data;
else
*pkt >> intdata;
std::unordered_map<u32, u32>::const_iterator i = m_hud_server_to_client.find(server_id);
if (i != m_hud_server_to_client.end()) {
ClientEvent *event = new ClientEvent();
event->type = CE_HUDCHANGE;
event->hudchange.id = i->second;
event->hudchange.stat = (HudElementStat)stat;
event->hudchange.v2fdata = new v2f(v2fdata);
event->hudchange.v3fdata = new v3f(v3fdata);
event->hudchange.sdata = new std::string(sdata);
event->hudchange.data = intdata;
event->hudchange.v2s32data = new v2s32(v2s32data);
m_client_event_queue.push(event);
}
}
void Client::handleCommand_HudSetFlags(NetworkPacket* pkt)
{
u32 flags, mask;
*pkt >> flags >> mask;
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
bool was_minimap_visible = player->hud_flags & HUD_FLAG_MINIMAP_VISIBLE;
bool was_minimap_radar_visible = player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE;
player->hud_flags &= ~mask;
player->hud_flags |= flags;
m_minimap_disabled_by_server = !(player->hud_flags & HUD_FLAG_MINIMAP_VISIBLE);
bool m_minimap_radar_disabled_by_server = !(player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE);
// Hide minimap if it has been disabled by the server
if (m_minimap && m_minimap_disabled_by_server && was_minimap_visible)
// defers a minimap update, therefore only call it if really
// needed, by checking that minimap was visible before
m_minimap->setMinimapMode(MINIMAP_MODE_OFF);
// Switch to surface mode if radar disabled by server
if (m_minimap && m_minimap_radar_disabled_by_server && was_minimap_radar_visible)
m_minimap->setMinimapMode(MINIMAP_MODE_SURFACEx1);
}
void Client::handleCommand_HudSetParam(NetworkPacket* pkt)
{
u16 param; std::string value;
*pkt >> param >> value;
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
if (param == HUD_PARAM_HOTBAR_ITEMCOUNT && value.size() == 4) {
s32 hotbar_itemcount = readS32((u8*) value.c_str());
if (hotbar_itemcount > 0 && hotbar_itemcount <= HUD_HOTBAR_ITEMCOUNT_MAX)
player->hud_hotbar_itemcount = hotbar_itemcount;
}
else if (param == HUD_PARAM_HOTBAR_IMAGE) {
// If value not empty verify image exists in texture source
if (!value.empty() && !getTextureSource()->isKnownSourceImage(value)) {
errorstream << "Server sent wrong Hud hotbar image (sent value: '"
<< value << "')" << std::endl;
return;
}
player->hotbar_image = value;
}
else if (param == HUD_PARAM_HOTBAR_SELECTED_IMAGE) {
// If value not empty verify image exists in texture source
if (!value.empty() && !getTextureSource()->isKnownSourceImage(value)) {
errorstream << "Server sent wrong Hud hotbar selected image (sent value: '"
<< value << "')" << std::endl;
return;
}
player->hotbar_selected_image = value;
}
}
void Client::handleCommand_HudSetSky(NetworkPacket* pkt)
{
std::string datastring(pkt->getString(0), pkt->getSize());
std::istringstream is(datastring, std::ios_base::binary);
video::SColor *bgcolor = new video::SColor(readARGB8(is));
std::string *type = new std::string(deSerializeString(is));
u16 count = readU16(is);
std::vector<std::string> *params = new std::vector<std::string>;
for (size_t i = 0; i < count; i++)
params->push_back(deSerializeString(is));
bool clouds = true;
try {
clouds = readU8(is);
} catch (...) {}
ClientEvent *event = new ClientEvent();
event->type = CE_SET_SKY;
event->set_sky.bgcolor = bgcolor;
event->set_sky.type = type;
event->set_sky.params = params;
event->set_sky.clouds = clouds;
m_client_event_queue.push(event);
}
void Client::handleCommand_CloudParams(NetworkPacket* pkt)
{
f32 density;
video::SColor color_bright;
video::SColor color_ambient;
f32 height;
f32 thickness;
v2f speed;
*pkt >> density >> color_bright >> color_ambient
>> height >> thickness >> speed;
ClientEvent *event = new ClientEvent();
event->type = CE_CLOUD_PARAMS;
event->cloud_params.density = density;
// use the underlying u32 representation, because we can't
// use struct members with constructors here, and this way
// we avoid using new() and delete() for no good reason
event->cloud_params.color_bright = color_bright.color;
event->cloud_params.color_ambient = color_ambient.color;
event->cloud_params.height = height;
event->cloud_params.thickness = thickness;
// same here: deconstruct to skip constructor
event->cloud_params.speed_x = speed.X;
event->cloud_params.speed_y = speed.Y;
m_client_event_queue.push(event);
}
void Client::handleCommand_OverrideDayNightRatio(NetworkPacket* pkt)
{
bool do_override;
u16 day_night_ratio_u;
*pkt >> do_override >> day_night_ratio_u;
float day_night_ratio_f = (float)day_night_ratio_u / 65536;
ClientEvent *event = new ClientEvent();
event->type = CE_OVERRIDE_DAY_NIGHT_RATIO;
event->override_day_night_ratio.do_override = do_override;
event->override_day_night_ratio.ratio_f = day_night_ratio_f;
m_client_event_queue.push(event);
}
void Client::handleCommand_LocalPlayerAnimations(NetworkPacket* pkt)
{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
*pkt >> player->local_animations[0];
*pkt >> player->local_animations[1];
*pkt >> player->local_animations[2];
*pkt >> player->local_animations[3];
*pkt >> player->local_animation_speed;
}
void Client::handleCommand_EyeOffset(NetworkPacket* pkt)
{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
*pkt >> player->eye_offset_first >> player->eye_offset_third;
}
void Client::handleCommand_UpdatePlayerList(NetworkPacket* pkt)
{
u8 type;
u16 num_players;
*pkt >> type >> num_players;
PlayerListModifer notice_type = (PlayerListModifer) type;
for (u16 i = 0; i < num_players; i++) {
std::string name;
*pkt >> name;
switch (notice_type) {
case PLAYER_LIST_INIT:
case PLAYER_LIST_ADD:
m_env.addPlayerName(name);
continue;
case PLAYER_LIST_REMOVE:
m_env.removePlayerName(name);
continue;
}
}
}
void Client::handleCommand_SrpBytesSandB(NetworkPacket* pkt)
{
if (m_chosen_auth_mech != AUTH_MECHANISM_SRP &&
m_chosen_auth_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
errorstream << "Client: Received SRP S_B login message,"
<< " but wasn't supposed to (chosen_mech="
<< m_chosen_auth_mech << ")." << std::endl;
return;
}
char *bytes_M = 0;
size_t len_M = 0;
SRPUser *usr = (SRPUser *) m_auth_data;
std::string s;
std::string B;
*pkt >> s >> B;
infostream << "Client: Received TOCLIENT_SRP_BYTES_S_B." << std::endl;
srp_user_process_challenge(usr, (const unsigned char *) s.c_str(), s.size(),
(const unsigned char *) B.c_str(), B.size(),
(unsigned char **) &bytes_M, &len_M);
if ( !bytes_M ) {
errorstream << "Client: SRP-6a S_B safety check violation!" << std::endl;
return;
}
NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_M, 0);
resp_pkt << std::string(bytes_M, len_M);
Send(&resp_pkt);
}
void Client::handleCommand_FormspecPrepend(NetworkPacket *pkt)
{
LocalPlayer *player = m_env.getLocalPlayer();
assert(player != NULL);
// Store formspec in LocalPlayer
*pkt >> player->formspec_prepend;
}
void Client::handleCommand_CSMRestrictionFlags(NetworkPacket *pkt)
{
*pkt >> m_csm_restriction_flags >> m_csm_restriction_noderange;
// Restrictions were received -> load mods if it's enabled
// Note: this should be moved after mods receptions from server instead
loadMods();
}
/*
* Mod channels
*/
void Client::handleCommand_ModChannelMsg(NetworkPacket *pkt)
{
std::string channel_name, sender, channel_msg;
*pkt >> channel_name >> sender >> channel_msg;
verbosestream << "Mod channel message received from server " << pkt->getPeerId()
<< " on channel " << channel_name << ". sender: `" << sender << "`, message: "
<< channel_msg << std::endl;
if (!m_modchannel_mgr->channelRegistered(channel_name)) {
verbosestream << "Server sent us messages on unregistered channel "
<< channel_name << ", ignoring." << std::endl;
return;
}
m_script->on_modchannel_message(channel_name, sender, channel_msg);
}
void Client::handleCommand_ModChannelSignal(NetworkPacket *pkt)
{
u8 signal_tmp;
ModChannelSignal signal;
std::string channel;
*pkt >> signal_tmp >> channel;
signal = (ModChannelSignal)signal_tmp;
bool valid_signal = true;
// @TODO: send Signal to Lua API
switch (signal) {
case MODCHANNEL_SIGNAL_JOIN_OK:
m_modchannel_mgr->setChannelState(channel, MODCHANNEL_STATE_READ_WRITE);
infostream << "Server ack our mod channel join on channel `" << channel
<< "`, joining." << std::endl;
break;
case MODCHANNEL_SIGNAL_JOIN_FAILURE:
// Unable to join, remove channel
m_modchannel_mgr->leaveChannel(channel, 0);
infostream << "Server refused our mod channel join on channel `" << channel
<< "`" << std::endl;
break;
case MODCHANNEL_SIGNAL_LEAVE_OK:
#ifndef NDEBUG
infostream << "Server ack our mod channel leave on channel " << channel
<< "`, leaving." << std::endl;
#endif
break;
case MODCHANNEL_SIGNAL_LEAVE_FAILURE:
infostream << "Server refused our mod channel leave on channel `" << channel
<< "`" << std::endl;
break;
case MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED:
#ifndef NDEBUG
// Generally unused, but ensure we don't do an implementation error
infostream << "Server tells us we sent a message on channel `" << channel
<< "` but we are not registered. Message was dropped." << std::endl;
#endif
break;
case MODCHANNEL_SIGNAL_SET_STATE: {
u8 state;
*pkt >> state;
if (state == MODCHANNEL_STATE_INIT || state >= MODCHANNEL_STATE_MAX) {
infostream << "Received wrong channel state " << state
<< ", ignoring." << std::endl;
return;
}
m_modchannel_mgr->setChannelState(channel, (ModChannelState) state);
infostream << "Server sets mod channel `" << channel
<< "` in read-only mode." << std::endl;
break;
}
default:
#ifndef NDEBUG
warningstream << "Received unhandled mod channel signal ID "
<< signal << ", ignoring." << std::endl;
#endif
valid_signal = false;
break;
}
// If signal is valid, forward it to client side mods
if (valid_signal)
m_script->on_modchannel_signal(channel, signal);
}
| pgimeno/minetest | src/network/clientpackethandler.cpp | C++ | mit | 40,786 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <iomanip>
#include <cerrno>
#include <algorithm>
#include <cmath>
#include "connection.h"
#include "serialization.h"
#include "log.h"
#include "porting.h"
#include "network/connectionthreads.h"
#include "network/networkpacket.h"
#include "network/peerhandler.h"
#include "util/serialize.h"
#include "util/numeric.h"
#include "util/string.h"
#include "settings.h"
#include "profiler.h"
namespace con
{
/******************************************************************************/
/* defines used for debugging and profiling */
/******************************************************************************/
#ifdef NDEBUG
#define LOG(a) a
#define PROFILE(a)
#else
/* this mutex is used to achieve log message consistency */
std::mutex log_message_mutex;
#define LOG(a) \
{ \
MutexAutoLock loglock(log_message_mutex); \
a; \
}
#define PROFILE(a) a
#endif
#define PING_TIMEOUT 5.0
BufferedPacket makePacket(Address &address, SharedBuffer<u8> data,
u32 protocol_id, session_t sender_peer_id, u8 channel)
{
u32 packet_size = data.getSize() + BASE_HEADER_SIZE;
BufferedPacket p(packet_size);
p.address = address;
writeU32(&p.data[0], protocol_id);
writeU16(&p.data[4], sender_peer_id);
writeU8(&p.data[6], channel);
memcpy(&p.data[BASE_HEADER_SIZE], *data, data.getSize());
return p;
}
SharedBuffer<u8> makeOriginalPacket(const SharedBuffer<u8> &data)
{
u32 header_size = 1;
u32 packet_size = data.getSize() + header_size;
SharedBuffer<u8> b(packet_size);
writeU8(&(b[0]), PACKET_TYPE_ORIGINAL);
if (data.getSize() > 0) {
memcpy(&(b[header_size]), *data, data.getSize());
}
return b;
}
// Split data in chunks and add TYPE_SPLIT headers to them
void makeSplitPacket(const SharedBuffer<u8> &data, u32 chunksize_max, u16 seqnum,
std::list<SharedBuffer<u8>> *chunks)
{
// Chunk packets, containing the TYPE_SPLIT header
u32 chunk_header_size = 7;
u32 maximum_data_size = chunksize_max - chunk_header_size;
u32 start = 0;
u32 end = 0;
u32 chunk_num = 0;
u16 chunk_count = 0;
do {
end = start + maximum_data_size - 1;
if (end > data.getSize() - 1)
end = data.getSize() - 1;
u32 payload_size = end - start + 1;
u32 packet_size = chunk_header_size + payload_size;
SharedBuffer<u8> chunk(packet_size);
writeU8(&chunk[0], PACKET_TYPE_SPLIT);
writeU16(&chunk[1], seqnum);
// [3] u16 chunk_count is written at next stage
writeU16(&chunk[5], chunk_num);
memcpy(&chunk[chunk_header_size], &data[start], payload_size);
chunks->push_back(chunk);
chunk_count++;
start = end + 1;
chunk_num++;
}
while (end != data.getSize() - 1);
for (SharedBuffer<u8> &chunk : *chunks) {
// Write chunk_count
writeU16(&(chunk[3]), chunk_count);
}
}
void makeAutoSplitPacket(SharedBuffer<u8> data, u32 chunksize_max,
u16 &split_seqnum, std::list<SharedBuffer<u8>> *list)
{
u32 original_header_size = 1;
if (data.getSize() + original_header_size > chunksize_max) {
makeSplitPacket(data, chunksize_max, split_seqnum, list);
split_seqnum++;
return;
}
list->push_back(makeOriginalPacket(data));
}
SharedBuffer<u8> makeReliablePacket(SharedBuffer<u8> data, u16 seqnum)
{
u32 header_size = 3;
u32 packet_size = data.getSize() + header_size;
SharedBuffer<u8> b(packet_size);
writeU8(&b[0], PACKET_TYPE_RELIABLE);
writeU16(&b[1], seqnum);
memcpy(&b[header_size], *data, data.getSize());
return b;
}
/*
ReliablePacketBuffer
*/
void ReliablePacketBuffer::print()
{
MutexAutoLock listlock(m_list_mutex);
LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
unsigned int index = 0;
for (BufferedPacket &bufferedPacket : m_list) {
u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1]));
LOG(dout_con<<index<< ":" << s << std::endl);
index++;
}
}
bool ReliablePacketBuffer::empty()
{
MutexAutoLock listlock(m_list_mutex);
return m_list.empty();
}
u32 ReliablePacketBuffer::size()
{
return m_list_size;
}
bool ReliablePacketBuffer::containsPacket(u16 seqnum)
{
return !(findPacket(seqnum) == m_list.end());
}
RPBSearchResult ReliablePacketBuffer::findPacket(u16 seqnum)
{
std::list<BufferedPacket>::iterator i = m_list.begin();
for(; i != m_list.end(); ++i)
{
u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
/*dout_con<<"findPacket(): finding seqnum="<<seqnum
<<", comparing to s="<<s<<std::endl;*/
if (s == seqnum)
break;
}
return i;
}
RPBSearchResult ReliablePacketBuffer::notFound()
{
return m_list.end();
}
bool ReliablePacketBuffer::getFirstSeqnum(u16& result)
{
MutexAutoLock listlock(m_list_mutex);
if (m_list.empty())
return false;
BufferedPacket p = *m_list.begin();
result = readU16(&p.data[BASE_HEADER_SIZE+1]);
return true;
}
BufferedPacket ReliablePacketBuffer::popFirst()
{
MutexAutoLock listlock(m_list_mutex);
if (m_list.empty())
throw NotFoundException("Buffer is empty");
BufferedPacket p = *m_list.begin();
m_list.erase(m_list.begin());
--m_list_size;
if (m_list_size == 0) {
m_oldest_non_answered_ack = 0;
} else {
m_oldest_non_answered_ack =
readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
}
return p;
}
BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
{
MutexAutoLock listlock(m_list_mutex);
RPBSearchResult r = findPacket(seqnum);
if (r == notFound()) {
LOG(dout_con<<"Sequence number: " << seqnum
<< " not found in reliable buffer"<<std::endl);
throw NotFoundException("seqnum not found in buffer");
}
BufferedPacket p = *r;
RPBSearchResult next = r;
++next;
if (next != notFound()) {
u16 s = readU16(&(next->data[BASE_HEADER_SIZE+1]));
m_oldest_non_answered_ack = s;
}
m_list.erase(r);
--m_list_size;
if (m_list_size == 0)
{ m_oldest_non_answered_ack = 0; }
else
{ m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]); }
return p;
}
void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
{
MutexAutoLock listlock(m_list_mutex);
if (p.data.getSize() < BASE_HEADER_SIZE + 3) {
errorstream << "ReliablePacketBuffer::insert(): Invalid data size for "
"reliable packet" << std::endl;
return;
}
u8 type = readU8(&p.data[BASE_HEADER_SIZE + 0]);
if (type != PACKET_TYPE_RELIABLE) {
errorstream << "ReliablePacketBuffer::insert(): type is not reliable"
<< std::endl;
return;
}
u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
if (!seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE)) {
errorstream << "ReliablePacketBuffer::insert(): seqnum is outside of "
"expected window " << std::endl;
return;
}
if (seqnum == next_expected) {
errorstream << "ReliablePacketBuffer::insert(): seqnum is next expected"
<< std::endl;
return;
}
++m_list_size;
sanity_check(m_list_size <= SEQNUM_MAX+1); // FIXME: Handle the error?
// Find the right place for the packet and insert it there
// If list is empty, just add it
if (m_list.empty())
{
m_list.push_back(p);
m_oldest_non_answered_ack = seqnum;
// Done.
return;
}
// Otherwise find the right place
std::list<BufferedPacket>::iterator i = m_list.begin();
// Find the first packet in the list which has a higher seqnum
u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
/* case seqnum is smaller then next_expected seqnum */
/* this is true e.g. on wrap around */
if (seqnum < next_expected) {
while(((s < seqnum) || (s >= next_expected)) && (i != m_list.end())) {
++i;
if (i != m_list.end())
s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
}
}
/* non wrap around case (at least for incoming and next_expected */
else
{
while(((s < seqnum) && (s >= next_expected)) && (i != m_list.end())) {
++i;
if (i != m_list.end())
s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
}
}
if (s == seqnum) {
if (
(readU16(&(i->data[BASE_HEADER_SIZE+1])) != seqnum) ||
(i->data.getSize() != p.data.getSize()) ||
(i->address != p.address)
)
{
/* if this happens your maximum transfer window may be to big */
fprintf(stderr,
"Duplicated seqnum %d non matching packet detected:\n",
seqnum);
fprintf(stderr, "Old: seqnum: %05d size: %04d, address: %s\n",
readU16(&(i->data[BASE_HEADER_SIZE+1])),i->data.getSize(),
i->address.serializeString().c_str());
fprintf(stderr, "New: seqnum: %05d size: %04u, address: %s\n",
readU16(&(p.data[BASE_HEADER_SIZE+1])),p.data.getSize(),
p.address.serializeString().c_str());
throw IncomingDataCorruption("duplicated packet isn't same as original one");
}
/* nothing to do this seems to be a resent packet */
/* for paranoia reason data should be compared */
--m_list_size;
}
/* insert or push back */
else if (i != m_list.end()) {
m_list.insert(i, p);
}
else {
m_list.push_back(p);
}
/* update last packet number */
m_oldest_non_answered_ack = readU16(&(*m_list.begin()).data[BASE_HEADER_SIZE+1]);
}
void ReliablePacketBuffer::incrementTimeouts(float dtime)
{
MutexAutoLock listlock(m_list_mutex);
for (BufferedPacket &bufferedPacket : m_list) {
bufferedPacket.time += dtime;
bufferedPacket.totaltime += dtime;
}
}
std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
unsigned int max_packets)
{
MutexAutoLock listlock(m_list_mutex);
std::list<BufferedPacket> timed_outs;
for (BufferedPacket &bufferedPacket : m_list) {
if (bufferedPacket.time >= timeout) {
timed_outs.push_back(bufferedPacket);
//this packet will be sent right afterwards reset timeout here
bufferedPacket.time = 0.0f;
if (timed_outs.size() >= max_packets)
break;
}
}
return timed_outs;
}
/*
IncomingSplitBuffer
*/
IncomingSplitBuffer::~IncomingSplitBuffer()
{
MutexAutoLock listlock(m_map_mutex);
for (auto &i : m_buf) {
delete i.second;
}
}
/*
This will throw a GotSplitPacketException when a full
split packet is constructed.
*/
SharedBuffer<u8> IncomingSplitBuffer::insert(const BufferedPacket &p, bool reliable)
{
MutexAutoLock listlock(m_map_mutex);
u32 headersize = BASE_HEADER_SIZE + 7;
if (p.data.getSize() < headersize) {
errorstream << "Invalid data size for split packet" << std::endl;
return SharedBuffer<u8>();
}
u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
if (type != PACKET_TYPE_SPLIT) {
errorstream << "IncomingSplitBuffer::insert(): type is not split"
<< std::endl;
return SharedBuffer<u8>();
}
// Add if doesn't exist
if (m_buf.find(seqnum) == m_buf.end()) {
m_buf[seqnum] = new IncomingSplitPacket(chunk_count, reliable);
}
IncomingSplitPacket *sp = m_buf[seqnum];
if (chunk_count != sp->chunk_count)
LOG(derr_con<<"Connection: WARNING: chunk_count="<<chunk_count
<<" != sp->chunk_count="<<sp->chunk_count
<<std::endl);
if (reliable != sp->reliable)
LOG(derr_con<<"Connection: WARNING: reliable="<<reliable
<<" != sp->reliable="<<sp->reliable
<<std::endl);
// If chunk already exists, ignore it.
// Sometimes two identical packets may arrive when there is network
// lag and the server re-sends stuff.
if (sp->chunks.find(chunk_num) != sp->chunks.end())
return SharedBuffer<u8>();
// Cut chunk data out of packet
u32 chunkdatasize = p.data.getSize() - headersize;
SharedBuffer<u8> chunkdata(chunkdatasize);
memcpy(*chunkdata, &(p.data[headersize]), chunkdatasize);
// Set chunk data in buffer
sp->chunks[chunk_num] = chunkdata;
// If not all chunks are received, return empty buffer
if (!sp->allReceived())
return SharedBuffer<u8>();
// Calculate total size
u32 totalsize = 0;
for (const auto &chunk : sp->chunks) {
totalsize += chunk.second.getSize();
}
SharedBuffer<u8> fulldata(totalsize);
// Copy chunks to data buffer
u32 start = 0;
for (u32 chunk_i=0; chunk_i<sp->chunk_count; chunk_i++) {
const SharedBuffer<u8> &buf = sp->chunks[chunk_i];
u16 buf_chunkdatasize = buf.getSize();
memcpy(&fulldata[start], *buf, buf_chunkdatasize);
start += buf_chunkdatasize;
}
// Remove sp from buffer
m_buf.erase(seqnum);
delete sp;
return fulldata;
}
void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
{
std::deque<u16> remove_queue;
{
MutexAutoLock listlock(m_map_mutex);
for (auto &i : m_buf) {
IncomingSplitPacket *p = i.second;
// Reliable ones are not removed by timeout
if (p->reliable)
continue;
p->time += dtime;
if (p->time >= timeout)
remove_queue.push_back(i.first);
}
}
for (u16 j : remove_queue) {
MutexAutoLock listlock(m_map_mutex);
LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
delete m_buf[j];
m_buf.erase(j);
}
}
/*
ConnectionCommand
*/
void ConnectionCommand::send(session_t peer_id_, u8 channelnum_, NetworkPacket *pkt,
bool reliable_)
{
type = CONNCMD_SEND;
peer_id = peer_id_;
channelnum = channelnum_;
data = pkt->oldForgePacket();
reliable = reliable_;
}
/*
Channel
*/
u16 Channel::readNextIncomingSeqNum()
{
MutexAutoLock internal(m_internal_mutex);
return next_incoming_seqnum;
}
u16 Channel::incNextIncomingSeqNum()
{
MutexAutoLock internal(m_internal_mutex);
u16 retval = next_incoming_seqnum;
next_incoming_seqnum++;
return retval;
}
u16 Channel::readNextSplitSeqNum()
{
MutexAutoLock internal(m_internal_mutex);
return next_outgoing_split_seqnum;
}
void Channel::setNextSplitSeqNum(u16 seqnum)
{
MutexAutoLock internal(m_internal_mutex);
next_outgoing_split_seqnum = seqnum;
}
u16 Channel::getOutgoingSequenceNumber(bool& successful)
{
MutexAutoLock internal(m_internal_mutex);
u16 retval = next_outgoing_seqnum;
u16 lowest_unacked_seqnumber;
/* shortcut if there ain't any packet in outgoing list */
if (outgoing_reliables_sent.empty())
{
next_outgoing_seqnum++;
return retval;
}
if (outgoing_reliables_sent.getFirstSeqnum(lowest_unacked_seqnumber))
{
if (lowest_unacked_seqnumber < next_outgoing_seqnum) {
// ugly cast but this one is required in order to tell compiler we
// know about difference of two unsigned may be negative in general
// but we already made sure it won't happen in this case
if (((u16)(next_outgoing_seqnum - lowest_unacked_seqnumber)) > window_size) {
successful = false;
return 0;
}
}
else {
// ugly cast but this one is required in order to tell compiler we
// know about difference of two unsigned may be negative in general
// but we already made sure it won't happen in this case
if ((next_outgoing_seqnum + (u16)(SEQNUM_MAX - lowest_unacked_seqnumber)) >
window_size) {
successful = false;
return 0;
}
}
}
next_outgoing_seqnum++;
return retval;
}
u16 Channel::readOutgoingSequenceNumber()
{
MutexAutoLock internal(m_internal_mutex);
return next_outgoing_seqnum;
}
bool Channel::putBackSequenceNumber(u16 seqnum)
{
if (((seqnum + 1) % (SEQNUM_MAX+1)) == next_outgoing_seqnum) {
next_outgoing_seqnum = seqnum;
return true;
}
return false;
}
void Channel::UpdateBytesSent(unsigned int bytes, unsigned int packets)
{
MutexAutoLock internal(m_internal_mutex);
current_bytes_transfered += bytes;
current_packet_successful += packets;
}
void Channel::UpdateBytesReceived(unsigned int bytes) {
MutexAutoLock internal(m_internal_mutex);
current_bytes_received += bytes;
}
void Channel::UpdateBytesLost(unsigned int bytes)
{
MutexAutoLock internal(m_internal_mutex);
current_bytes_lost += bytes;
}
void Channel::UpdatePacketLossCounter(unsigned int count)
{
MutexAutoLock internal(m_internal_mutex);
current_packet_loss += count;
}
void Channel::UpdatePacketTooLateCounter()
{
MutexAutoLock internal(m_internal_mutex);
current_packet_too_late++;
}
void Channel::UpdateTimers(float dtime)
{
bpm_counter += dtime;
packet_loss_counter += dtime;
if (packet_loss_counter > 1.0f) {
packet_loss_counter -= 1.0f;
unsigned int packet_loss = 11; /* use a neutral value for initialization */
unsigned int packets_successful = 0;
//unsigned int packet_too_late = 0;
bool reasonable_amount_of_data_transmitted = false;
{
MutexAutoLock internal(m_internal_mutex);
packet_loss = current_packet_loss;
//packet_too_late = current_packet_too_late;
packets_successful = current_packet_successful;
if (current_bytes_transfered > (unsigned int) (window_size*512/2)) {
reasonable_amount_of_data_transmitted = true;
}
current_packet_loss = 0;
current_packet_too_late = 0;
current_packet_successful = 0;
}
/* dynamic window size */
float successful_to_lost_ratio = 0.0f;
bool done = false;
if (packets_successful > 0) {
successful_to_lost_ratio = packet_loss/packets_successful;
} else if (packet_loss > 0) {
window_size = std::max(
(window_size - 10),
MIN_RELIABLE_WINDOW_SIZE);
done = true;
}
if (!done) {
if ((successful_to_lost_ratio < 0.01f) &&
(window_size < MAX_RELIABLE_WINDOW_SIZE)) {
/* don't even think about increasing if we didn't even
* use major parts of our window */
if (reasonable_amount_of_data_transmitted)
window_size = std::min(
(window_size + 100),
MAX_RELIABLE_WINDOW_SIZE);
} else if ((successful_to_lost_ratio < 0.05f) &&
(window_size < MAX_RELIABLE_WINDOW_SIZE)) {
/* don't even think about increasing if we didn't even
* use major parts of our window */
if (reasonable_amount_of_data_transmitted)
window_size = std::min(
(window_size + 50),
MAX_RELIABLE_WINDOW_SIZE);
} else if (successful_to_lost_ratio > 0.15f) {
window_size = std::max(
(window_size - 100),
MIN_RELIABLE_WINDOW_SIZE);
} else if (successful_to_lost_ratio > 0.1f) {
window_size = std::max(
(window_size - 50),
MIN_RELIABLE_WINDOW_SIZE);
}
}
}
if (bpm_counter > 10.0f) {
{
MutexAutoLock internal(m_internal_mutex);
cur_kbps =
(((float) current_bytes_transfered)/bpm_counter)/1024.0f;
current_bytes_transfered = 0;
cur_kbps_lost =
(((float) current_bytes_lost)/bpm_counter)/1024.0f;
current_bytes_lost = 0;
cur_incoming_kbps =
(((float) current_bytes_received)/bpm_counter)/1024.0f;
current_bytes_received = 0;
bpm_counter = 0.0f;
}
if (cur_kbps > max_kbps) {
max_kbps = cur_kbps;
}
if (cur_kbps_lost > max_kbps_lost) {
max_kbps_lost = cur_kbps_lost;
}
if (cur_incoming_kbps > max_incoming_kbps) {
max_incoming_kbps = cur_incoming_kbps;
}
rate_samples = MYMIN(rate_samples+1,10);
float old_fraction = ((float) (rate_samples-1) )/( (float) rate_samples);
avg_kbps = avg_kbps * old_fraction +
cur_kbps * (1.0 - old_fraction);
avg_kbps_lost = avg_kbps_lost * old_fraction +
cur_kbps_lost * (1.0 - old_fraction);
avg_incoming_kbps = avg_incoming_kbps * old_fraction +
cur_incoming_kbps * (1.0 - old_fraction);
}
}
/*
Peer
*/
PeerHelper::PeerHelper(Peer* peer) :
m_peer(peer)
{
if (peer && !peer->IncUseCount())
m_peer = nullptr;
}
PeerHelper::~PeerHelper()
{
if (m_peer)
m_peer->DecUseCount();
m_peer = nullptr;
}
PeerHelper& PeerHelper::operator=(Peer* peer)
{
m_peer = peer;
if (peer && !peer->IncUseCount())
m_peer = nullptr;
return *this;
}
Peer* PeerHelper::operator->() const
{
return m_peer;
}
Peer* PeerHelper::operator&() const
{
return m_peer;
}
bool PeerHelper::operator!()
{
return ! m_peer;
}
bool PeerHelper::operator!=(void* ptr)
{
return ((void*) m_peer != ptr);
}
bool Peer::IncUseCount()
{
MutexAutoLock lock(m_exclusive_access_mutex);
if (!m_pending_deletion) {
this->m_usage++;
return true;
}
return false;
}
void Peer::DecUseCount()
{
{
MutexAutoLock lock(m_exclusive_access_mutex);
sanity_check(m_usage > 0);
m_usage--;
if (!((m_pending_deletion) && (m_usage == 0)))
return;
}
delete this;
}
void Peer::RTTStatistics(float rtt, const std::string &profiler_id,
unsigned int num_samples) {
if (m_last_rtt > 0) {
/* set min max values */
if (rtt < m_rtt.min_rtt)
m_rtt.min_rtt = rtt;
if (rtt >= m_rtt.max_rtt)
m_rtt.max_rtt = rtt;
/* do average calculation */
if (m_rtt.avg_rtt < 0.0)
m_rtt.avg_rtt = rtt;
else
m_rtt.avg_rtt = m_rtt.avg_rtt * (num_samples/(num_samples-1)) +
rtt * (1/num_samples);
/* do jitter calculation */
//just use some neutral value at beginning
float jitter = m_rtt.jitter_min;
if (rtt > m_last_rtt)
jitter = rtt-m_last_rtt;
if (rtt <= m_last_rtt)
jitter = m_last_rtt - rtt;
if (jitter < m_rtt.jitter_min)
m_rtt.jitter_min = jitter;
if (jitter >= m_rtt.jitter_max)
m_rtt.jitter_max = jitter;
if (m_rtt.jitter_avg < 0.0)
m_rtt.jitter_avg = jitter;
else
m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
jitter * (1/num_samples);
if (!profiler_id.empty()) {
g_profiler->graphAdd(profiler_id + "_rtt", rtt);
g_profiler->graphAdd(profiler_id + "_jitter", jitter);
}
}
/* save values required for next loop */
m_last_rtt = rtt;
}
bool Peer::isTimedOut(float timeout)
{
MutexAutoLock lock(m_exclusive_access_mutex);
u64 current_time = porting::getTimeMs();
float dtime = CALC_DTIME(m_last_timeout_check,current_time);
m_last_timeout_check = current_time;
m_timeout_counter += dtime;
return m_timeout_counter > timeout;
}
void Peer::Drop()
{
{
MutexAutoLock usage_lock(m_exclusive_access_mutex);
m_pending_deletion = true;
if (m_usage != 0)
return;
}
PROFILE(std::stringstream peerIdentifier1);
PROFILE(peerIdentifier1 << "runTimeouts[" << m_connection->getDesc()
<< ";" << id << ";RELIABLE]");
PROFILE(g_profiler->remove(peerIdentifier1.str()));
PROFILE(std::stringstream peerIdentifier2);
PROFILE(peerIdentifier2 << "sendPackets[" << m_connection->getDesc()
<< ";" << id << ";RELIABLE]");
PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier2.str(), SPT_AVG));
delete this;
}
UDPPeer::UDPPeer(u16 a_id, Address a_address, Connection* connection) :
Peer(a_address,a_id,connection)
{
for (Channel &channel : channels)
channel.setWindowSize(g_settings->getU16("max_packets_per_iteration"));
}
bool UDPPeer::getAddress(MTProtocols type,Address& toset)
{
if ((type == MTP_UDP) || (type == MTP_MINETEST_RELIABLE_UDP) || (type == MTP_PRIMARY))
{
toset = address;
return true;
}
return false;
}
void UDPPeer::reportRTT(float rtt)
{
if (rtt < 0.0) {
return;
}
RTTStatistics(rtt,"rudp",MAX_RELIABLE_WINDOW_SIZE*10);
float timeout = getStat(AVG_RTT) * RESEND_TIMEOUT_FACTOR;
if (timeout < RESEND_TIMEOUT_MIN)
timeout = RESEND_TIMEOUT_MIN;
if (timeout > RESEND_TIMEOUT_MAX)
timeout = RESEND_TIMEOUT_MAX;
MutexAutoLock usage_lock(m_exclusive_access_mutex);
resend_timeout = timeout;
}
bool UDPPeer::Ping(float dtime,SharedBuffer<u8>& data)
{
m_ping_timer += dtime;
if (m_ping_timer >= PING_TIMEOUT)
{
// Create and send PING packet
writeU8(&data[0], PACKET_TYPE_CONTROL);
writeU8(&data[1], CONTROLTYPE_PING);
m_ping_timer = 0.0;
return true;
}
return false;
}
void UDPPeer::PutReliableSendCommand(ConnectionCommand &c,
unsigned int max_packet_size)
{
if (m_pending_disconnect)
return;
if ( channels[c.channelnum].queued_commands.empty() &&
/* don't queue more packets then window size */
(channels[c.channelnum].queued_reliables.size()
< (channels[c.channelnum].getWindowSize()/2))) {
LOG(dout_con<<m_connection->getDesc()
<<" processing reliable command for peer id: " << c.peer_id
<<" data size: " << c.data.getSize() << std::endl);
if (!processReliableSendCommand(c,max_packet_size)) {
channels[c.channelnum].queued_commands.push_back(c);
}
}
else {
LOG(dout_con<<m_connection->getDesc()
<<" Queueing reliable command for peer id: " << c.peer_id
<<" data size: " << c.data.getSize() <<std::endl);
channels[c.channelnum].queued_commands.push_back(c);
}
}
bool UDPPeer::processReliableSendCommand(
ConnectionCommand &c,
unsigned int max_packet_size)
{
if (m_pending_disconnect)
return true;
u32 chunksize_max = max_packet_size
- BASE_HEADER_SIZE
- RELIABLE_HEADER_SIZE;
sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
std::list<SharedBuffer<u8>> originals;
u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
if (c.raw) {
originals.emplace_back(c.data);
} else {
makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number, &originals);
channels[c.channelnum].setNextSplitSeqNum(split_sequence_number);
}
bool have_sequence_number = true;
bool have_initial_sequence_number = false;
std::queue<BufferedPacket> toadd;
volatile u16 initial_sequence_number = 0;
for (SharedBuffer<u8> &original : originals) {
u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
/* oops, we don't have enough sequence numbers to send this packet */
if (!have_sequence_number)
break;
if (!have_initial_sequence_number)
{
initial_sequence_number = seqnum;
have_initial_sequence_number = true;
}
SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
// Add base headers and make a packet
BufferedPacket p = con::makePacket(address, reliable,
m_connection->GetProtocolID(), m_connection->GetPeerID(),
c.channelnum);
toadd.push(p);
}
if (have_sequence_number) {
volatile u16 pcount = 0;
while (!toadd.empty()) {
BufferedPacket p = toadd.front();
toadd.pop();
// LOG(dout_con<<connection->getDesc()
// << " queuing reliable packet for peer_id: " << c.peer_id
// << " channel: " << (c.channelnum&0xFF)
// << " seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
// << std::endl)
channels[c.channelnum].queued_reliables.push(p);
pcount++;
}
sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
return true;
}
volatile u16 packets_available = toadd.size();
/* we didn't get a single sequence number no need to fill queue */
if (!have_initial_sequence_number) {
return false;
}
while (!toadd.empty()) {
/* remove packet */
toadd.pop();
bool successfully_put_back_sequence_number
= channels[c.channelnum].putBackSequenceNumber(
(initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
}
LOG(dout_con<<m_connection->getDesc()
<< " Windowsize exceeded on reliable sending "
<< c.data.getSize() << " bytes"
<< std::endl << "\t\tinitial_sequence_number: "
<< initial_sequence_number
<< std::endl << "\t\tgot at most : "
<< packets_available << " packets"
<< std::endl << "\t\tpackets queued : "
<< channels[c.channelnum].outgoing_reliables_sent.size()
<< std::endl);
return false;
}
void UDPPeer::RunCommandQueues(
unsigned int max_packet_size,
unsigned int maxcommands,
unsigned int maxtransfer)
{
for (Channel &channel : channels) {
unsigned int commands_processed = 0;
if ((!channel.queued_commands.empty()) &&
(channel.queued_reliables.size() < maxtransfer) &&
(commands_processed < maxcommands)) {
try {
ConnectionCommand c = channel.queued_commands.front();
LOG(dout_con << m_connection->getDesc()
<< " processing queued reliable command " << std::endl);
// Packet is processed, remove it from queue
if (processReliableSendCommand(c,max_packet_size)) {
channel.queued_commands.pop_front();
} else {
LOG(dout_con << m_connection->getDesc()
<< " Failed to queue packets for peer_id: " << c.peer_id
<< ", delaying sending of " << c.data.getSize()
<< " bytes" << std::endl);
}
}
catch (ItemNotFoundException &e) {
// intentionally empty
}
}
}
}
u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
{
assert(channel < CHANNEL_COUNT); // Pre-condition
return channels[channel].readNextSplitSeqNum();
}
void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
{
assert(channel < CHANNEL_COUNT); // Pre-condition
channels[channel].setNextSplitSeqNum(seqnum);
}
SharedBuffer<u8> UDPPeer::addSplitPacket(u8 channel, const BufferedPacket &toadd,
bool reliable)
{
assert(channel < CHANNEL_COUNT); // Pre-condition
return channels[channel].incoming_splits.insert(toadd, reliable);
}
/*
Connection
*/
Connection::Connection(u32 protocol_id, u32 max_packet_size, float timeout,
bool ipv6, PeerHandler *peerhandler) :
m_udpSocket(ipv6),
m_protocol_id(protocol_id),
m_sendThread(new ConnectionSendThread(max_packet_size, timeout)),
m_receiveThread(new ConnectionReceiveThread(max_packet_size)),
m_bc_peerhandler(peerhandler)
{
m_udpSocket.setTimeoutMs(5);
m_sendThread->setParent(this);
m_receiveThread->setParent(this);
m_sendThread->start();
m_receiveThread->start();
}
Connection::~Connection()
{
m_shutting_down = true;
// request threads to stop
m_sendThread->stop();
m_receiveThread->stop();
//TODO for some unkonwn reason send/receive threads do not exit as they're
// supposed to be but wait on peer timeout. To speed up shutdown we reduce
// timeout to half a second.
m_sendThread->setPeerTimeout(0.5);
// wait for threads to finish
m_sendThread->wait();
m_receiveThread->wait();
// Delete peers
for (auto &peer : m_peers) {
delete peer.second;
}
}
/* Internal stuff */
void Connection::putEvent(ConnectionEvent &e)
{
assert(e.type != CONNEVENT_NONE); // Pre-condition
m_event_queue.push_back(e);
}
void Connection::TriggerSend()
{
m_sendThread->Trigger();
}
PeerHelper Connection::getPeerNoEx(session_t peer_id)
{
MutexAutoLock peerlock(m_peers_mutex);
std::map<session_t, Peer *>::iterator node = m_peers.find(peer_id);
if (node == m_peers.end()) {
return PeerHelper(NULL);
}
// Error checking
FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
return PeerHelper(node->second);
}
/* find peer_id for address */
u16 Connection::lookupPeer(Address& sender)
{
MutexAutoLock peerlock(m_peers_mutex);
std::map<u16, Peer*>::iterator j;
j = m_peers.begin();
for(; j != m_peers.end(); ++j)
{
Peer *peer = j->second;
if (peer->isPendingDeletion())
continue;
Address tocheck;
if ((peer->getAddress(MTP_MINETEST_RELIABLE_UDP, tocheck)) && (tocheck == sender))
return peer->id;
if ((peer->getAddress(MTP_UDP, tocheck)) && (tocheck == sender))
return peer->id;
}
return PEER_ID_INEXISTENT;
}
bool Connection::deletePeer(session_t peer_id, bool timeout)
{
Peer *peer = 0;
/* lock list as short as possible */
{
MutexAutoLock peerlock(m_peers_mutex);
if (m_peers.find(peer_id) == m_peers.end())
return false;
peer = m_peers[peer_id];
m_peers.erase(peer_id);
m_peer_ids.remove(peer_id);
}
Address peer_address;
//any peer has a primary address this never fails!
peer->getAddress(MTP_PRIMARY, peer_address);
// Create event
ConnectionEvent e;
e.peerRemoved(peer_id, timeout, peer_address);
putEvent(e);
peer->Drop();
return true;
}
/* Interface */
ConnectionEvent Connection::waitEvent(u32 timeout_ms)
{
try {
return m_event_queue.pop_front(timeout_ms);
} catch(ItemNotFoundException &ex) {
ConnectionEvent e;
e.type = CONNEVENT_NONE;
return e;
}
}
void Connection::putCommand(ConnectionCommand &c)
{
if (!m_shutting_down) {
m_command_queue.push_back(c);
m_sendThread->Trigger();
}
}
void Connection::Serve(Address bind_addr)
{
ConnectionCommand c;
c.serve(bind_addr);
putCommand(c);
}
void Connection::Connect(Address address)
{
ConnectionCommand c;
c.connect(address);
putCommand(c);
}
bool Connection::Connected()
{
MutexAutoLock peerlock(m_peers_mutex);
if (m_peers.size() != 1)
return false;
std::map<session_t, Peer *>::iterator node = m_peers.find(PEER_ID_SERVER);
if (node == m_peers.end())
return false;
if (m_peer_id == PEER_ID_INEXISTENT)
return false;
return true;
}
void Connection::Disconnect()
{
ConnectionCommand c;
c.disconnect();
putCommand(c);
}
void Connection::Receive(NetworkPacket* pkt)
{
for(;;) {
ConnectionEvent e = waitEvent(m_bc_receive_timeout);
if (e.type != CONNEVENT_NONE)
LOG(dout_con << getDesc() << ": Receive: got event: "
<< e.describe() << std::endl);
switch(e.type) {
case CONNEVENT_NONE:
throw NoIncomingDataException("No incoming data");
case CONNEVENT_DATA_RECEIVED:
// Data size is lesser than command size, ignoring packet
if (e.data.getSize() < 2) {
continue;
}
pkt->putRawPacket(*e.data, e.data.getSize(), e.peer_id);
return;
case CONNEVENT_PEER_ADDED: {
UDPPeer tmp(e.peer_id, e.address, this);
if (m_bc_peerhandler)
m_bc_peerhandler->peerAdded(&tmp);
continue;
}
case CONNEVENT_PEER_REMOVED: {
UDPPeer tmp(e.peer_id, e.address, this);
if (m_bc_peerhandler)
m_bc_peerhandler->deletingPeer(&tmp, e.timeout);
continue;
}
case CONNEVENT_BIND_FAILED:
throw ConnectionBindFailed("Failed to bind socket "
"(port already in use?)");
}
}
throw NoIncomingDataException("No incoming data");
}
void Connection::Send(session_t peer_id, u8 channelnum,
NetworkPacket *pkt, bool reliable)
{
assert(channelnum < CHANNEL_COUNT); // Pre-condition
ConnectionCommand c;
c.send(peer_id, channelnum, pkt, reliable);
putCommand(c);
}
Address Connection::GetPeerAddress(session_t peer_id)
{
PeerHelper peer = getPeerNoEx(peer_id);
if (!peer)
throw PeerNotFoundException("No address for peer found!");
Address peer_address;
peer->getAddress(MTP_PRIMARY, peer_address);
return peer_address;
}
float Connection::getPeerStat(session_t peer_id, rtt_stat_type type)
{
PeerHelper peer = getPeerNoEx(peer_id);
if (!peer) return -1;
return peer->getStat(type);
}
float Connection::getLocalStat(rate_stat_type type)
{
PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
float retval = 0.0;
for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
switch(type) {
case CUR_DL_RATE:
retval += channel.getCurrentDownloadRateKB();
break;
case AVG_DL_RATE:
retval += channel.getAvgDownloadRateKB();
break;
case CUR_INC_RATE:
retval += channel.getCurrentIncomingRateKB();
break;
case AVG_INC_RATE:
retval += channel.getAvgIncomingRateKB();
break;
case AVG_LOSS_RATE:
retval += channel.getAvgLossRateKB();
break;
case CUR_LOSS_RATE:
retval += channel.getCurrentLossRateKB();
break;
default:
FATAL_ERROR("Connection::getLocalStat Invalid stat type");
}
}
return retval;
}
u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd)
{
// Somebody wants to make a new connection
// Get a unique peer id (2 or higher)
session_t peer_id_new = m_next_remote_peer_id;
u16 overflow = MAX_UDP_PEERS;
/*
Find an unused peer id
*/
MutexAutoLock lock(m_peers_mutex);
bool out_of_ids = false;
for(;;) {
// Check if exists
if (m_peers.find(peer_id_new) == m_peers.end())
break;
// Check for overflow
if (peer_id_new == overflow) {
out_of_ids = true;
break;
}
peer_id_new++;
}
if (out_of_ids) {
errorstream << getDesc() << " ran out of peer ids" << std::endl;
return PEER_ID_INEXISTENT;
}
// Create a peer
Peer *peer = 0;
peer = new UDPPeer(peer_id_new, sender, this);
m_peers[peer->id] = peer;
m_peer_ids.push_back(peer->id);
m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS;
LOG(dout_con << getDesc()
<< "createPeer(): giving peer_id=" << peer_id_new << std::endl);
ConnectionCommand cmd;
SharedBuffer<u8> reply(4);
writeU8(&reply[0], PACKET_TYPE_CONTROL);
writeU8(&reply[1], CONTROLTYPE_SET_PEER_ID);
writeU16(&reply[2], peer_id_new);
cmd.createPeer(peer_id_new,reply);
putCommand(cmd);
// Create peer addition event
ConnectionEvent e;
e.peerAdded(peer_id_new, sender);
putEvent(e);
// We're now talking to a valid peer_id
return peer_id_new;
}
void Connection::PrintInfo(std::ostream &out)
{
m_info_mutex.lock();
out<<getDesc()<<": ";
m_info_mutex.unlock();
}
const std::string Connection::getDesc()
{
return std::string("con(")+
itos(m_udpSocket.GetHandle())+"/"+itos(m_peer_id)+")";
}
void Connection::DisconnectPeer(session_t peer_id)
{
ConnectionCommand discon;
discon.disconnect_peer(peer_id);
putCommand(discon);
}
void Connection::sendAck(session_t peer_id, u8 channelnum, u16 seqnum)
{
assert(channelnum < CHANNEL_COUNT); // Pre-condition
LOG(dout_con<<getDesc()
<<" Queuing ACK command to peer_id: " << peer_id <<
" channel: " << (channelnum & 0xFF) <<
" seqnum: " << seqnum << std::endl);
ConnectionCommand c;
SharedBuffer<u8> ack(4);
writeU8(&ack[0], PACKET_TYPE_CONTROL);
writeU8(&ack[1], CONTROLTYPE_ACK);
writeU16(&ack[2], seqnum);
c.ack(peer_id, channelnum, ack);
putCommand(c);
m_sendThread->Trigger();
}
UDPPeer* Connection::createServerPeer(Address& address)
{
if (getPeerNoEx(PEER_ID_SERVER) != 0)
{
throw ConnectionException("Already connected to a server");
}
UDPPeer *peer = new UDPPeer(PEER_ID_SERVER, address, this);
{
MutexAutoLock lock(m_peers_mutex);
m_peers[peer->id] = peer;
m_peer_ids.push_back(peer->id);
}
return peer;
}
} // namespace
| pgimeno/minetest | src/network/connection.cpp | C++ | mit | 38,241 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "irrlichttypes_bloated.h"
#include "peerhandler.h"
#include "socket.h"
#include "constants.h"
#include "util/pointer.h"
#include "util/container.h"
#include "util/thread.h"
#include "util/numeric.h"
#include "networkprotocol.h"
#include <iostream>
#include <fstream>
#include <list>
#include <map>
class NetworkPacket;
namespace con
{
class ConnectionReceiveThread;
class ConnectionSendThread;
typedef enum MTProtocols {
MTP_PRIMARY,
MTP_UDP,
MTP_MINETEST_RELIABLE_UDP
} MTProtocols;
#define MAX_UDP_PEERS 65535
#define SEQNUM_MAX 65535
inline bool seqnum_higher(u16 totest, u16 base)
{
if (totest > base)
{
if ((totest - base) > (SEQNUM_MAX/2))
return false;
return true;
}
if ((base - totest) > (SEQNUM_MAX/2))
return true;
return false;
}
inline bool seqnum_in_window(u16 seqnum, u16 next,u16 window_size)
{
u16 window_start = next;
u16 window_end = ( next + window_size ) % (SEQNUM_MAX+1);
if (window_start < window_end) {
return ((seqnum >= window_start) && (seqnum < window_end));
}
return ((seqnum < window_end) || (seqnum >= window_start));
}
static inline float CALC_DTIME(u64 lasttime, u64 curtime)
{
float value = ( curtime - lasttime) / 1000.0;
return MYMAX(MYMIN(value,0.1),0.0);
}
struct BufferedPacket
{
BufferedPacket(u8 *a_data, u32 a_size):
data(a_data, a_size)
{}
BufferedPacket(u32 a_size):
data(a_size)
{}
Buffer<u8> data; // Data of the packet, including headers
float time = 0.0f; // Seconds from buffering the packet or re-sending
float totaltime = 0.0f; // Seconds from buffering the packet
u64 absolute_send_time = -1;
Address address; // Sender or destination
unsigned int resend_count = 0;
};
// This adds the base headers to the data and makes a packet out of it
BufferedPacket makePacket(Address &address, SharedBuffer<u8> data,
u32 protocol_id, session_t sender_peer_id, u8 channel);
// Depending on size, make a TYPE_ORIGINAL or TYPE_SPLIT packet
// Increments split_seqnum if a split packet is made
void makeAutoSplitPacket(SharedBuffer<u8> data, u32 chunksize_max,
u16 &split_seqnum, std::list<SharedBuffer<u8>> *list);
// Add the TYPE_RELIABLE header to the data
SharedBuffer<u8> makeReliablePacket(SharedBuffer<u8> data, u16 seqnum);
struct IncomingSplitPacket
{
IncomingSplitPacket(u32 cc, bool r):
chunk_count(cc), reliable(r) {}
IncomingSplitPacket() = delete;
// Key is chunk number, value is data without headers
std::map<u16, SharedBuffer<u8>> chunks;
u32 chunk_count;
float time = 0.0f; // Seconds from adding
bool reliable = false; // If true, isn't deleted on timeout
bool allReceived() const
{
return (chunks.size() == chunk_count);
}
};
/*
=== NOTES ===
A packet is sent through a channel to a peer with a basic header:
TODO: Should we have a receiver_peer_id also?
Header (7 bytes):
[0] u32 protocol_id
[4] session_t sender_peer_id
[6] u8 channel
sender_peer_id:
Unique to each peer.
value 0 (PEER_ID_INEXISTENT) is reserved for making new connections
value 1 (PEER_ID_SERVER) is reserved for server
these constants are defined in constants.h
channel:
The lower the number, the higher the priority is.
Only channels 0, 1 and 2 exist.
*/
#define BASE_HEADER_SIZE 7
#define CHANNEL_COUNT 3
/*
Packet types:
CONTROL: This is a packet used by the protocol.
- When this is processed, nothing is handed to the user.
Header (2 byte):
[0] u8 type
[1] u8 controltype
controltype and data description:
CONTROLTYPE_ACK
[2] u16 seqnum
CONTROLTYPE_SET_PEER_ID
[2] session_t peer_id_new
CONTROLTYPE_PING
- There is no actual reply, but this can be sent in a reliable
packet to get a reply
CONTROLTYPE_DISCO
*/
//#define TYPE_CONTROL 0
#define CONTROLTYPE_ACK 0
#define CONTROLTYPE_SET_PEER_ID 1
#define CONTROLTYPE_PING 2
#define CONTROLTYPE_DISCO 3
/*
ORIGINAL: This is a plain packet with no control and no error
checking at all.
- When this is processed, it is directly handed to the user.
Header (1 byte):
[0] u8 type
*/
//#define TYPE_ORIGINAL 1
#define ORIGINAL_HEADER_SIZE 1
/*
SPLIT: These are sequences of packets forming one bigger piece of
data.
- When processed and all the packet_nums 0...packet_count-1 are
present (this should be buffered), the resulting data shall be
directly handed to the user.
- If the data fails to come up in a reasonable time, the buffer shall
be silently discarded.
- These can be sent as-is or atop of a RELIABLE packet stream.
Header (7 bytes):
[0] u8 type
[1] u16 seqnum
[3] u16 chunk_count
[5] u16 chunk_num
*/
//#define TYPE_SPLIT 2
/*
RELIABLE: Delivery of all RELIABLE packets shall be forced by ACKs,
and they shall be delivered in the same order as sent. This is done
with a buffer in the receiving and transmitting end.
- When this is processed, the contents of each packet is recursively
processed as packets.
Header (3 bytes):
[0] u8 type
[1] u16 seqnum
*/
//#define TYPE_RELIABLE 3
#define RELIABLE_HEADER_SIZE 3
#define SEQNUM_INITIAL 65500
enum PacketType: u8 {
PACKET_TYPE_CONTROL = 0,
PACKET_TYPE_ORIGINAL = 1,
PACKET_TYPE_SPLIT = 2,
PACKET_TYPE_RELIABLE = 3,
PACKET_TYPE_MAX
};
/*
A buffer which stores reliable packets and sorts them internally
for fast access to the smallest one.
*/
typedef std::list<BufferedPacket>::iterator RPBSearchResult;
class ReliablePacketBuffer
{
public:
ReliablePacketBuffer() = default;
bool getFirstSeqnum(u16& result);
BufferedPacket popFirst();
BufferedPacket popSeqnum(u16 seqnum);
void insert(BufferedPacket &p,u16 next_expected);
void incrementTimeouts(float dtime);
std::list<BufferedPacket> getTimedOuts(float timeout,
unsigned int max_packets);
void print();
bool empty();
bool containsPacket(u16 seqnum);
RPBSearchResult notFound();
u32 size();
private:
RPBSearchResult findPacket(u16 seqnum);
std::list<BufferedPacket> m_list;
u32 m_list_size = 0;
u16 m_oldest_non_answered_ack;
std::mutex m_list_mutex;
};
/*
A buffer for reconstructing split packets
*/
class IncomingSplitBuffer
{
public:
~IncomingSplitBuffer();
/*
Returns a reference counted buffer of length != 0 when a full split
packet is constructed. If not, returns one of length 0.
*/
SharedBuffer<u8> insert(const BufferedPacket &p, bool reliable);
void removeUnreliableTimedOuts(float dtime, float timeout);
private:
// Key is seqnum
std::map<u16, IncomingSplitPacket*> m_buf;
std::mutex m_map_mutex;
};
struct OutgoingPacket
{
session_t peer_id;
u8 channelnum;
SharedBuffer<u8> data;
bool reliable;
bool ack;
OutgoingPacket(session_t peer_id_, u8 channelnum_, const SharedBuffer<u8> &data_,
bool reliable_,bool ack_=false):
peer_id(peer_id_),
channelnum(channelnum_),
data(data_),
reliable(reliable_),
ack(ack_)
{
}
};
enum ConnectionCommandType{
CONNCMD_NONE,
CONNCMD_SERVE,
CONNCMD_CONNECT,
CONNCMD_DISCONNECT,
CONNCMD_DISCONNECT_PEER,
CONNCMD_SEND,
CONNCMD_SEND_TO_ALL,
CONCMD_ACK,
CONCMD_CREATE_PEER
};
struct ConnectionCommand
{
enum ConnectionCommandType type = CONNCMD_NONE;
Address address;
session_t peer_id = PEER_ID_INEXISTENT;
u8 channelnum = 0;
Buffer<u8> data;
bool reliable = false;
bool raw = false;
ConnectionCommand() = default;
ConnectionCommand &operator=(const ConnectionCommand &other)
{
type = other.type;
address = other.address;
peer_id = other.peer_id;
channelnum = other.channelnum;
// We must copy the buffer here to prevent race condition
data = SharedBuffer<u8>(*other.data, other.data.getSize());
reliable = other.reliable;
raw = other.raw;
return *this;
}
void serve(Address address_)
{
type = CONNCMD_SERVE;
address = address_;
}
void connect(Address address_)
{
type = CONNCMD_CONNECT;
address = address_;
}
void disconnect()
{
type = CONNCMD_DISCONNECT;
}
void disconnect_peer(session_t peer_id_)
{
type = CONNCMD_DISCONNECT_PEER;
peer_id = peer_id_;
}
void send(session_t peer_id_, u8 channelnum_, NetworkPacket *pkt, bool reliable_);
void ack(session_t peer_id_, u8 channelnum_, const SharedBuffer<u8> &data_)
{
type = CONCMD_ACK;
peer_id = peer_id_;
channelnum = channelnum_;
data = data_;
reliable = false;
}
void createPeer(session_t peer_id_, const SharedBuffer<u8> &data_)
{
type = CONCMD_CREATE_PEER;
peer_id = peer_id_;
data = data_;
channelnum = 0;
reliable = true;
raw = true;
}
};
/* maximum window size to use, 0xFFFF is theoretical maximum don't think about
* touching it, the less you're away from it the more likely data corruption
* will occur
*/
#define MAX_RELIABLE_WINDOW_SIZE 0x8000
/* starting value for window size */
#define MIN_RELIABLE_WINDOW_SIZE 0x40
class Channel
{
public:
u16 readNextIncomingSeqNum();
u16 incNextIncomingSeqNum();
u16 getOutgoingSequenceNumber(bool& successfull);
u16 readOutgoingSequenceNumber();
bool putBackSequenceNumber(u16);
u16 readNextSplitSeqNum();
void setNextSplitSeqNum(u16 seqnum);
// This is for buffering the incoming packets that are coming in
// the wrong order
ReliablePacketBuffer incoming_reliables;
// This is for buffering the sent packets so that the sender can
// re-send them if no ACK is received
ReliablePacketBuffer outgoing_reliables_sent;
//queued reliable packets
std::queue<BufferedPacket> queued_reliables;
//queue commands prior splitting to packets
std::deque<ConnectionCommand> queued_commands;
IncomingSplitBuffer incoming_splits;
Channel() = default;
~Channel() = default;
void UpdatePacketLossCounter(unsigned int count);
void UpdatePacketTooLateCounter();
void UpdateBytesSent(unsigned int bytes,unsigned int packages=1);
void UpdateBytesLost(unsigned int bytes);
void UpdateBytesReceived(unsigned int bytes);
void UpdateTimers(float dtime);
const float getCurrentDownloadRateKB()
{ MutexAutoLock lock(m_internal_mutex); return cur_kbps; };
const float getMaxDownloadRateKB()
{ MutexAutoLock lock(m_internal_mutex); return max_kbps; };
const float getCurrentLossRateKB()
{ MutexAutoLock lock(m_internal_mutex); return cur_kbps_lost; };
const float getMaxLossRateKB()
{ MutexAutoLock lock(m_internal_mutex); return max_kbps_lost; };
const float getCurrentIncomingRateKB()
{ MutexAutoLock lock(m_internal_mutex); return cur_incoming_kbps; };
const float getMaxIncomingRateKB()
{ MutexAutoLock lock(m_internal_mutex); return max_incoming_kbps; };
const float getAvgDownloadRateKB()
{ MutexAutoLock lock(m_internal_mutex); return avg_kbps; };
const float getAvgLossRateKB()
{ MutexAutoLock lock(m_internal_mutex); return avg_kbps_lost; };
const float getAvgIncomingRateKB()
{ MutexAutoLock lock(m_internal_mutex); return avg_incoming_kbps; };
const unsigned int getWindowSize() const { return window_size; };
void setWindowSize(unsigned int size) { window_size = size; };
private:
std::mutex m_internal_mutex;
int window_size = MIN_RELIABLE_WINDOW_SIZE;
u16 next_incoming_seqnum = SEQNUM_INITIAL;
u16 next_outgoing_seqnum = SEQNUM_INITIAL;
u16 next_outgoing_split_seqnum = SEQNUM_INITIAL;
unsigned int current_packet_loss = 0;
unsigned int current_packet_too_late = 0;
unsigned int current_packet_successful = 0;
float packet_loss_counter = 0.0f;
unsigned int current_bytes_transfered = 0;
unsigned int current_bytes_received = 0;
unsigned int current_bytes_lost = 0;
float max_kbps = 0.0f;
float cur_kbps = 0.0f;
float avg_kbps = 0.0f;
float max_incoming_kbps = 0.0f;
float cur_incoming_kbps = 0.0f;
float avg_incoming_kbps = 0.0f;
float max_kbps_lost = 0.0f;
float cur_kbps_lost = 0.0f;
float avg_kbps_lost = 0.0f;
float bpm_counter = 0.0f;
unsigned int rate_samples = 0;
};
class Peer;
class PeerHelper
{
public:
PeerHelper() = default;
PeerHelper(Peer* peer);
~PeerHelper();
PeerHelper& operator=(Peer* peer);
Peer* operator->() const;
bool operator!();
Peer* operator&() const;
bool operator!=(void* ptr);
private:
Peer *m_peer = nullptr;
};
class Connection;
typedef enum {
CUR_DL_RATE,
AVG_DL_RATE,
CUR_INC_RATE,
AVG_INC_RATE,
CUR_LOSS_RATE,
AVG_LOSS_RATE,
} rate_stat_type;
class Peer {
public:
friend class PeerHelper;
Peer(Address address_,u16 id_,Connection* connection) :
id(id_),
m_connection(connection),
address(address_),
m_last_timeout_check(porting::getTimeMs())
{
};
virtual ~Peer() {
MutexAutoLock usage_lock(m_exclusive_access_mutex);
FATAL_ERROR_IF(m_usage != 0, "Reference counting failure");
};
// Unique id of the peer
u16 id;
void Drop();
virtual void PutReliableSendCommand(ConnectionCommand &c,
unsigned int max_packet_size) {};
virtual bool getAddress(MTProtocols type, Address& toset) = 0;
bool isPendingDeletion()
{ MutexAutoLock lock(m_exclusive_access_mutex); return m_pending_deletion; };
void ResetTimeout()
{MutexAutoLock lock(m_exclusive_access_mutex); m_timeout_counter = 0.0; };
bool isTimedOut(float timeout);
unsigned int m_increment_packets_remaining = 9;
unsigned int m_increment_bytes_remaining = 0;
virtual u16 getNextSplitSequenceNumber(u8 channel) { return 0; };
virtual void setNextSplitSequenceNumber(u8 channel, u16 seqnum) {};
virtual SharedBuffer<u8> addSplitPacket(u8 channel, const BufferedPacket &toadd,
bool reliable)
{
fprintf(stderr,"Peer: addSplitPacket called, this is supposed to be never called!\n");
return SharedBuffer<u8>(0);
};
virtual bool Ping(float dtime, SharedBuffer<u8>& data) { return false; };
virtual float getStat(rtt_stat_type type) const {
switch (type) {
case MIN_RTT:
return m_rtt.min_rtt;
case MAX_RTT:
return m_rtt.max_rtt;
case AVG_RTT:
return m_rtt.avg_rtt;
case MIN_JITTER:
return m_rtt.jitter_min;
case MAX_JITTER:
return m_rtt.jitter_max;
case AVG_JITTER:
return m_rtt.jitter_avg;
}
return -1;
}
protected:
virtual void reportRTT(float rtt) {};
void RTTStatistics(float rtt,
const std::string &profiler_id = "",
unsigned int num_samples = 1000);
bool IncUseCount();
void DecUseCount();
std::mutex m_exclusive_access_mutex;
bool m_pending_deletion = false;
Connection* m_connection;
// Address of the peer
Address address;
// Ping timer
float m_ping_timer = 0.0f;
private:
struct rttstats {
float jitter_min = FLT_MAX;
float jitter_max = 0.0f;
float jitter_avg = -1.0f;
float min_rtt = FLT_MAX;
float max_rtt = 0.0f;
float avg_rtt = -1.0f;
rttstats() = default;
};
rttstats m_rtt;
float m_last_rtt = -1.0f;
// current usage count
unsigned int m_usage = 0;
// Seconds from last receive
float m_timeout_counter = 0.0f;
u64 m_last_timeout_check;
};
class UDPPeer : public Peer
{
public:
friend class PeerHelper;
friend class ConnectionReceiveThread;
friend class ConnectionSendThread;
friend class Connection;
UDPPeer(u16 a_id, Address a_address, Connection* connection);
virtual ~UDPPeer() = default;
void PutReliableSendCommand(ConnectionCommand &c,
unsigned int max_packet_size);
bool getAddress(MTProtocols type, Address& toset);
u16 getNextSplitSequenceNumber(u8 channel);
void setNextSplitSequenceNumber(u8 channel, u16 seqnum);
SharedBuffer<u8> addSplitPacket(u8 channel, const BufferedPacket &toadd,
bool reliable);
protected:
/*
Calculates avg_rtt and resend_timeout.
rtt=-1 only recalculates resend_timeout
*/
void reportRTT(float rtt);
void RunCommandQueues(
unsigned int max_packet_size,
unsigned int maxcommands,
unsigned int maxtransfer);
float getResendTimeout()
{ MutexAutoLock lock(m_exclusive_access_mutex); return resend_timeout; }
void setResendTimeout(float timeout)
{ MutexAutoLock lock(m_exclusive_access_mutex); resend_timeout = timeout; }
bool Ping(float dtime,SharedBuffer<u8>& data);
Channel channels[CHANNEL_COUNT];
bool m_pending_disconnect = false;
private:
// This is changed dynamically
float resend_timeout = 0.5;
bool processReliableSendCommand(
ConnectionCommand &c,
unsigned int max_packet_size);
};
/*
Connection
*/
enum ConnectionEventType{
CONNEVENT_NONE,
CONNEVENT_DATA_RECEIVED,
CONNEVENT_PEER_ADDED,
CONNEVENT_PEER_REMOVED,
CONNEVENT_BIND_FAILED,
};
struct ConnectionEvent
{
enum ConnectionEventType type = CONNEVENT_NONE;
session_t peer_id = 0;
Buffer<u8> data;
bool timeout = false;
Address address;
ConnectionEvent() = default;
std::string describe()
{
switch(type) {
case CONNEVENT_NONE:
return "CONNEVENT_NONE";
case CONNEVENT_DATA_RECEIVED:
return "CONNEVENT_DATA_RECEIVED";
case CONNEVENT_PEER_ADDED:
return "CONNEVENT_PEER_ADDED";
case CONNEVENT_PEER_REMOVED:
return "CONNEVENT_PEER_REMOVED";
case CONNEVENT_BIND_FAILED:
return "CONNEVENT_BIND_FAILED";
}
return "Invalid ConnectionEvent";
}
void dataReceived(session_t peer_id_, const SharedBuffer<u8> &data_)
{
type = CONNEVENT_DATA_RECEIVED;
peer_id = peer_id_;
data = data_;
}
void peerAdded(session_t peer_id_, Address address_)
{
type = CONNEVENT_PEER_ADDED;
peer_id = peer_id_;
address = address_;
}
void peerRemoved(session_t peer_id_, bool timeout_, Address address_)
{
type = CONNEVENT_PEER_REMOVED;
peer_id = peer_id_;
timeout = timeout_;
address = address_;
}
void bindFailed()
{
type = CONNEVENT_BIND_FAILED;
}
};
class PeerHandler;
class Connection
{
public:
friend class ConnectionSendThread;
friend class ConnectionReceiveThread;
Connection(u32 protocol_id, u32 max_packet_size, float timeout, bool ipv6,
PeerHandler *peerhandler);
~Connection();
/* Interface */
ConnectionEvent waitEvent(u32 timeout_ms);
void putCommand(ConnectionCommand &c);
void SetTimeoutMs(u32 timeout) { m_bc_receive_timeout = timeout; }
void Serve(Address bind_addr);
void Connect(Address address);
bool Connected();
void Disconnect();
void Receive(NetworkPacket* pkt);
void Send(session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable);
session_t GetPeerID() const { return m_peer_id; }
Address GetPeerAddress(session_t peer_id);
float getPeerStat(session_t peer_id, rtt_stat_type type);
float getLocalStat(rate_stat_type type);
const u32 GetProtocolID() const { return m_protocol_id; };
const std::string getDesc();
void DisconnectPeer(session_t peer_id);
protected:
PeerHelper getPeerNoEx(session_t peer_id);
u16 lookupPeer(Address& sender);
u16 createPeer(Address& sender, MTProtocols protocol, int fd);
UDPPeer* createServerPeer(Address& sender);
bool deletePeer(session_t peer_id, bool timeout);
void SetPeerID(session_t id) { m_peer_id = id; }
void sendAck(session_t peer_id, u8 channelnum, u16 seqnum);
void PrintInfo(std::ostream &out);
std::list<session_t> getPeerIDs()
{
MutexAutoLock peerlock(m_peers_mutex);
return m_peer_ids;
}
UDPSocket m_udpSocket;
MutexedQueue<ConnectionCommand> m_command_queue;
void putEvent(ConnectionEvent &e);
void TriggerSend();
private:
MutexedQueue<ConnectionEvent> m_event_queue;
session_t m_peer_id = 0;
u32 m_protocol_id;
std::map<session_t, Peer *> m_peers;
std::list<session_t> m_peer_ids;
std::mutex m_peers_mutex;
std::unique_ptr<ConnectionSendThread> m_sendThread;
std::unique_ptr<ConnectionReceiveThread> m_receiveThread;
std::mutex m_info_mutex;
// Backwards compatibility
PeerHandler *m_bc_peerhandler;
u32 m_bc_receive_timeout = 0;
bool m_shutting_down = false;
session_t m_next_remote_peer_id = 2;
};
} // namespace
| pgimeno/minetest | src/network/connection.h | C++ | mit | 20,255 |
/*
Minetest
Copyright (C) 2013-2017 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2017 celeron55, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "connectionthreads.h"
#include "log.h"
#include "profiler.h"
#include "settings.h"
#include "network/networkpacket.h"
#include "util/serialize.h"
namespace con
{
/******************************************************************************/
/* defines used for debugging and profiling */
/******************************************************************************/
#ifdef NDEBUG
#define LOG(a) a
#define PROFILE(a)
#undef DEBUG_CONNECTION_KBPS
#else
/* this mutex is used to achieve log message consistency */
std::mutex log_conthread_mutex;
#define LOG(a) \
{ \
MutexAutoLock loglock(log_conthread_mutex); \
a; \
}
#define PROFILE(a) a
//#define DEBUG_CONNECTION_KBPS
#undef DEBUG_CONNECTION_KBPS
#endif
/* maximum number of retries for reliable packets */
#define MAX_RELIABLE_RETRY 5
#define WINDOW_SIZE 5
static session_t readPeerId(u8 *packetdata)
{
return readU16(&packetdata[4]);
}
static u8 readChannel(u8 *packetdata)
{
return readU8(&packetdata[6]);
}
/******************************************************************************/
/* Connection Threads */
/******************************************************************************/
ConnectionSendThread::ConnectionSendThread(unsigned int max_packet_size,
float timeout) :
Thread("ConnectionSend"),
m_max_packet_size(max_packet_size),
m_timeout(timeout),
m_max_data_packets_per_iteration(g_settings->getU16("max_packets_per_iteration"))
{
}
void *ConnectionSendThread::run()
{
assert(m_connection);
LOG(dout_con << m_connection->getDesc()
<< "ConnectionSend thread started" << std::endl);
u64 curtime = porting::getTimeMs();
u64 lasttime = curtime;
PROFILE(std::stringstream ThreadIdentifier);
PROFILE(ThreadIdentifier << "ConnectionSend: [" << m_connection->getDesc() << "]");
/* if stop is requested don't stop immediately but try to send all */
/* packets first */
while (!stopRequested() || packetsQueued()) {
BEGIN_DEBUG_EXCEPTION_HANDLER
PROFILE(ScopeProfiler sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
m_iteration_packets_avaialble = m_max_data_packets_per_iteration;
/* wait for trigger or timeout */
m_send_sleep_semaphore.wait(50);
/* remove all triggers */
while (m_send_sleep_semaphore.wait(0)) {
}
lasttime = curtime;
curtime = porting::getTimeMs();
float dtime = CALC_DTIME(lasttime, curtime);
/* first do all the reliable stuff */
runTimeouts(dtime);
/* translate commands to packets */
ConnectionCommand c = m_connection->m_command_queue.pop_frontNoEx(0);
while (c.type != CONNCMD_NONE) {
if (c.reliable)
processReliableCommand(c);
else
processNonReliableCommand(c);
c = m_connection->m_command_queue.pop_frontNoEx(0);
}
/* send non reliable packets */
sendPackets(dtime);
END_DEBUG_EXCEPTION_HANDLER
}
PROFILE(g_profiler->remove(ThreadIdentifier.str()));
return NULL;
}
void ConnectionSendThread::Trigger()
{
m_send_sleep_semaphore.post();
}
bool ConnectionSendThread::packetsQueued()
{
std::list<session_t> peerIds = m_connection->getPeerIDs();
if (!m_outgoing_queue.empty() && !peerIds.empty())
return true;
for (session_t peerId : peerIds) {
PeerHelper peer = m_connection->getPeerNoEx(peerId);
if (!peer)
continue;
if (dynamic_cast<UDPPeer *>(&peer) == 0)
continue;
for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
if (!channel.queued_commands.empty()) {
return true;
}
}
}
return false;
}
void ConnectionSendThread::runTimeouts(float dtime)
{
std::list<session_t> timeouted_peers;
std::list<session_t> peerIds = m_connection->getPeerIDs();
for (session_t &peerId : peerIds) {
PeerHelper peer = m_connection->getPeerNoEx(peerId);
if (!peer)
continue;
UDPPeer *udpPeer = dynamic_cast<UDPPeer *>(&peer);
if (!udpPeer)
continue;
PROFILE(std::stringstream peerIdentifier);
PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
<< ";" << peerId << ";RELIABLE]");
PROFILE(ScopeProfiler
peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
SharedBuffer<u8> data(2); // data for sending ping, required here because of goto
/*
Check peer timeout
*/
if (peer->isTimedOut(m_timeout)) {
infostream << m_connection->getDesc()
<< "RunTimeouts(): Peer " << peer->id
<< " has timed out."
<< " (source=peer->timeout_counter)"
<< std::endl;
// Add peer to the list
timeouted_peers.push_back(peer->id);
// Don't bother going through the buffers of this one
continue;
}
float resend_timeout = udpPeer->getResendTimeout();
bool retry_count_exceeded = false;
for (Channel &channel : udpPeer->channels) {
std::list<BufferedPacket> timed_outs;
// Remove timed out incomplete unreliable split packets
channel.incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout);
// Increment reliable packet times
channel.outgoing_reliables_sent.incrementTimeouts(dtime);
unsigned int numpeers = m_connection->m_peers.size();
if (numpeers == 0)
return;
// Re-send timed out outgoing reliables
timed_outs = channel.outgoing_reliables_sent.getTimedOuts(resend_timeout,
(m_max_data_packets_per_iteration / numpeers));
channel.UpdatePacketLossCounter(timed_outs.size());
g_profiler->graphAdd("packets_lost", timed_outs.size());
m_iteration_packets_avaialble -= timed_outs.size();
for (std::list<BufferedPacket>::iterator k = timed_outs.begin();
k != timed_outs.end(); ++k) {
session_t peer_id = readPeerId(*(k->data));
u8 channelnum = readChannel(*(k->data));
u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE + 1]));
channel.UpdateBytesLost(k->data.getSize());
k->resend_count++;
if (k->resend_count > MAX_RELIABLE_RETRY) {
retry_count_exceeded = true;
timeouted_peers.push_back(peer->id);
/* no need to check additional packets if a single one did timeout*/
break;
}
LOG(derr_con << m_connection->getDesc()
<< "RE-SENDING timed-out RELIABLE to "
<< k->address.serializeString()
<< "(t/o=" << resend_timeout << "): "
<< "from_peer_id=" << peer_id
<< ", channel=" << ((int) channelnum & 0xff)
<< ", seqnum=" << seqnum
<< std::endl);
rawSend(*k);
// do not handle rtt here as we can't decide if this packet was
// lost or really takes more time to transmit
}
if (retry_count_exceeded) {
break; /* no need to check other channels if we already did timeout */
}
channel.UpdateTimers(dtime);
}
/* skip to next peer if we did timeout */
if (retry_count_exceeded)
continue;
/* send ping if necessary */
if (udpPeer->Ping(dtime, data)) {
LOG(dout_con << m_connection->getDesc()
<< "Sending ping for peer_id: " << udpPeer->id << std::endl);
/* this may fail if there ain't a sequence number left */
if (!rawSendAsPacket(udpPeer->id, 0, data, true)) {
//retrigger with reduced ping interval
udpPeer->Ping(4.0, data);
}
}
udpPeer->RunCommandQueues(m_max_packet_size,
m_max_commands_per_iteration,
m_max_packets_requeued);
}
// Remove timed out peers
for (u16 timeouted_peer : timeouted_peers) {
LOG(derr_con << m_connection->getDesc()
<< "RunTimeouts(): Removing peer " << timeouted_peer << std::endl);
m_connection->deletePeer(timeouted_peer, true);
}
}
void ConnectionSendThread::rawSend(const BufferedPacket &packet)
{
try {
m_connection->m_udpSocket.Send(packet.address, *packet.data,
packet.data.getSize());
LOG(dout_con << m_connection->getDesc()
<< " rawSend: " << packet.data.getSize()
<< " bytes sent" << std::endl);
} catch (SendFailedException &e) {
LOG(derr_con << m_connection->getDesc()
<< "Connection::rawSend(): SendFailedException: "
<< packet.address.serializeString() << std::endl);
}
}
void ConnectionSendThread::sendAsPacketReliable(BufferedPacket &p, Channel *channel)
{
try {
p.absolute_send_time = porting::getTimeMs();
// Buffer the packet
channel->outgoing_reliables_sent.insert(p,
(channel->readOutgoingSequenceNumber() - MAX_RELIABLE_WINDOW_SIZE)
% (MAX_RELIABLE_WINDOW_SIZE + 1));
}
catch (AlreadyExistsException &e) {
LOG(derr_con << m_connection->getDesc()
<< "WARNING: Going to send a reliable packet"
<< " in outgoing buffer" << std::endl);
}
// Send the packet
rawSend(p);
}
bool ConnectionSendThread::rawSendAsPacket(session_t peer_id, u8 channelnum,
SharedBuffer<u8> data, bool reliable)
{
PeerHelper peer = m_connection->getPeerNoEx(peer_id);
if (!peer) {
LOG(dout_con << m_connection->getDesc()
<< " INFO: dropped packet for non existent peer_id: "
<< peer_id << std::endl);
FATAL_ERROR_IF(!reliable,
"Trying to send raw packet reliable but no peer found!");
return false;
}
Channel *channel = &(dynamic_cast<UDPPeer *>(&peer)->channels[channelnum]);
if (reliable) {
bool have_sequence_number_for_raw_packet = true;
u16 seqnum =
channel->getOutgoingSequenceNumber(have_sequence_number_for_raw_packet);
if (!have_sequence_number_for_raw_packet)
return false;
SharedBuffer<u8> reliable = makeReliablePacket(data, seqnum);
Address peer_address;
peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
// Add base headers and make a packet
BufferedPacket p = con::makePacket(peer_address, reliable,
m_connection->GetProtocolID(), m_connection->GetPeerID(),
channelnum);
// first check if our send window is already maxed out
if (channel->outgoing_reliables_sent.size()
< channel->getWindowSize()) {
LOG(dout_con << m_connection->getDesc()
<< " INFO: sending a reliable packet to peer_id " << peer_id
<< " channel: " << (u32)channelnum
<< " seqnum: " << seqnum << std::endl);
sendAsPacketReliable(p, channel);
return true;
}
LOG(dout_con << m_connection->getDesc()
<< " INFO: queueing reliable packet for peer_id: " << peer_id
<< " channel: " << (u32)channelnum
<< " seqnum: " << seqnum << std::endl);
channel->queued_reliables.push(p);
return false;
}
Address peer_address;
if (peer->getAddress(MTP_UDP, peer_address)) {
// Add base headers and make a packet
BufferedPacket p = con::makePacket(peer_address, data,
m_connection->GetProtocolID(), m_connection->GetPeerID(),
channelnum);
// Send the packet
rawSend(p);
return true;
}
LOG(dout_con << m_connection->getDesc()
<< " INFO: dropped unreliable packet for peer_id: " << peer_id
<< " because of (yet) missing udp address" << std::endl);
return false;
}
void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
{
assert(c.reliable); // Pre-condition
switch (c.type) {
case CONNCMD_NONE:
LOG(dout_con << m_connection->getDesc()
<< "UDP processing reliable CONNCMD_NONE" << std::endl);
return;
case CONNCMD_SEND:
LOG(dout_con << m_connection->getDesc()
<< "UDP processing reliable CONNCMD_SEND" << std::endl);
sendReliable(c);
return;
case CONNCMD_SEND_TO_ALL:
LOG(dout_con << m_connection->getDesc()
<< "UDP processing CONNCMD_SEND_TO_ALL" << std::endl);
sendToAllReliable(c);
return;
case CONCMD_CREATE_PEER:
LOG(dout_con << m_connection->getDesc()
<< "UDP processing reliable CONCMD_CREATE_PEER" << std::endl);
if (!rawSendAsPacket(c.peer_id, c.channelnum, c.data, c.reliable)) {
/* put to queue if we couldn't send it immediately */
sendReliable(c);
}
return;
case CONNCMD_SERVE:
case CONNCMD_CONNECT:
case CONNCMD_DISCONNECT:
case CONCMD_ACK:
FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
default:
LOG(dout_con << m_connection->getDesc()
<< " Invalid reliable command type: " << c.type << std::endl);
}
}
void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
{
assert(!c.reliable); // Pre-condition
switch (c.type) {
case CONNCMD_NONE:
LOG(dout_con << m_connection->getDesc()
<< " UDP processing CONNCMD_NONE" << std::endl);
return;
case CONNCMD_SERVE:
LOG(dout_con << m_connection->getDesc()
<< " UDP processing CONNCMD_SERVE port="
<< c.address.serializeString() << std::endl);
serve(c.address);
return;
case CONNCMD_CONNECT:
LOG(dout_con << m_connection->getDesc()
<< " UDP processing CONNCMD_CONNECT" << std::endl);
connect(c.address);
return;
case CONNCMD_DISCONNECT:
LOG(dout_con << m_connection->getDesc()
<< " UDP processing CONNCMD_DISCONNECT" << std::endl);
disconnect();
return;
case CONNCMD_DISCONNECT_PEER:
LOG(dout_con << m_connection->getDesc()
<< " UDP processing CONNCMD_DISCONNECT_PEER" << std::endl);
disconnect_peer(c.peer_id);
return;
case CONNCMD_SEND:
LOG(dout_con << m_connection->getDesc()
<< " UDP processing CONNCMD_SEND" << std::endl);
send(c.peer_id, c.channelnum, c.data);
return;
case CONNCMD_SEND_TO_ALL:
LOG(dout_con << m_connection->getDesc()
<< " UDP processing CONNCMD_SEND_TO_ALL" << std::endl);
sendToAll(c.channelnum, c.data);
return;
case CONCMD_ACK:
LOG(dout_con << m_connection->getDesc()
<< " UDP processing CONCMD_ACK" << std::endl);
sendAsPacket(c.peer_id, c.channelnum, c.data, true);
return;
case CONCMD_CREATE_PEER:
FATAL_ERROR("Got command that should be reliable as unreliable command");
default:
LOG(dout_con << m_connection->getDesc()
<< " Invalid command type: " << c.type << std::endl);
}
}
void ConnectionSendThread::serve(Address bind_address)
{
LOG(dout_con << m_connection->getDesc()
<< "UDP serving at port " << bind_address.serializeString() << std::endl);
try {
m_connection->m_udpSocket.Bind(bind_address);
m_connection->SetPeerID(PEER_ID_SERVER);
}
catch (SocketException &e) {
// Create event
ConnectionEvent ce;
ce.bindFailed();
m_connection->putEvent(ce);
}
}
void ConnectionSendThread::connect(Address address)
{
LOG(dout_con << m_connection->getDesc() << " connecting to "
<< address.serializeString()
<< ":" << address.getPort() << std::endl);
UDPPeer *peer = m_connection->createServerPeer(address);
// Create event
ConnectionEvent e;
e.peerAdded(peer->id, peer->address);
m_connection->putEvent(e);
Address bind_addr;
if (address.isIPv6())
bind_addr.setAddress((IPv6AddressBytes *) NULL);
else
bind_addr.setAddress(0, 0, 0, 0);
m_connection->m_udpSocket.Bind(bind_addr);
// Send a dummy packet to server with peer_id = PEER_ID_INEXISTENT
m_connection->SetPeerID(PEER_ID_INEXISTENT);
NetworkPacket pkt(0, 0);
m_connection->Send(PEER_ID_SERVER, 0, &pkt, true);
}
void ConnectionSendThread::disconnect()
{
LOG(dout_con << m_connection->getDesc() << " disconnecting" << std::endl);
// Create and send DISCO packet
SharedBuffer<u8> data(2);
writeU8(&data[0], PACKET_TYPE_CONTROL);
writeU8(&data[1], CONTROLTYPE_DISCO);
// Send to all
std::list<session_t> peerids = m_connection->getPeerIDs();
for (session_t peerid : peerids) {
sendAsPacket(peerid, 0, data, false);
}
}
void ConnectionSendThread::disconnect_peer(session_t peer_id)
{
LOG(dout_con << m_connection->getDesc() << " disconnecting peer" << std::endl);
// Create and send DISCO packet
SharedBuffer<u8> data(2);
writeU8(&data[0], PACKET_TYPE_CONTROL);
writeU8(&data[1], CONTROLTYPE_DISCO);
sendAsPacket(peer_id, 0, data, false);
PeerHelper peer = m_connection->getPeerNoEx(peer_id);
if (!peer)
return;
if (dynamic_cast<UDPPeer *>(&peer) == 0) {
return;
}
dynamic_cast<UDPPeer *>(&peer)->m_pending_disconnect = true;
}
void ConnectionSendThread::send(session_t peer_id, u8 channelnum,
SharedBuffer<u8> data)
{
assert(channelnum < CHANNEL_COUNT); // Pre-condition
PeerHelper peer = m_connection->getPeerNoEx(peer_id);
if (!peer) {
LOG(dout_con << m_connection->getDesc() << " peer: peer_id=" << peer_id
<< ">>>NOT<<< found on sending packet"
<< ", channel " << (channelnum % 0xFF)
<< ", size: " << data.getSize() << std::endl);
return;
}
LOG(dout_con << m_connection->getDesc() << " sending to peer_id=" << peer_id
<< ", channel " << (channelnum % 0xFF)
<< ", size: " << data.getSize() << std::endl);
u16 split_sequence_number = peer->getNextSplitSequenceNumber(channelnum);
u32 chunksize_max = m_max_packet_size - BASE_HEADER_SIZE;
std::list<SharedBuffer<u8>> originals;
makeAutoSplitPacket(data, chunksize_max, split_sequence_number, &originals);
peer->setNextSplitSequenceNumber(channelnum, split_sequence_number);
for (const SharedBuffer<u8> &original : originals) {
sendAsPacket(peer_id, channelnum, original);
}
}
void ConnectionSendThread::sendReliable(ConnectionCommand &c)
{
PeerHelper peer = m_connection->getPeerNoEx(c.peer_id);
if (!peer)
return;
peer->PutReliableSendCommand(c, m_max_packet_size);
}
void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
{
std::list<session_t> peerids = m_connection->getPeerIDs();
for (session_t peerid : peerids) {
send(peerid, channelnum, data);
}
}
void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
{
std::list<session_t> peerids = m_connection->getPeerIDs();
for (session_t peerid : peerids) {
PeerHelper peer = m_connection->getPeerNoEx(peerid);
if (!peer)
continue;
peer->PutReliableSendCommand(c, m_max_packet_size);
}
}
void ConnectionSendThread::sendPackets(float dtime)
{
std::list<session_t> peerIds = m_connection->getPeerIDs();
std::list<session_t> pendingDisconnect;
std::map<session_t, bool> pending_unreliable;
for (session_t peerId : peerIds) {
PeerHelper peer = m_connection->getPeerNoEx(peerId);
//peer may have been removed
if (!peer) {
LOG(dout_con << m_connection->getDesc() << " Peer not found: peer_id="
<< peerId
<< std::endl);
continue;
}
peer->m_increment_packets_remaining =
m_iteration_packets_avaialble / m_connection->m_peers.size();
UDPPeer *udpPeer = dynamic_cast<UDPPeer *>(&peer);
if (!udpPeer) {
continue;
}
if (udpPeer->m_pending_disconnect) {
pendingDisconnect.push_back(peerId);
}
PROFILE(std::stringstream
peerIdentifier);
PROFILE(
peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << peerId
<< ";RELIABLE]");
PROFILE(ScopeProfiler
peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
LOG(dout_con << m_connection->getDesc()
<< " Handle per peer queues: peer_id=" << peerId
<< " packet quota: " << peer->m_increment_packets_remaining << std::endl);
// first send queued reliable packets for all peers (if possible)
for (unsigned int i = 0; i < CHANNEL_COUNT; i++) {
Channel &channel = udpPeer->channels[i];
u16 next_to_ack = 0;
channel.outgoing_reliables_sent.getFirstSeqnum(next_to_ack);
u16 next_to_receive = 0;
channel.incoming_reliables.getFirstSeqnum(next_to_receive);
LOG(dout_con << m_connection->getDesc() << "\t channel: "
<< i << ", peer quota:"
<< peer->m_increment_packets_remaining
<< std::endl
<< "\t\t\treliables on wire: "
<< channel.outgoing_reliables_sent.size()
<< ", waiting for ack for " << next_to_ack
<< std::endl
<< "\t\t\tincoming_reliables: "
<< channel.incoming_reliables.size()
<< ", next reliable packet: "
<< channel.readNextIncomingSeqNum()
<< ", next queued: " << next_to_receive
<< std::endl
<< "\t\t\treliables queued : "
<< channel.queued_reliables.size()
<< std::endl
<< "\t\t\tqueued commands : "
<< channel.queued_commands.size()
<< std::endl);
while (!channel.queued_reliables.empty() &&
channel.outgoing_reliables_sent.size()
< channel.getWindowSize() &&
peer->m_increment_packets_remaining > 0) {
BufferedPacket p = channel.queued_reliables.front();
channel.queued_reliables.pop();
LOG(dout_con << m_connection->getDesc()
<< " INFO: sending a queued reliable packet "
<< " channel: " << i
<< ", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE + 1])
<< std::endl);
sendAsPacketReliable(p, &channel);
peer->m_increment_packets_remaining--;
}
}
}
if (!m_outgoing_queue.empty()) {
LOG(dout_con << m_connection->getDesc()
<< " Handle non reliable queue ("
<< m_outgoing_queue.size() << " pkts)" << std::endl);
}
unsigned int initial_queuesize = m_outgoing_queue.size();
/* send non reliable packets*/
for (unsigned int i = 0; i < initial_queuesize; i++) {
OutgoingPacket packet = m_outgoing_queue.front();
m_outgoing_queue.pop();
if (packet.reliable)
continue;
PeerHelper peer = m_connection->getPeerNoEx(packet.peer_id);
if (!peer) {
LOG(dout_con << m_connection->getDesc()
<< " Outgoing queue: peer_id=" << packet.peer_id
<< ">>>NOT<<< found on sending packet"
<< ", channel " << (packet.channelnum % 0xFF)
<< ", size: " << packet.data.getSize() << std::endl);
continue;
}
/* send acks immediately */
if (packet.ack) {
rawSendAsPacket(packet.peer_id, packet.channelnum,
packet.data, packet.reliable);
peer->m_increment_packets_remaining =
MYMIN(0, peer->m_increment_packets_remaining--);
} else if (
(peer->m_increment_packets_remaining > 0) ||
(stopRequested())) {
rawSendAsPacket(packet.peer_id, packet.channelnum,
packet.data, packet.reliable);
peer->m_increment_packets_remaining--;
} else {
m_outgoing_queue.push(packet);
pending_unreliable[packet.peer_id] = true;
}
}
for (session_t peerId : pendingDisconnect) {
if (!pending_unreliable[peerId]) {
m_connection->deletePeer(peerId, false);
}
}
}
void ConnectionSendThread::sendAsPacket(session_t peer_id, u8 channelnum,
SharedBuffer<u8> data, bool ack)
{
OutgoingPacket packet(peer_id, channelnum, data, false, ack);
m_outgoing_queue.push(packet);
}
ConnectionReceiveThread::ConnectionReceiveThread(unsigned int max_packet_size) :
Thread("ConnectionReceive")
{
}
void *ConnectionReceiveThread::run()
{
assert(m_connection);
LOG(dout_con << m_connection->getDesc()
<< "ConnectionReceive thread started" << std::endl);
PROFILE(std::stringstream
ThreadIdentifier);
PROFILE(ThreadIdentifier << "ConnectionReceive: [" << m_connection->getDesc() << "]");
#ifdef DEBUG_CONNECTION_KBPS
u64 curtime = porting::getTimeMs();
u64 lasttime = curtime;
float debug_print_timer = 0.0;
#endif
while (!stopRequested()) {
BEGIN_DEBUG_EXCEPTION_HANDLER
PROFILE(ScopeProfiler
sp(g_profiler, ThreadIdentifier.str(), SPT_AVG));
#ifdef DEBUG_CONNECTION_KBPS
lasttime = curtime;
curtime = porting::getTimeMs();
float dtime = CALC_DTIME(lasttime,curtime);
#endif
/* receive packets */
receive();
#ifdef DEBUG_CONNECTION_KBPS
debug_print_timer += dtime;
if (debug_print_timer > 20.0) {
debug_print_timer -= 20.0;
std::list<session_t> peerids = m_connection->getPeerIDs();
for (std::list<session_t>::iterator i = peerids.begin();
i != peerids.end();
i++)
{
PeerHelper peer = m_connection->getPeerNoEx(*i);
if (!peer)
continue;
float peer_current = 0.0;
float peer_loss = 0.0;
float avg_rate = 0.0;
float avg_loss = 0.0;
for(u16 j=0; j<CHANNEL_COUNT; j++)
{
peer_current +=peer->channels[j].getCurrentDownloadRateKB();
peer_loss += peer->channels[j].getCurrentLossRateKB();
avg_rate += peer->channels[j].getAvgDownloadRateKB();
avg_loss += peer->channels[j].getAvgLossRateKB();
}
std::stringstream output;
output << std::fixed << std::setprecision(1);
output << "OUT to Peer " << *i << " RATES (good / loss) " << std::endl;
output << "\tcurrent (sum): " << peer_current << "kb/s "<< peer_loss << "kb/s" << std::endl;
output << "\taverage (sum): " << avg_rate << "kb/s "<< avg_loss << "kb/s" << std::endl;
output << std::setfill(' ');
for(u16 j=0; j<CHANNEL_COUNT; j++)
{
output << "\tcha " << j << ":"
<< " CUR: " << std::setw(6) << peer->channels[j].getCurrentDownloadRateKB() <<"kb/s"
<< " AVG: " << std::setw(6) << peer->channels[j].getAvgDownloadRateKB() <<"kb/s"
<< " MAX: " << std::setw(6) << peer->channels[j].getMaxDownloadRateKB() <<"kb/s"
<< " /"
<< " CUR: " << std::setw(6) << peer->channels[j].getCurrentLossRateKB() <<"kb/s"
<< " AVG: " << std::setw(6) << peer->channels[j].getAvgLossRateKB() <<"kb/s"
<< " MAX: " << std::setw(6) << peer->channels[j].getMaxLossRateKB() <<"kb/s"
<< " / WS: " << peer->channels[j].getWindowSize()
<< std::endl;
}
fprintf(stderr,"%s\n",output.str().c_str());
}
}
#endif
END_DEBUG_EXCEPTION_HANDLER
}
PROFILE(g_profiler->remove(ThreadIdentifier.str()));
return NULL;
}
// Receive packets from the network and buffers and create ConnectionEvents
void ConnectionReceiveThread::receive()
{
// use IPv6 minimum allowed MTU as receive buffer size as this is
// theoretical reliable upper boundary of a udp packet for all IPv6 enabled
// infrastructure
unsigned int packet_maxsize = 1500;
SharedBuffer<u8> packetdata(packet_maxsize);
bool packet_queued = true;
unsigned int loop_count = 0;
/* first of all read packets from socket */
/* check for incoming data available */
while ((loop_count < 10) &&
(m_connection->m_udpSocket.WaitData(50))) {
loop_count++;
try {
if (packet_queued) {
bool data_left = true;
session_t peer_id;
SharedBuffer<u8> resultdata;
while (data_left) {
try {
data_left = getFromBuffers(peer_id, resultdata);
if (data_left) {
ConnectionEvent e;
e.dataReceived(peer_id, resultdata);
m_connection->putEvent(e);
}
}
catch (ProcessedSilentlyException &e) {
/* try reading again */
}
}
packet_queued = false;
}
Address sender;
s32 received_size = m_connection->m_udpSocket.Receive(sender, *packetdata,
packet_maxsize);
if ((received_size < BASE_HEADER_SIZE) ||
(readU32(&packetdata[0]) != m_connection->GetProtocolID())) {
LOG(derr_con << m_connection->getDesc()
<< "Receive(): Invalid incoming packet, "
<< "size: " << received_size
<< ", protocol: "
<< ((received_size >= 4) ? readU32(&packetdata[0]) : -1)
<< std::endl);
continue;
}
session_t peer_id = readPeerId(*packetdata);
u8 channelnum = readChannel(*packetdata);
if (channelnum > CHANNEL_COUNT - 1) {
LOG(derr_con << m_connection->getDesc()
<< "Receive(): Invalid channel " << (u32)channelnum << std::endl);
throw InvalidIncomingDataException("Channel doesn't exist");
}
/* Try to identify peer by sender address (may happen on join) */
if (peer_id == PEER_ID_INEXISTENT) {
peer_id = m_connection->lookupPeer(sender);
// We do not have to remind the peer of its
// peer id as the CONTROLTYPE_SET_PEER_ID
// command was sent reliably.
}
/* The peer was not found in our lists. Add it. */
if (peer_id == PEER_ID_INEXISTENT) {
peer_id = m_connection->createPeer(sender, MTP_MINETEST_RELIABLE_UDP, 0);
}
PeerHelper peer = m_connection->getPeerNoEx(peer_id);
if (!peer) {
LOG(dout_con << m_connection->getDesc()
<< " got packet from unknown peer_id: "
<< peer_id << " Ignoring." << std::endl);
continue;
}
// Validate peer address
Address peer_address;
if (peer->getAddress(MTP_UDP, peer_address)) {
if (peer_address != sender) {
LOG(derr_con << m_connection->getDesc()
<< m_connection->getDesc()
<< " Peer " << peer_id << " sending from different address."
" Ignoring." << std::endl);
continue;
}
} else {
bool invalid_address = true;
if (invalid_address) {
LOG(derr_con << m_connection->getDesc()
<< m_connection->getDesc()
<< " Peer " << peer_id << " unknown."
" Ignoring." << std::endl);
continue;
}
}
peer->ResetTimeout();
Channel *channel = 0;
if (dynamic_cast<UDPPeer *>(&peer) != 0) {
channel = &(dynamic_cast<UDPPeer *>(&peer)->channels[channelnum]);
}
if (channel != 0) {
channel->UpdateBytesReceived(received_size);
}
// Throw the received packet to channel->processPacket()
// Make a new SharedBuffer from the data without the base headers
SharedBuffer<u8> strippeddata(received_size - BASE_HEADER_SIZE);
memcpy(*strippeddata, &packetdata[BASE_HEADER_SIZE],
strippeddata.getSize());
try {
// Process it (the result is some data with no headers made by us)
SharedBuffer<u8> resultdata = processPacket
(channel, strippeddata, peer_id, channelnum, false);
LOG(dout_con << m_connection->getDesc()
<< " ProcessPacket from peer_id: " << peer_id
<< ", channel: " << (u32)channelnum << ", returned "
<< resultdata.getSize() << " bytes" << std::endl);
ConnectionEvent e;
e.dataReceived(peer_id, resultdata);
m_connection->putEvent(e);
}
catch (ProcessedSilentlyException &e) {
}
catch (ProcessedQueued &e) {
packet_queued = true;
}
}
catch (InvalidIncomingDataException &e) {
}
catch (ProcessedSilentlyException &e) {
}
}
}
bool ConnectionReceiveThread::getFromBuffers(session_t &peer_id, SharedBuffer<u8> &dst)
{
std::list<session_t> peerids = m_connection->getPeerIDs();
for (session_t peerid : peerids) {
PeerHelper peer = m_connection->getPeerNoEx(peerid);
if (!peer)
continue;
if (dynamic_cast<UDPPeer *>(&peer) == 0)
continue;
for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
if (checkIncomingBuffers(&channel, peer_id, dst)) {
return true;
}
}
}
return false;
}
bool ConnectionReceiveThread::checkIncomingBuffers(Channel *channel,
session_t &peer_id, SharedBuffer<u8> &dst)
{
u16 firstseqnum = 0;
if (channel->incoming_reliables.getFirstSeqnum(firstseqnum)) {
if (firstseqnum == channel->readNextIncomingSeqNum()) {
BufferedPacket p = channel->incoming_reliables.popFirst();
peer_id = readPeerId(*p.data);
u8 channelnum = readChannel(*p.data);
u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE + 1]);
LOG(dout_con << m_connection->getDesc()
<< "UNBUFFERING TYPE_RELIABLE"
<< " seqnum=" << seqnum
<< " peer_id=" << peer_id
<< " channel=" << ((int) channelnum & 0xff)
<< std::endl);
channel->incNextIncomingSeqNum();
u32 headers_size = BASE_HEADER_SIZE + RELIABLE_HEADER_SIZE;
// Get out the inside packet and re-process it
SharedBuffer<u8> payload(p.data.getSize() - headers_size);
memcpy(*payload, &p.data[headers_size], payload.getSize());
dst = processPacket(channel, payload, peer_id, channelnum, true);
return true;
}
}
return false;
}
SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
SharedBuffer<u8> packetdata, session_t peer_id, u8 channelnum, bool reliable)
{
PeerHelper peer = m_connection->getPeerNoEx(peer_id);
if (!peer) {
errorstream << "Peer not found (possible timeout)" << std::endl;
throw ProcessedSilentlyException("Peer not found (possible timeout)");
}
if (packetdata.getSize() < 1)
throw InvalidIncomingDataException("packetdata.getSize() < 1");
u8 type = readU8(&(packetdata[0]));
if (MAX_UDP_PEERS <= 65535 && peer_id >= MAX_UDP_PEERS) {
std::string errmsg = "Invalid peer_id=" + itos(peer_id);
errorstream << errmsg << std::endl;
throw InvalidIncomingDataException(errmsg.c_str());
}
if (type >= PACKET_TYPE_MAX) {
derr_con << m_connection->getDesc() << "Got invalid type=" << ((int) type & 0xff)
<< std::endl;
throw InvalidIncomingDataException("Invalid packet type");
}
const PacketTypeHandler &pHandle = packetTypeRouter[type];
return (this->*pHandle.handler)(channel, packetdata, &peer, channelnum, reliable);
}
const ConnectionReceiveThread::PacketTypeHandler
ConnectionReceiveThread::packetTypeRouter[PACKET_TYPE_MAX] = {
{&ConnectionReceiveThread::handlePacketType_Control},
{&ConnectionReceiveThread::handlePacketType_Original},
{&ConnectionReceiveThread::handlePacketType_Split},
{&ConnectionReceiveThread::handlePacketType_Reliable},
};
SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Control(Channel *channel,
SharedBuffer<u8> packetdata, Peer *peer, u8 channelnum, bool reliable)
{
if (packetdata.getSize() < 2)
throw InvalidIncomingDataException("packetdata.getSize() < 2");
u8 controltype = readU8(&(packetdata[1]));
if (controltype == CONTROLTYPE_ACK) {
assert(channel != NULL);
if (packetdata.getSize() < 4) {
throw InvalidIncomingDataException(
"packetdata.getSize() < 4 (ACK header size)");
}
u16 seqnum = readU16(&packetdata[2]);
LOG(dout_con << m_connection->getDesc() << " [ CONTROLTYPE_ACK: channelnum="
<< ((int) channelnum & 0xff) << ", peer_id=" << peer->id << ", seqnum="
<< seqnum << " ]" << std::endl);
try {
BufferedPacket p = channel->outgoing_reliables_sent.popSeqnum(seqnum);
// only calculate rtt from straight sent packets
if (p.resend_count == 0) {
// Get round trip time
u64 current_time = porting::getTimeMs();
// a overflow is quite unlikely but as it'd result in major
// rtt miscalculation we handle it here
if (current_time > p.absolute_send_time) {
float rtt = (current_time - p.absolute_send_time) / 1000.0;
// Let peer calculate stuff according to it
// (avg_rtt and resend_timeout)
dynamic_cast<UDPPeer *>(peer)->reportRTT(rtt);
} else if (p.totaltime > 0) {
float rtt = p.totaltime;
// Let peer calculate stuff according to it
// (avg_rtt and resend_timeout)
dynamic_cast<UDPPeer *>(peer)->reportRTT(rtt);
}
}
// put bytes for max bandwidth calculation
channel->UpdateBytesSent(p.data.getSize(), 1);
if (channel->outgoing_reliables_sent.size() == 0)
m_connection->TriggerSend();
} catch (NotFoundException &e) {
LOG(derr_con << m_connection->getDesc()
<< "WARNING: ACKed packet not in outgoing queue" << std::endl);
channel->UpdatePacketTooLateCounter();
}
throw ProcessedSilentlyException("Got an ACK");
} else if (controltype == CONTROLTYPE_SET_PEER_ID) {
// Got a packet to set our peer id
if (packetdata.getSize() < 4)
throw InvalidIncomingDataException
("packetdata.getSize() < 4 (SET_PEER_ID header size)");
session_t peer_id_new = readU16(&packetdata[2]);
LOG(dout_con << m_connection->getDesc() << "Got new peer id: " << peer_id_new
<< "... " << std::endl);
if (m_connection->GetPeerID() != PEER_ID_INEXISTENT) {
LOG(derr_con << m_connection->getDesc()
<< "WARNING: Not changing existing peer id." << std::endl);
} else {
LOG(dout_con << m_connection->getDesc() << "changing own peer id"
<< std::endl);
m_connection->SetPeerID(peer_id_new);
}
throw ProcessedSilentlyException("Got a SET_PEER_ID");
} else if (controltype == CONTROLTYPE_PING) {
// Just ignore it, the incoming data already reset
// the timeout counter
LOG(dout_con << m_connection->getDesc() << "PING" << std::endl);
throw ProcessedSilentlyException("Got a PING");
} else if (controltype == CONTROLTYPE_DISCO) {
// Just ignore it, the incoming data already reset
// the timeout counter
LOG(dout_con << m_connection->getDesc() << "DISCO: Removing peer "
<< peer->id << std::endl);
if (!m_connection->deletePeer(peer->id, false)) {
derr_con << m_connection->getDesc() << "DISCO: Peer not found" << std::endl;
}
throw ProcessedSilentlyException("Got a DISCO");
} else {
LOG(derr_con << m_connection->getDesc()
<< "INVALID TYPE_CONTROL: invalid controltype="
<< ((int) controltype & 0xff) << std::endl);
throw InvalidIncomingDataException("Invalid control type");
}
}
SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Original(Channel *channel,
SharedBuffer<u8> packetdata, Peer *peer, u8 channelnum, bool reliable)
{
if (packetdata.getSize() <= ORIGINAL_HEADER_SIZE)
throw InvalidIncomingDataException
("packetdata.getSize() <= ORIGINAL_HEADER_SIZE");
LOG(dout_con << m_connection->getDesc() << "RETURNING TYPE_ORIGINAL to user"
<< std::endl);
// Get the inside packet out and return it
SharedBuffer<u8> payload(packetdata.getSize() - ORIGINAL_HEADER_SIZE);
memcpy(*payload, &(packetdata[ORIGINAL_HEADER_SIZE]), payload.getSize());
return payload;
}
SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Split(Channel *channel,
SharedBuffer<u8> packetdata, Peer *peer, u8 channelnum, bool reliable)
{
Address peer_address;
if (peer->getAddress(MTP_UDP, peer_address)) {
// We have to create a packet again for buffering
// This isn't actually too bad an idea.
BufferedPacket packet = makePacket(peer_address,
packetdata,
m_connection->GetProtocolID(),
peer->id,
channelnum);
// Buffer the packet
SharedBuffer<u8> data = peer->addSplitPacket(channelnum, packet, reliable);
if (data.getSize() != 0) {
LOG(dout_con << m_connection->getDesc()
<< "RETURNING TYPE_SPLIT: Constructed full data, "
<< "size=" << data.getSize() << std::endl);
return data;
}
LOG(dout_con << m_connection->getDesc() << "BUFFERED TYPE_SPLIT" << std::endl);
throw ProcessedSilentlyException("Buffered a split packet chunk");
}
// We should never get here.
FATAL_ERROR("Invalid execution point");
}
SharedBuffer<u8> ConnectionReceiveThread::handlePacketType_Reliable(Channel *channel,
SharedBuffer<u8> packetdata, Peer *peer, u8 channelnum, bool reliable)
{
assert(channel != NULL);
// Recursive reliable packets not allowed
if (reliable)
throw InvalidIncomingDataException("Found nested reliable packets");
if (packetdata.getSize() < RELIABLE_HEADER_SIZE)
throw InvalidIncomingDataException("packetdata.getSize() < RELIABLE_HEADER_SIZE");
u16 seqnum = readU16(&packetdata[1]);
bool is_future_packet = false;
bool is_old_packet = false;
/* packet is within our receive window send ack */
if (seqnum_in_window(seqnum,
channel->readNextIncomingSeqNum(), MAX_RELIABLE_WINDOW_SIZE)) {
m_connection->sendAck(peer->id, channelnum, seqnum);
} else {
is_future_packet = seqnum_higher(seqnum, channel->readNextIncomingSeqNum());
is_old_packet = seqnum_higher(channel->readNextIncomingSeqNum(), seqnum);
/* packet is not within receive window, don't send ack. *
* if this was a valid packet it's gonna be retransmitted */
if (is_future_packet)
throw ProcessedSilentlyException(
"Received packet newer then expected, not sending ack");
/* seems like our ack was lost, send another one for a old packet */
if (is_old_packet) {
LOG(dout_con << m_connection->getDesc()
<< "RE-SENDING ACK: peer_id: " << peer->id
<< ", channel: " << (channelnum & 0xFF)
<< ", seqnum: " << seqnum << std::endl;)
m_connection->sendAck(peer->id, channelnum, seqnum);
// we already have this packet so this one was on wire at least
// the current timeout
// we don't know how long this packet was on wire don't do silly guessing
// dynamic_cast<UDPPeer*>(&peer)->
// reportRTT(dynamic_cast<UDPPeer*>(&peer)->getResendTimeout());
throw ProcessedSilentlyException("Retransmitting ack for old packet");
}
}
if (seqnum != channel->readNextIncomingSeqNum()) {
Address peer_address;
// this is a reliable packet so we have a udp address for sure
peer->getAddress(MTP_MINETEST_RELIABLE_UDP, peer_address);
// This one comes later, buffer it.
// Actually we have to make a packet to buffer one.
// Well, we have all the ingredients, so just do it.
BufferedPacket packet = con::makePacket(
peer_address,
packetdata,
m_connection->GetProtocolID(),
peer->id,
channelnum);
try {
channel->incoming_reliables.insert(packet, channel->readNextIncomingSeqNum());
LOG(dout_con << m_connection->getDesc()
<< "BUFFERING, TYPE_RELIABLE peer_id: " << peer->id
<< ", channel: " << (channelnum & 0xFF)
<< ", seqnum: " << seqnum << std::endl;)
throw ProcessedQueued("Buffered future reliable packet");
} catch (AlreadyExistsException &e) {
} catch (IncomingDataCorruption &e) {
ConnectionCommand discon;
discon.disconnect_peer(peer->id);
m_connection->putCommand(discon);
LOG(derr_con << m_connection->getDesc()
<< "INVALID, TYPE_RELIABLE peer_id: " << peer->id
<< ", channel: " << (channelnum & 0xFF)
<< ", seqnum: " << seqnum
<< "DROPPING CLIENT!" << std::endl;)
}
}
/* we got a packet to process right now */
LOG(dout_con << m_connection->getDesc()
<< "RECURSIVE, TYPE_RELIABLE peer_id: " << peer->id
<< ", channel: " << (channelnum & 0xFF)
<< ", seqnum: " << seqnum << std::endl;)
/* check for resend case */
u16 queued_seqnum = 0;
if (channel->incoming_reliables.getFirstSeqnum(queued_seqnum)) {
if (queued_seqnum == seqnum) {
BufferedPacket queued_packet = channel->incoming_reliables.popFirst();
/** TODO find a way to verify the new against the old packet */
}
}
channel->incNextIncomingSeqNum();
// Get out the inside packet and re-process it
SharedBuffer<u8> payload(packetdata.getSize() - RELIABLE_HEADER_SIZE);
memcpy(*payload, &packetdata[RELIABLE_HEADER_SIZE], payload.getSize());
return processPacket(channel, payload, peer->id, channelnum, true);
}
}
| pgimeno/minetest | src/network/connectionthreads.cpp | C++ | mit | 42,235 |
/*
Minetest
Copyright (C) 2013-2017 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2017 celeron55, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include <cassert>
#include "threading/thread.h"
#include "connection.h"
namespace con
{
class Connection;
class ConnectionSendThread : public Thread
{
public:
friend class UDPPeer;
ConnectionSendThread(unsigned int max_packet_size, float timeout);
void *run();
void Trigger();
void setParent(Connection *parent)
{
assert(parent != NULL); // Pre-condition
m_connection = parent;
}
void setPeerTimeout(float peer_timeout) { m_timeout = peer_timeout; }
private:
void runTimeouts(float dtime);
void rawSend(const BufferedPacket &packet);
bool rawSendAsPacket(session_t peer_id, u8 channelnum, SharedBuffer<u8> data,
bool reliable);
void processReliableCommand(ConnectionCommand &c);
void processNonReliableCommand(ConnectionCommand &c);
void serve(Address bind_address);
void connect(Address address);
void disconnect();
void disconnect_peer(session_t peer_id);
void send(session_t peer_id, u8 channelnum, SharedBuffer<u8> data);
void sendReliable(ConnectionCommand &c);
void sendToAll(u8 channelnum, SharedBuffer<u8> data);
void sendToAllReliable(ConnectionCommand &c);
void sendPackets(float dtime);
void sendAsPacket(session_t peer_id, u8 channelnum, SharedBuffer<u8> data,
bool ack = false);
void sendAsPacketReliable(BufferedPacket &p, Channel *channel);
bool packetsQueued();
Connection *m_connection = nullptr;
unsigned int m_max_packet_size;
float m_timeout;
std::queue<OutgoingPacket> m_outgoing_queue;
Semaphore m_send_sleep_semaphore;
unsigned int m_iteration_packets_avaialble;
unsigned int m_max_commands_per_iteration = 1;
unsigned int m_max_data_packets_per_iteration;
unsigned int m_max_packets_requeued = 256;
};
class ConnectionReceiveThread : public Thread
{
public:
ConnectionReceiveThread(unsigned int max_packet_size);
void *run();
void setParent(Connection *parent)
{
assert(parent); // Pre-condition
m_connection = parent;
}
private:
void receive();
// Returns next data from a buffer if possible
// If found, returns true; if not, false.
// If found, sets peer_id and dst
bool getFromBuffers(session_t &peer_id, SharedBuffer<u8> &dst);
bool checkIncomingBuffers(
Channel *channel, session_t &peer_id, SharedBuffer<u8> &dst);
/*
Processes a packet with the basic header stripped out.
Parameters:
packetdata: Data in packet (with no base headers)
peer_id: peer id of the sender of the packet in question
channelnum: channel on which the packet was sent
reliable: true if recursing into a reliable packet
*/
SharedBuffer<u8> processPacket(Channel *channel, SharedBuffer<u8> packetdata,
session_t peer_id, u8 channelnum, bool reliable);
SharedBuffer<u8> handlePacketType_Control(Channel *channel,
SharedBuffer<u8> packetdata, Peer *peer, u8 channelnum,
bool reliable);
SharedBuffer<u8> handlePacketType_Original(Channel *channel,
SharedBuffer<u8> packetdata, Peer *peer, u8 channelnum,
bool reliable);
SharedBuffer<u8> handlePacketType_Split(Channel *channel,
SharedBuffer<u8> packetdata, Peer *peer, u8 channelnum,
bool reliable);
SharedBuffer<u8> handlePacketType_Reliable(Channel *channel,
SharedBuffer<u8> packetdata, Peer *peer, u8 channelnum,
bool reliable);
struct PacketTypeHandler
{
SharedBuffer<u8> (ConnectionReceiveThread::*handler)(Channel *channel,
SharedBuffer<u8> packet, Peer *peer, u8 channelnum,
bool reliable);
};
static const PacketTypeHandler packetTypeRouter[PACKET_TYPE_MAX];
Connection *m_connection = nullptr;
};
}
| pgimeno/minetest | src/network/connectionthreads.h | C++ | mit | 4,389 |
/*
Minetest
Copyright (C) 2013-2017 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "exceptions.h"
namespace con
{
/*
Exceptions
*/
class NotFoundException : public BaseException
{
public:
NotFoundException(const char *s) : BaseException(s) {}
};
class PeerNotFoundException : public BaseException
{
public:
PeerNotFoundException(const char *s) : BaseException(s) {}
};
class ConnectionException : public BaseException
{
public:
ConnectionException(const char *s) : BaseException(s) {}
};
class ConnectionBindFailed : public BaseException
{
public:
ConnectionBindFailed(const char *s) : BaseException(s) {}
};
class InvalidIncomingDataException : public BaseException
{
public:
InvalidIncomingDataException(const char *s) : BaseException(s) {}
};
class InvalidOutgoingDataException : public BaseException
{
public:
InvalidOutgoingDataException(const char *s) : BaseException(s) {}
};
class NoIncomingDataException : public BaseException
{
public:
NoIncomingDataException(const char *s) : BaseException(s) {}
};
class ProcessedSilentlyException : public BaseException
{
public:
ProcessedSilentlyException(const char *s) : BaseException(s) {}
};
class ProcessedQueued : public BaseException
{
public:
ProcessedQueued(const char *s) : BaseException(s) {}
};
class IncomingDataCorruption : public BaseException
{
public:
IncomingDataCorruption(const char *s) : BaseException(s) {}
};
}
class SocketException : public BaseException
{
public:
SocketException(const std::string &s) : BaseException(s) {}
};
class ResolveError : public BaseException
{
public:
ResolveError(const std::string &s) : BaseException(s) {}
};
class SendFailedException : public BaseException
{
public:
SendFailedException(const std::string &s) : BaseException(s) {}
}; | pgimeno/minetest | src/network/networkexceptions.h | C++ | mit | 2,493 |
/*
Minetest
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "networkpacket.h"
#include <sstream>
#include "networkexceptions.h"
#include "util/serialize.h"
#include "networkprotocol.h"
NetworkPacket::NetworkPacket(u16 command, u32 datasize, session_t peer_id):
m_datasize(datasize), m_command(command), m_peer_id(peer_id)
{
m_data.resize(m_datasize);
}
NetworkPacket::NetworkPacket(u16 command, u32 datasize):
m_datasize(datasize), m_command(command)
{
m_data.resize(m_datasize);
}
NetworkPacket::~NetworkPacket()
{
m_data.clear();
}
void NetworkPacket::checkReadOffset(u32 from_offset, u32 field_size)
{
if (from_offset + field_size > m_datasize) {
std::stringstream ss;
ss << "Reading outside packet (offset: " <<
from_offset << ", packet size: " << getSize() << ")";
throw PacketError(ss.str());
}
}
void NetworkPacket::putRawPacket(u8 *data, u32 datasize, session_t peer_id)
{
// If a m_command is already set, we are rewriting on same packet
// This is not permitted
assert(m_command == 0);
m_datasize = datasize - 2;
m_peer_id = peer_id;
m_data.resize(m_datasize);
// split command and datas
m_command = readU16(&data[0]);
memcpy(m_data.data(), &data[2], m_datasize);
}
const char* NetworkPacket::getString(u32 from_offset)
{
checkReadOffset(from_offset, 0);
return (char*)&m_data[from_offset];
}
void NetworkPacket::putRawString(const char* src, u32 len)
{
if (m_read_offset + len > m_datasize) {
m_datasize = m_read_offset + len;
m_data.resize(m_datasize);
}
if (len == 0)
return;
memcpy(&m_data[m_read_offset], src, len);
m_read_offset += len;
}
NetworkPacket& NetworkPacket::operator>>(std::string& dst)
{
checkReadOffset(m_read_offset, 2);
u16 strLen = readU16(&m_data[m_read_offset]);
m_read_offset += 2;
dst.clear();
if (strLen == 0) {
return *this;
}
checkReadOffset(m_read_offset, strLen);
dst.reserve(strLen);
dst.append((char*)&m_data[m_read_offset], strLen);
m_read_offset += strLen;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(const std::string &src)
{
if (src.size() > STRING_MAX_LEN) {
throw PacketError("String too long");
}
u16 msgsize = src.size();
*this << msgsize;
putRawString(src.c_str(), (u32)msgsize);
return *this;
}
void NetworkPacket::putLongString(const std::string &src)
{
if (src.size() > LONG_STRING_MAX_LEN) {
throw PacketError("String too long");
}
u32 msgsize = src.size();
*this << msgsize;
putRawString(src.c_str(), msgsize);
}
NetworkPacket& NetworkPacket::operator>>(std::wstring& dst)
{
checkReadOffset(m_read_offset, 2);
u16 strLen = readU16(&m_data[m_read_offset]);
m_read_offset += 2;
dst.clear();
if (strLen == 0) {
return *this;
}
checkReadOffset(m_read_offset, strLen * 2);
dst.reserve(strLen);
for(u16 i=0; i<strLen; i++) {
wchar_t c16 = readU16(&m_data[m_read_offset]);
dst.append(&c16, 1);
m_read_offset += sizeof(u16);
}
return *this;
}
NetworkPacket& NetworkPacket::operator<<(const std::wstring &src)
{
if (src.size() > WIDE_STRING_MAX_LEN) {
throw PacketError("String too long");
}
u16 msgsize = src.size();
*this << msgsize;
// Write string
for (u16 i=0; i<msgsize; i++) {
*this << (u16) src[i];
}
return *this;
}
std::string NetworkPacket::readLongString()
{
checkReadOffset(m_read_offset, 4);
u32 strLen = readU32(&m_data[m_read_offset]);
m_read_offset += 4;
if (strLen == 0) {
return "";
}
if (strLen > LONG_STRING_MAX_LEN) {
throw PacketError("String too long");
}
checkReadOffset(m_read_offset, strLen);
std::string dst;
dst.reserve(strLen);
dst.append((char*)&m_data[m_read_offset], strLen);
m_read_offset += strLen;
return dst;
}
NetworkPacket& NetworkPacket::operator>>(char& dst)
{
checkReadOffset(m_read_offset, 1);
dst = readU8(&m_data[m_read_offset]);
m_read_offset += 1;
return *this;
}
char NetworkPacket::getChar(u32 offset)
{
checkReadOffset(offset, 1);
return readU8(&m_data[offset]);
}
NetworkPacket& NetworkPacket::operator<<(char src)
{
checkDataSize(1);
writeU8(&m_data[m_read_offset], src);
m_read_offset += 1;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(u8 src)
{
checkDataSize(1);
writeU8(&m_data[m_read_offset], src);
m_read_offset += 1;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(bool src)
{
checkDataSize(1);
writeU8(&m_data[m_read_offset], src);
m_read_offset += 1;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(u16 src)
{
checkDataSize(2);
writeU16(&m_data[m_read_offset], src);
m_read_offset += 2;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(u32 src)
{
checkDataSize(4);
writeU32(&m_data[m_read_offset], src);
m_read_offset += 4;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(u64 src)
{
checkDataSize(8);
writeU64(&m_data[m_read_offset], src);
m_read_offset += 8;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(float src)
{
checkDataSize(4);
writeF32(&m_data[m_read_offset], src);
m_read_offset += 4;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(bool& dst)
{
checkReadOffset(m_read_offset, 1);
dst = readU8(&m_data[m_read_offset]);
m_read_offset += 1;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(u8& dst)
{
checkReadOffset(m_read_offset, 1);
dst = readU8(&m_data[m_read_offset]);
m_read_offset += 1;
return *this;
}
u8 NetworkPacket::getU8(u32 offset)
{
checkReadOffset(offset, 1);
return readU8(&m_data[offset]);
}
u8* NetworkPacket::getU8Ptr(u32 from_offset)
{
if (m_datasize == 0) {
return NULL;
}
checkReadOffset(from_offset, 1);
return (u8*)&m_data[from_offset];
}
NetworkPacket& NetworkPacket::operator>>(u16& dst)
{
checkReadOffset(m_read_offset, 2);
dst = readU16(&m_data[m_read_offset]);
m_read_offset += 2;
return *this;
}
u16 NetworkPacket::getU16(u32 from_offset)
{
checkReadOffset(from_offset, 2);
return readU16(&m_data[from_offset]);
}
NetworkPacket& NetworkPacket::operator>>(u32& dst)
{
checkReadOffset(m_read_offset, 4);
dst = readU32(&m_data[m_read_offset]);
m_read_offset += 4;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(u64& dst)
{
checkReadOffset(m_read_offset, 8);
dst = readU64(&m_data[m_read_offset]);
m_read_offset += 8;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(float& dst)
{
checkReadOffset(m_read_offset, 4);
dst = readF32(&m_data[m_read_offset]);
m_read_offset += 4;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(v2f& dst)
{
checkReadOffset(m_read_offset, 8);
dst = readV2F32(&m_data[m_read_offset]);
m_read_offset += 8;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(v3f& dst)
{
checkReadOffset(m_read_offset, 12);
dst = readV3F32(&m_data[m_read_offset]);
m_read_offset += 12;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(s16& dst)
{
checkReadOffset(m_read_offset, 2);
dst = readS16(&m_data[m_read_offset]);
m_read_offset += 2;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(s16 src)
{
*this << (u16) src;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(s32& dst)
{
checkReadOffset(m_read_offset, 4);
dst = readS32(&m_data[m_read_offset]);
m_read_offset += 4;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(s32 src)
{
*this << (u32) src;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(v3s16& dst)
{
checkReadOffset(m_read_offset, 6);
dst = readV3S16(&m_data[m_read_offset]);
m_read_offset += 6;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(v2s32& dst)
{
checkReadOffset(m_read_offset, 8);
dst = readV2S32(&m_data[m_read_offset]);
m_read_offset += 8;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(v3s32& dst)
{
checkReadOffset(m_read_offset, 12);
dst = readV3S32(&m_data[m_read_offset]);
m_read_offset += 12;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(v2f src)
{
*this << (float) src.X;
*this << (float) src.Y;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(v3f src)
{
*this << (float) src.X;
*this << (float) src.Y;
*this << (float) src.Z;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(v3s16 src)
{
*this << (s16) src.X;
*this << (s16) src.Y;
*this << (s16) src.Z;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(v2s32 src)
{
*this << (s32) src.X;
*this << (s32) src.Y;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(v3s32 src)
{
*this << (s32) src.X;
*this << (s32) src.Y;
*this << (s32) src.Z;
return *this;
}
NetworkPacket& NetworkPacket::operator>>(video::SColor& dst)
{
checkReadOffset(m_read_offset, 4);
dst = readARGB8(&m_data[m_read_offset]);
m_read_offset += 4;
return *this;
}
NetworkPacket& NetworkPacket::operator<<(video::SColor src)
{
checkDataSize(4);
writeU32(&m_data[m_read_offset], src.color);
m_read_offset += 4;
return *this;
}
SharedBuffer<u8> NetworkPacket::oldForgePacket()
{
SharedBuffer<u8> sb(m_datasize + 2);
writeU16(&sb[0], m_command);
u8* datas = getU8Ptr(0);
if (datas != NULL)
memcpy(&sb[2], datas, m_datasize);
return sb;
}
| pgimeno/minetest | src/network/networkpacket.cpp | C++ | mit | 9,784 |
/*
Minetest
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "util/pointer.h"
#include "util/numeric.h"
#include "networkprotocol.h"
#include <SColor.h>
class NetworkPacket
{
public:
NetworkPacket(u16 command, u32 datasize, session_t peer_id);
NetworkPacket(u16 command, u32 datasize);
NetworkPacket() = default;
~NetworkPacket();
void putRawPacket(u8 *data, u32 datasize, session_t peer_id);
// Getters
u32 getSize() const { return m_datasize; }
session_t getPeerId() const { return m_peer_id; }
u16 getCommand() { return m_command; }
const u32 getRemainingBytes() const { return m_datasize - m_read_offset; }
const char *getRemainingString() { return getString(m_read_offset); }
// Returns a c-string without copying.
// A better name for this would be getRawString()
const char *getString(u32 from_offset);
// major difference to putCString(): doesn't write len into the buffer
void putRawString(const char *src, u32 len);
void putRawString(const std::string &src)
{
putRawString(src.c_str(), src.size());
}
NetworkPacket &operator>>(std::string &dst);
NetworkPacket &operator<<(const std::string &src);
void putLongString(const std::string &src);
NetworkPacket &operator>>(std::wstring &dst);
NetworkPacket &operator<<(const std::wstring &src);
std::string readLongString();
char getChar(u32 offset);
NetworkPacket &operator>>(char &dst);
NetworkPacket &operator<<(char src);
NetworkPacket &operator>>(bool &dst);
NetworkPacket &operator<<(bool src);
u8 getU8(u32 offset);
NetworkPacket &operator>>(u8 &dst);
NetworkPacket &operator<<(u8 src);
u8 *getU8Ptr(u32 offset);
u16 getU16(u32 from_offset);
NetworkPacket &operator>>(u16 &dst);
NetworkPacket &operator<<(u16 src);
NetworkPacket &operator>>(u32 &dst);
NetworkPacket &operator<<(u32 src);
NetworkPacket &operator>>(u64 &dst);
NetworkPacket &operator<<(u64 src);
NetworkPacket &operator>>(float &dst);
NetworkPacket &operator<<(float src);
NetworkPacket &operator>>(v2f &dst);
NetworkPacket &operator<<(v2f src);
NetworkPacket &operator>>(v3f &dst);
NetworkPacket &operator<<(v3f src);
NetworkPacket &operator>>(s16 &dst);
NetworkPacket &operator<<(s16 src);
NetworkPacket &operator>>(s32 &dst);
NetworkPacket &operator<<(s32 src);
NetworkPacket &operator>>(v2s32 &dst);
NetworkPacket &operator<<(v2s32 src);
NetworkPacket &operator>>(v3s16 &dst);
NetworkPacket &operator<<(v3s16 src);
NetworkPacket &operator>>(v3s32 &dst);
NetworkPacket &operator<<(v3s32 src);
NetworkPacket &operator>>(video::SColor &dst);
NetworkPacket &operator<<(video::SColor src);
// Temp, we remove SharedBuffer when migration finished
SharedBuffer<u8> oldForgePacket();
private:
void checkReadOffset(u32 from_offset, u32 field_size);
inline void checkDataSize(u32 field_size)
{
if (m_read_offset + field_size > m_datasize) {
m_datasize = m_read_offset + field_size;
m_data.resize(m_datasize);
}
}
std::vector<u8> m_data;
u32 m_datasize = 0;
u32 m_read_offset = 0;
u16 m_command = 0;
session_t m_peer_id = 0;
};
| pgimeno/minetest | src/network/networkpacket.h | C++ | mit | 3,811 |
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "util/string.h"
/*
changes by PROTOCOL_VERSION:
PROTOCOL_VERSION 3:
Base for writing changes here
PROTOCOL_VERSION 4:
Add TOCLIENT_MEDIA
Add TOCLIENT_TOOLDEF
Add TOCLIENT_NODEDEF
Add TOCLIENT_CRAFTITEMDEF
Add TOSERVER_INTERACT
Obsolete TOSERVER_CLICK_ACTIVEOBJECT
Obsolete TOSERVER_GROUND_ACTION
PROTOCOL_VERSION 5:
Make players to be handled mostly as ActiveObjects
PROTOCOL_VERSION 6:
Only non-cached textures are sent
PROTOCOL_VERSION 7:
Add TOCLIENT_ITEMDEF
Obsolete TOCLIENT_TOOLDEF
Obsolete TOCLIENT_CRAFTITEMDEF
Compress the contents of TOCLIENT_ITEMDEF and TOCLIENT_NODEDEF
PROTOCOL_VERSION 8:
Digging based on item groups
Many things
PROTOCOL_VERSION 9:
ContentFeatures and NodeDefManager use a different serialization
format; better for future version cross-compatibility
Many things
Obsolete TOCLIENT_PLAYERITEM
PROTOCOL_VERSION 10:
TOCLIENT_PRIVILEGES
Version raised to force 'fly' and 'fast' privileges into effect.
Node metadata change (came in later; somewhat incompatible)
PROTOCOL_VERSION 11:
TileDef in ContentFeatures
Nodebox drawtype
(some dev snapshot)
TOCLIENT_INVENTORY_FORMSPEC
(0.4.0, 0.4.1)
PROTOCOL_VERSION 12:
TOSERVER_INVENTORY_FIELDS
16-bit node ids
TOCLIENT_DETACHED_INVENTORY
PROTOCOL_VERSION 13:
InventoryList field "Width" (deserialization fails with old versions)
PROTOCOL_VERSION 14:
Added transfer of player pressed keys to the server
Added new messages for mesh and bone animation, as well as attachments
GENERIC_CMD_SET_ANIMATION
GENERIC_CMD_SET_BONE_POSITION
GENERIC_CMD_SET_ATTACHMENT
PROTOCOL_VERSION 15:
Serialization format changes
PROTOCOL_VERSION 16:
TOCLIENT_SHOW_FORMSPEC
PROTOCOL_VERSION 17:
Serialization format change: include backface_culling flag in TileDef
Added rightclickable field in nodedef
TOCLIENT_SPAWN_PARTICLE
TOCLIENT_ADD_PARTICLESPAWNER
TOCLIENT_DELETE_PARTICLESPAWNER
PROTOCOL_VERSION 18:
damageGroups added to ToolCapabilities
sound_place added to ItemDefinition
PROTOCOL_VERSION 19:
GENERIC_CMD_SET_PHYSICS_OVERRIDE
PROTOCOL_VERSION 20:
TOCLIENT_HUDADD
TOCLIENT_HUDRM
TOCLIENT_HUDCHANGE
TOCLIENT_HUD_SET_FLAGS
PROTOCOL_VERSION 21:
TOCLIENT_BREATH
TOSERVER_BREATH
range added to ItemDefinition
drowning, leveled and liquid_range added to ContentFeatures
stepheight and collideWithObjects added to object properties
version, heat and humidity transfer in MapBock
automatic_face_movement_dir and automatic_face_movement_dir_offset
added to object properties
PROTOCOL_VERSION 22:
add swap_node
PROTOCOL_VERSION 23:
Obsolete TOSERVER_RECEIVED_MEDIA
Server: Stop using TOSERVER_CLIENT_READY
PROTOCOL_VERSION 24:
ContentFeatures version 7
ContentFeatures: change number of special tiles to 6 (CF_SPECIAL_COUNT)
PROTOCOL_VERSION 25:
Rename TOCLIENT_ACCESS_DENIED to TOCLIENT_ACCESS_DENIED_LEGAGY
Rename TOCLIENT_DELETE_PARTICLESPAWNER to
TOCLIENT_DELETE_PARTICLESPAWNER_LEGACY
Rename TOSERVER_PASSWORD to TOSERVER_PASSWORD_LEGACY
Rename TOSERVER_INIT to TOSERVER_INIT_LEGACY
Rename TOCLIENT_INIT to TOCLIENT_INIT_LEGACY
Add TOCLIENT_ACCESS_DENIED new opcode (0x0A), using error codes
for standard error, keeping customisation possible. This
permit translation
Add TOCLIENT_DELETE_PARTICLESPAWNER (0x53), fixing the u16 read and
reading u32
Add new opcode TOSERVER_INIT for client presentation to server
Add new opcodes TOSERVER_FIRST_SRP, TOSERVER_SRP_BYTES_A,
TOSERVER_SRP_BYTES_M, TOCLIENT_SRP_BYTES_S_B
for the three supported auth mechanisms around srp
Add new opcodes TOCLIENT_ACCEPT_SUDO_MODE and TOCLIENT_DENY_SUDO_MODE
for sudo mode handling (auth mech generic way of changing password).
Add TOCLIENT_HELLO for presenting server to client after client
presentation
Add TOCLIENT_AUTH_ACCEPT to accept connection from client
Rename GENERIC_CMD_SET_ATTACHMENT to GENERIC_CMD_ATTACH_TO
PROTOCOL_VERSION 26:
Add TileDef tileable_horizontal, tileable_vertical flags
PROTOCOL_VERSION 27:
backface_culling: backwards compatibility for playing with
newer client on pre-27 servers.
Add nodedef v3 - connected nodeboxes
PROTOCOL_VERSION 28:
CPT2_MESHOPTIONS
PROTOCOL_VERSION 29:
Server doesn't accept TOSERVER_BREATH anymore
serialization of TileAnimation params changed
TAT_SHEET_2D
Removed client-sided chat perdiction
PROTOCOL VERSION 30:
New ContentFeatures serialization version
Add node and tile color and palette
Fix plantlike visual_scale being applied squared and add compatibility
with pre-30 clients by sending sqrt(visual_scale)
PROTOCOL VERSION 31:
Add tile overlay
Stop sending TOSERVER_CLIENT_READY
PROTOCOL VERSION 32:
Add fading sounds
PROTOCOL VERSION 33:
Add TOCLIENT_UPDATE_PLAYER_LIST and send the player list to the client,
instead of guessing based on the active object list.
PROTOCOL VERSION 34:
Add sound pitch
PROTOCOL VERSION 35:
Rename TOCLIENT_CHAT_MESSAGE to TOCLIENT_CHAT_MESSAGE_OLD (0x30)
Add TOCLIENT_CHAT_MESSAGE (0x2F)
This chat message is a signalisation message containing various
informations:
* timestamp
* sender
* type (RAW, NORMAL, ANNOUNCE, SYSTEM)
* content
Add TOCLIENT_CSM_RESTRICTION_FLAGS to define which CSM features should be
limited
Add settable player collisionbox. Breaks compatibility with older
clients as a 1-node vertical offset has been removed from player's
position
Add settable player stepheight using existing object property.
Breaks compatibility with older clients.
PROTOCOL VERSION 36:
Backwards compatibility drop
Add 'can_zoom' to player object properties
Add glow to object properties
Change TileDef serialization format.
Add world-aligned tiles.
Mod channels
Raise ObjectProperties version to 3 for removing 'can_zoom' and adding
'zoom_fov'.
Nodebox version 5
Add disconnected nodeboxes
Add TOCLIENT_FORMSPEC_PREPEND
PROTOCOL VERSION 37:
Redo detached inventory sending
Add TOCLIENT_NODEMETA_CHANGED
New network float format
ContentFeatures version 13
Add full Euler rotations instead of just yaw
*/
#define LATEST_PROTOCOL_VERSION 37
#define LATEST_PROTOCOL_VERSION_STRING TOSTRING(LATEST_PROTOCOL_VERSION)
// Server's supported network protocol range
#define SERVER_PROTOCOL_VERSION_MIN 37
#define SERVER_PROTOCOL_VERSION_MAX LATEST_PROTOCOL_VERSION
// Client's supported network protocol range
// The minimal version depends on whether
// send_pre_v25_init is enabled or not
#define CLIENT_PROTOCOL_VERSION_MIN 37
#define CLIENT_PROTOCOL_VERSION_MAX LATEST_PROTOCOL_VERSION
// Constant that differentiates the protocol from random data and other protocols
#define PROTOCOL_ID 0x4f457403
#define PASSWORD_SIZE 28 // Maximum password length. Allows for
// base64-encoded SHA-1 (27+\0).
#define FORMSPEC_API_VERSION 1
#define FORMSPEC_VERSION_STRING "formspec_version[" TOSTRING(FORMSPEC_API_VERSION) "]"
#define TEXTURENAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-"
typedef u16 session_t;
enum ToClientCommand
{
TOCLIENT_HELLO = 0x02,
/*
Sent after TOSERVER_INIT.
u8 deployed serialisation version
u16 deployed network compression mode
u16 deployed protocol version
u32 supported auth methods
std::string username that should be used for legacy hash (for proper casing)
*/
TOCLIENT_AUTH_ACCEPT = 0x03,
/*
Message from server to accept auth.
v3s16 player's position + v3f(0,BS/2,0) floatToInt'd
u64 map seed
f1000 recommended send interval
u32 : supported auth methods for sudo mode
(where the user can change their password)
*/
TOCLIENT_ACCEPT_SUDO_MODE = 0x04,
/*
Sent to client to show it is in sudo mode now.
*/
TOCLIENT_DENY_SUDO_MODE = 0x05,
/*
Signals client that sudo mode auth failed.
*/
TOCLIENT_ACCESS_DENIED = 0x0A,
/*
u8 reason
std::string custom reason (if needed, otherwise "")
u8 (bool) reconnect
*/
TOCLIENT_INIT_LEGACY = 0x10, // Obsolete
TOCLIENT_BLOCKDATA = 0x20, //TODO: Multiple blocks
TOCLIENT_ADDNODE = 0x21,
/*
v3s16 position
serialized mapnode
u8 keep_metadata // Added in protocol version 22
*/
TOCLIENT_REMOVENODE = 0x22,
TOCLIENT_PLAYERPOS = 0x23, // Obsolete
TOCLIENT_PLAYERINFO = 0x24, // Obsolete
TOCLIENT_OPT_BLOCK_NOT_FOUND = 0x25, // Obsolete
TOCLIENT_SECTORMETA = 0x26, // Obsolete
TOCLIENT_INVENTORY = 0x27,
/*
[0] u16 command
[2] serialized inventory
*/
TOCLIENT_OBJECTDATA = 0x28, // Obsolete
TOCLIENT_TIME_OF_DAY = 0x29,
/*
u16 time (0-23999)
Added in a later version:
f1000 time_speed
*/
TOCLIENT_CSM_RESTRICTION_FLAGS = 0x2A,
/*
u32 CSMRestrictionFlags byteflag
*/
// (oops, there is some gap here)
TOCLIENT_CHAT_MESSAGE = 0x2F,
/*
u8 version
u8 message_type
u16 sendername length
wstring sendername
u16 length
wstring message
*/
TOCLIENT_CHAT_MESSAGE_OLD = 0x30, // Obsolete
TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD = 0x31,
/*
u16 count of removed objects
for all removed objects {
u16 id
}
u16 count of added objects
for all added objects {
u16 id
u8 type
u32 initialization data length
string initialization data
}
*/
TOCLIENT_ACTIVE_OBJECT_MESSAGES = 0x32,
/*
for all objects
{
u16 id
u16 message length
string message
}
*/
TOCLIENT_HP = 0x33,
/*
u8 hp
*/
TOCLIENT_MOVE_PLAYER = 0x34,
/*
v3f1000 player position
f1000 player pitch
f1000 player yaw
*/
TOCLIENT_ACCESS_DENIED_LEGACY = 0x35,
/*
u16 reason_length
wstring reason
*/
TOCLIENT_PLAYERITEM = 0x36, // Obsolete
TOCLIENT_DEATHSCREEN = 0x37,
/*
u8 bool set camera point target
v3f1000 camera point target (to point the death cause or whatever)
*/
TOCLIENT_MEDIA = 0x38,
/*
u16 total number of texture bunches
u16 index of this bunch
u32 number of files in this bunch
for each file {
u16 length of name
string name
u32 length of data
data
}
u16 length of remote media server url (if applicable)
string url
*/
TOCLIENT_TOOLDEF = 0x39,
/*
u32 length of the next item
serialized ToolDefManager
*/
TOCLIENT_NODEDEF = 0x3a,
/*
u32 length of the next item
serialized NodeDefManager
*/
TOCLIENT_CRAFTITEMDEF = 0x3b,
/*
u32 length of the next item
serialized CraftiItemDefManager
*/
TOCLIENT_ANNOUNCE_MEDIA = 0x3c,
/*
u32 number of files
for each texture {
u16 length of name
string name
u16 length of sha1_digest
string sha1_digest
}
*/
TOCLIENT_ITEMDEF = 0x3d,
/*
u32 length of next item
serialized ItemDefManager
*/
TOCLIENT_PLAY_SOUND = 0x3f,
/*
s32 sound_id
u16 len
u8[len] sound name
s32 gain*1000
u8 type (0=local, 1=positional, 2=object)
s32[3] pos_nodes*10000
u16 object_id
u8 loop (bool)
*/
TOCLIENT_STOP_SOUND = 0x40,
/*
s32 sound_id
*/
TOCLIENT_PRIVILEGES = 0x41,
/*
u16 number of privileges
for each privilege
u16 len
u8[len] privilege
*/
TOCLIENT_INVENTORY_FORMSPEC = 0x42,
/*
u32 len
u8[len] formspec
*/
TOCLIENT_DETACHED_INVENTORY = 0x43,
/*
[0] u16 command
u16 len
u8[len] name
[2] serialized inventory
*/
TOCLIENT_SHOW_FORMSPEC = 0x44,
/*
[0] u16 command
u32 len
u8[len] formspec
u16 len
u8[len] formname
*/
TOCLIENT_MOVEMENT = 0x45,
/*
f1000 movement_acceleration_default
f1000 movement_acceleration_air
f1000 movement_acceleration_fast
f1000 movement_speed_walk
f1000 movement_speed_crouch
f1000 movement_speed_fast
f1000 movement_speed_climb
f1000 movement_speed_jump
f1000 movement_liquid_fluidity
f1000 movement_liquid_fluidity_smooth
f1000 movement_liquid_sink
f1000 movement_gravity
*/
TOCLIENT_SPAWN_PARTICLE = 0x46,
/*
v3f1000 pos
v3f1000 velocity
v3f1000 acceleration
f1000 expirationtime
f1000 size
u8 bool collisiondetection
u32 len
u8[len] texture
u8 bool vertical
u8 collision_removal
TileAnimation animation
u8 glow
u8 object_collision
*/
TOCLIENT_ADD_PARTICLESPAWNER = 0x47,
/*
u16 amount
f1000 spawntime
v3f1000 minpos
v3f1000 maxpos
v3f1000 minvel
v3f1000 maxvel
v3f1000 minacc
v3f1000 maxacc
f1000 minexptime
f1000 maxexptime
f1000 minsize
f1000 maxsize
u8 bool collisiondetection
u32 len
u8[len] texture
u8 bool vertical
u8 collision_removal
u32 id
TileAnimation animation
u8 glow
u8 object_collision
*/
TOCLIENT_DELETE_PARTICLESPAWNER_LEGACY = 0x48, // Obsolete
TOCLIENT_HUDADD = 0x49,
/*
u32 id
u8 type
v2f1000 pos
u32 len
u8[len] name
v2f1000 scale
u32 len2
u8[len2] text
u32 number
u32 item
u32 dir
v2f1000 align
v2f1000 offset
v3f1000 world_pos
v2s32 size
*/
TOCLIENT_HUDRM = 0x4a,
/*
u32 id
*/
TOCLIENT_HUDCHANGE = 0x4b,
/*
u32 id
u8 stat
[v2f1000 data |
u32 len
u8[len] data |
u32 data]
*/
TOCLIENT_HUD_SET_FLAGS = 0x4c,
/*
u32 flags
u32 mask
*/
TOCLIENT_HUD_SET_PARAM = 0x4d,
/*
u16 param
u16 len
u8[len] value
*/
TOCLIENT_BREATH = 0x4e,
/*
u16 breath
*/
TOCLIENT_SET_SKY = 0x4f,
/*
u8[4] color (ARGB)
u8 len
u8[len] type
u16 count
foreach count:
u8 len
u8[len] param
u8 clouds (boolean)
*/
TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO = 0x50,
/*
u8 do_override (boolean)
u16 day-night ratio 0...65535
*/
TOCLIENT_LOCAL_PLAYER_ANIMATIONS = 0x51,
/*
v2s32 stand/idle
v2s32 walk
v2s32 dig
v2s32 walk+dig
f1000 frame_speed
*/
TOCLIENT_EYE_OFFSET = 0x52,
/*
v3f1000 first
v3f1000 third
*/
TOCLIENT_DELETE_PARTICLESPAWNER = 0x53,
/*
u32 id
*/
TOCLIENT_CLOUD_PARAMS = 0x54,
/*
f1000 density
u8[4] color_diffuse (ARGB)
u8[4] color_ambient (ARGB)
f1000 height
f1000 thickness
v2f1000 speed
*/
TOCLIENT_FADE_SOUND = 0x55,
/*
s32 sound_id
float step
float gain
*/
TOCLIENT_UPDATE_PLAYER_LIST = 0x56,
/*
u8 type
u16 number of players
for each player
u16 len
u8[len] player name
*/
TOCLIENT_MODCHANNEL_MSG = 0x57,
/*
u16 channel name length
std::string channel name
u16 channel name sender
std::string channel name
u16 message length
std::string message
*/
TOCLIENT_MODCHANNEL_SIGNAL = 0x58,
/*
u8 signal id
u16 channel name length
std::string channel name
*/
TOCLIENT_NODEMETA_CHANGED = 0x59,
/*
serialized and compressed node metadata
*/
TOCLIENT_SRP_BYTES_S_B = 0x60,
/*
Belonging to AUTH_MECHANISM_SRP.
std::string bytes_s
std::string bytes_B
*/
TOCLIENT_FORMSPEC_PREPEND = 0x61,
/*
u16 len
u8[len] formspec
*/
TOCLIENT_NUM_MSG_TYPES = 0x62,
};
enum ToServerCommand
{
TOSERVER_INIT = 0x02,
/*
Sent first after connected.
u8 serialisation version (=SER_FMT_VER_HIGHEST_READ)
u16 supported network compression modes
u16 minimum supported network protocol version
u16 maximum supported network protocol version
std::string player name
*/
TOSERVER_INIT_LEGACY = 0x10, // Obsolete
TOSERVER_INIT2 = 0x11,
/*
Sent as an ACK for TOCLIENT_INIT.
After this, the server can send data.
[0] u16 TOSERVER_INIT2
*/
TOSERVER_MODCHANNEL_JOIN = 0x17,
/*
u16 channel name length
std::string channel name
*/
TOSERVER_MODCHANNEL_LEAVE = 0x18,
/*
u16 channel name length
std::string channel name
*/
TOSERVER_MODCHANNEL_MSG = 0x19,
/*
u16 channel name length
std::string channel name
u16 message length
std::string message
*/
TOSERVER_GETBLOCK = 0x20, // Obsolete
TOSERVER_ADDNODE = 0x21, // Obsolete
TOSERVER_REMOVENODE = 0x22, // Obsolete
TOSERVER_PLAYERPOS = 0x23,
/*
[0] u16 command
[2] v3s32 position*100
[2+12] v3s32 speed*100
[2+12+12] s32 pitch*100
[2+12+12+4] s32 yaw*100
[2+12+12+4+4] u32 keyPressed
[2+12+12+4+4+1] u8 fov*80
[2+12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
*/
TOSERVER_GOTBLOCKS = 0x24,
/*
[0] u16 command
[2] u8 count
[3] v3s16 pos_0
[3+6] v3s16 pos_1
...
*/
TOSERVER_DELETEDBLOCKS = 0x25,
/*
[0] u16 command
[2] u8 count
[3] v3s16 pos_0
[3+6] v3s16 pos_1
...
*/
TOSERVER_ADDNODE_FROM_INVENTORY = 0x26, // Obsolete
TOSERVER_CLICK_OBJECT = 0x27, // Obsolete
TOSERVER_GROUND_ACTION = 0x28, // Obsolete
TOSERVER_RELEASE = 0x29, // Obsolete
TOSERVER_SIGNTEXT = 0x30, // Obsolete
TOSERVER_INVENTORY_ACTION = 0x31,
/*
See InventoryAction in inventorymanager.h
*/
TOSERVER_CHAT_MESSAGE = 0x32,
/*
u16 length
wstring message
*/
TOSERVER_SIGNNODETEXT = 0x33, // Obsolete
TOSERVER_CLICK_ACTIVEOBJECT = 0x34, // Obsolete
TOSERVER_DAMAGE = 0x35,
/*
u8 amount
*/
TOSERVER_PASSWORD_LEGACY = 0x36, // Obsolete
TOSERVER_PLAYERITEM = 0x37,
/*
Sent to change selected item.
[0] u16 TOSERVER_PLAYERITEM
[2] u16 item
*/
TOSERVER_RESPAWN = 0x38,
/*
u16 TOSERVER_RESPAWN
*/
TOSERVER_INTERACT = 0x39,
/*
[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
*/
TOSERVER_REMOVED_SOUNDS = 0x3a,
/*
u16 len
s32[len] sound_id
*/
TOSERVER_NODEMETA_FIELDS = 0x3b,
/*
v3s16 p
u16 len
u8[len] form name (reserved for future use)
u16 number of fields
for each field:
u16 len
u8[len] field name
u32 len
u8[len] field value
*/
TOSERVER_INVENTORY_FIELDS = 0x3c,
/*
u16 len
u8[len] form name (reserved for future use)
u16 number of fields
for each field:
u16 len
u8[len] field name
u32 len
u8[len] field value
*/
TOSERVER_REQUEST_MEDIA = 0x40,
/*
u16 number of files requested
for each file {
u16 length of name
string name
}
*/
TOSERVER_RECEIVED_MEDIA = 0x41, // Obsolete
TOSERVER_BREATH = 0x42, // Obsolete
TOSERVER_CLIENT_READY = 0x43,
/*
u8 major
u8 minor
u8 patch
u8 reserved
u16 len
u8[len] full_version_string
*/
TOSERVER_FIRST_SRP = 0x50,
/*
Belonging to AUTH_MECHANISM_FIRST_SRP.
std::string srp salt
std::string srp verification key
u8 is_empty (=1 if password is empty, 0 otherwise)
*/
TOSERVER_SRP_BYTES_A = 0x51,
/*
Belonging to AUTH_MECHANISM_SRP,
depending on current_login_based_on.
std::string bytes_A
u8 current_login_based_on : on which version of the password's
hash this login is based on (0 legacy hash,
or 1 directly the password)
*/
TOSERVER_SRP_BYTES_M = 0x52,
/*
Belonging to AUTH_MECHANISM_SRP.
std::string bytes_M
*/
TOSERVER_NUM_MSG_TYPES = 0x53,
};
enum AuthMechanism
{
// reserved
AUTH_MECHANISM_NONE = 0,
// SRP based on the legacy hash
AUTH_MECHANISM_LEGACY_PASSWORD = 1 << 0,
// SRP based on the srp verification key
AUTH_MECHANISM_SRP = 1 << 1,
// Establishes a srp verification key, for first login and password changing
AUTH_MECHANISM_FIRST_SRP = 1 << 2,
};
enum AccessDeniedCode {
SERVER_ACCESSDENIED_WRONG_PASSWORD,
SERVER_ACCESSDENIED_UNEXPECTED_DATA,
SERVER_ACCESSDENIED_SINGLEPLAYER,
SERVER_ACCESSDENIED_WRONG_VERSION,
SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME,
SERVER_ACCESSDENIED_WRONG_NAME,
SERVER_ACCESSDENIED_TOO_MANY_USERS,
SERVER_ACCESSDENIED_EMPTY_PASSWORD,
SERVER_ACCESSDENIED_ALREADY_CONNECTED,
SERVER_ACCESSDENIED_SERVER_FAIL,
SERVER_ACCESSDENIED_CUSTOM_STRING,
SERVER_ACCESSDENIED_SHUTDOWN,
SERVER_ACCESSDENIED_CRASH,
SERVER_ACCESSDENIED_MAX,
};
enum NetProtoCompressionMode {
NETPROTO_COMPRESSION_NONE = 0,
};
const static std::string accessDeniedStrings[SERVER_ACCESSDENIED_MAX] = {
"Invalid password",
"Your client sent something the server didn't expect. Try reconnecting or updating your client",
"The server is running in simple singleplayer mode. You cannot connect.",
"Your client's version is not supported.\nPlease contact server administrator.",
"Player name contains disallowed characters.",
"Player name not allowed.",
"Too many users.",
"Empty passwords are disallowed. Set a password and try again.",
"Another client is connected with this name. If your client closed unexpectedly, try again in a minute.",
"Server authentication failed. This is likely a server error.",
"",
"Server shutting down.",
"This server has experienced an internal error. You will now be disconnected."
};
enum PlayerListModifer: u8
{
PLAYER_LIST_INIT,
PLAYER_LIST_ADD,
PLAYER_LIST_REMOVE,
};
enum CSMRestrictionFlags : u64 {
CSM_RF_NONE = 0x00000000,
// Until server-sent CSM and verifying of builtin are complete,
// 'CSM_RF_LOAD_CLIENT_MODS' also disables loading 'builtin'.
// When those are complete, this should return to only being a restriction on the
// loading of client mods.
CSM_RF_LOAD_CLIENT_MODS = 0x00000001, // Don't load client-provided mods or 'builtin'
CSM_RF_CHAT_MESSAGES = 0x00000002, // Disable chat message sending from CSM
CSM_RF_READ_ITEMDEFS = 0x00000004, // Disable itemdef lookups
CSM_RF_READ_NODEDEFS = 0x00000008, // Disable nodedef lookups
CSM_RF_LOOKUP_NODES = 0x00000010, // Limit node lookups
CSM_RF_READ_PLAYERINFO = 0x00000020, // Disable player info lookups
CSM_RF_ALL = 0xFFFFFFFF,
};
| pgimeno/minetest | src/network/networkprotocol.h | C++ | mit | 22,005 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "networkprotocol.h"
namespace con
{
typedef enum
{
MIN_RTT,
MAX_RTT,
AVG_RTT,
MIN_JITTER,
MAX_JITTER,
AVG_JITTER
} rtt_stat_type;
class Peer;
class PeerHandler
{
public:
PeerHandler() = default;
virtual ~PeerHandler() = default;
/*
This is called after the Peer has been inserted into the
Connection's peer container.
*/
virtual void peerAdded(Peer *peer) = 0;
/*
This is called before the Peer has been removed from the
Connection's peer container.
*/
virtual void deletingPeer(Peer *peer, bool timeout) = 0;
};
enum PeerChangeType : u8
{
PEER_ADDED,
PEER_REMOVED
};
struct PeerChange
{
PeerChange(PeerChangeType t, session_t _peer_id, bool _timeout) :
type(t), peer_id(_peer_id), timeout(_timeout)
{
}
PeerChange() = delete;
PeerChangeType type;
session_t peer_id;
bool timeout;
};
}
| pgimeno/minetest | src/network/peerhandler.h | C++ | mit | 1,638 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "serveropcodes.h"
const static ToServerCommandHandler null_command_handler = { "TOSERVER_NULL", TOSERVER_STATE_ALL, &Server::handleCommand_Null };
const ToServerCommandHandler toServerCommandTable[TOSERVER_NUM_MSG_TYPES] =
{
null_command_handler, // 0x00 (never use this)
null_command_handler, // 0x01
{ "TOSERVER_INIT", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_Init }, // 0x02
null_command_handler, // 0x03
null_command_handler, // 0x04
null_command_handler, // 0x05
null_command_handler, // 0x06
null_command_handler, // 0x07
null_command_handler, // 0x08
null_command_handler, // 0x09
null_command_handler, // 0x0a
null_command_handler, // 0x0b
null_command_handler, // 0x0c
null_command_handler, // 0x0d
null_command_handler, // 0x0e
null_command_handler, // 0x0f
null_command_handler, // 0x10
{ "TOSERVER_INIT2", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_Init2 }, // 0x11
null_command_handler, // 0x12
null_command_handler, // 0x13
null_command_handler, // 0x14
null_command_handler, // 0x15
null_command_handler, // 0x16
{ "TOSERVER_MODCHANNEL_JOIN", TOSERVER_STATE_INGAME, &Server::handleCommand_ModChannelJoin }, // 0x17
{ "TOSERVER_MODCHANNEL_LEAVE", TOSERVER_STATE_INGAME, &Server::handleCommand_ModChannelLeave }, // 0x18
{ "TOSERVER_MODCHANNEL_MSG", TOSERVER_STATE_INGAME, &Server::handleCommand_ModChannelMsg }, // 0x19
null_command_handler, // 0x1a
null_command_handler, // 0x1b
null_command_handler, // 0x1c
null_command_handler, // 0x1d
null_command_handler, // 0x1e
null_command_handler, // 0x1f
null_command_handler, // 0x20
null_command_handler, // 0x21
null_command_handler, // 0x22
{ "TOSERVER_PLAYERPOS", TOSERVER_STATE_INGAME, &Server::handleCommand_PlayerPos }, // 0x23
{ "TOSERVER_GOTBLOCKS", TOSERVER_STATE_STARTUP, &Server::handleCommand_GotBlocks }, // 0x24
{ "TOSERVER_DELETEDBLOCKS", TOSERVER_STATE_INGAME, &Server::handleCommand_DeletedBlocks }, // 0x25
null_command_handler, // 0x26
null_command_handler, // 0x27
null_command_handler, // 0x28
null_command_handler, // 0x29
null_command_handler, // 0x2a
null_command_handler, // 0x2b
null_command_handler, // 0x2c
null_command_handler, // 0x2d
null_command_handler, // 0x2e
null_command_handler, // 0x2f
null_command_handler, // 0x30
{ "TOSERVER_INVENTORY_ACTION", TOSERVER_STATE_INGAME, &Server::handleCommand_InventoryAction }, // 0x31
{ "TOSERVER_CHAT_MESSAGE", TOSERVER_STATE_INGAME, &Server::handleCommand_ChatMessage }, // 0x32
null_command_handler, // 0x33
null_command_handler, // 0x34
{ "TOSERVER_DAMAGE", TOSERVER_STATE_INGAME, &Server::handleCommand_Damage }, // 0x35
null_command_handler, // 0x36
{ "TOSERVER_PLAYERITEM", TOSERVER_STATE_INGAME, &Server::handleCommand_PlayerItem }, // 0x37
{ "TOSERVER_RESPAWN", TOSERVER_STATE_INGAME, &Server::handleCommand_Respawn }, // 0x38
{ "TOSERVER_INTERACT", TOSERVER_STATE_INGAME, &Server::handleCommand_Interact }, // 0x39
{ "TOSERVER_REMOVED_SOUNDS", TOSERVER_STATE_INGAME, &Server::handleCommand_RemovedSounds }, // 0x3a
{ "TOSERVER_NODEMETA_FIELDS", TOSERVER_STATE_INGAME, &Server::handleCommand_NodeMetaFields }, // 0x3b
{ "TOSERVER_INVENTORY_FIELDS", TOSERVER_STATE_INGAME, &Server::handleCommand_InventoryFields }, // 0x3c
null_command_handler, // 0x3d
null_command_handler, // 0x3e
null_command_handler, // 0x3f
{ "TOSERVER_REQUEST_MEDIA", TOSERVER_STATE_STARTUP, &Server::handleCommand_RequestMedia }, // 0x40
null_command_handler, // 0x41
null_command_handler, // 0x42
{ "TOSERVER_CLIENT_READY", TOSERVER_STATE_STARTUP, &Server::handleCommand_ClientReady }, // 0x43
null_command_handler, // 0x44
null_command_handler, // 0x45
null_command_handler, // 0x46
null_command_handler, // 0x47
null_command_handler, // 0x48
null_command_handler, // 0x49
null_command_handler, // 0x4a
null_command_handler, // 0x4b
null_command_handler, // 0x4c
null_command_handler, // 0x4d
null_command_handler, // 0x4e
null_command_handler, // 0x4f
{ "TOSERVER_FIRST_SRP", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_FirstSrp }, // 0x50
{ "TOSERVER_SRP_BYTES_A", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_SrpBytesA }, // 0x51
{ "TOSERVER_SRP_BYTES_M", TOSERVER_STATE_NOT_CONNECTED, &Server::handleCommand_SrpBytesM }, // 0x52
};
const static ClientCommandFactory null_command_factory = { "TOCLIENT_NULL", 0, false };
const ClientCommandFactory clientCommandFactoryTable[TOCLIENT_NUM_MSG_TYPES] =
{
null_command_factory, // 0x00
null_command_factory, // 0x01
{ "TOCLIENT_HELLO", 0, true }, // 0x02
{ "TOCLIENT_AUTH_ACCEPT", 0, true }, // 0x03
{ "TOCLIENT_ACCEPT_SUDO_MODE", 0, true }, // 0x04
{ "TOCLIENT_DENY_SUDO_MODE", 0, true }, // 0x05
null_command_factory, // 0x06
null_command_factory, // 0x07
null_command_factory, // 0x08
null_command_factory, // 0x09
{ "TOCLIENT_ACCESS_DENIED", 0, true }, // 0x0A
null_command_factory, // 0x0B
null_command_factory, // 0x0C
null_command_factory, // 0x0D
null_command_factory, // 0x0E
null_command_factory, // 0x0F
{ "TOCLIENT_INIT", 0, true }, // 0x10
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
{ "TOCLIENT_BLOCKDATA", 2, true }, // 0x20
{ "TOCLIENT_ADDNODE", 0, true }, // 0x21
{ "TOCLIENT_REMOVENODE", 0, true }, // 0x22
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
{ "TOCLIENT_INVENTORY", 0, true }, // 0x27
null_command_factory,
{ "TOCLIENT_TIME_OF_DAY", 0, true }, // 0x29
{ "TOCLIENT_CSM_RESTRICTION_FLAGS", 0, true }, // 0x2A
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
{ "TOCLIENT_CHAT_MESSAGE", 0, true }, // 0x2F
null_command_factory, // 0x30
{ "TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD", 0, true }, // 0x31
{ "TOCLIENT_ACTIVE_OBJECT_MESSAGES", 0, true }, // 0x32 Special packet, sent by 0 (rel) and 1 (unrel) channel
{ "TOCLIENT_HP", 0, true }, // 0x33
{ "TOCLIENT_MOVE_PLAYER", 0, true }, // 0x34
{ "TOCLIENT_ACCESS_DENIED_LEGACY", 0, true }, // 0x35
null_command_factory, // 0x36
{ "TOCLIENT_DEATHSCREEN", 0, true }, // 0x37
{ "TOCLIENT_MEDIA", 2, true }, // 0x38
null_command_factory, // 0x39
{ "TOCLIENT_NODEDEF", 0, true }, // 0x3a
null_command_factory, // 0x3b
{ "TOCLIENT_ANNOUNCE_MEDIA", 0, true }, // 0x3c
{ "TOCLIENT_ITEMDEF", 0, true }, // 0x3d
null_command_factory,
{ "TOCLIENT_PLAY_SOUND", 0, true }, // 0x3f
{ "TOCLIENT_STOP_SOUND", 0, true }, // 0x40
{ "TOCLIENT_PRIVILEGES", 0, true }, // 0x41
{ "TOCLIENT_INVENTORY_FORMSPEC", 0, true }, // 0x42
{ "TOCLIENT_DETACHED_INVENTORY", 0, true }, // 0x43
{ "TOCLIENT_SHOW_FORMSPEC", 0, true }, // 0x44
{ "TOCLIENT_MOVEMENT", 0, true }, // 0x45
{ "TOCLIENT_SPAWN_PARTICLE", 0, true }, // 0x46
{ "TOCLIENT_ADD_PARTICLESPAWNER", 0, true }, // 0x47
null_command_factory, // 0x48
{ "TOCLIENT_HUDADD", 1, true }, // 0x49
{ "TOCLIENT_HUDRM", 1, true }, // 0x4a
{ "TOCLIENT_HUDCHANGE", 0, true }, // 0x4b
{ "TOCLIENT_HUD_SET_FLAGS", 0, true }, // 0x4c
{ "TOCLIENT_HUD_SET_PARAM", 0, true }, // 0x4d
{ "TOCLIENT_BREATH", 0, true }, // 0x4e
{ "TOCLIENT_SET_SKY", 0, true }, // 0x4f
{ "TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO", 0, true }, // 0x50
{ "TOCLIENT_LOCAL_PLAYER_ANIMATIONS", 0, true }, // 0x51
{ "TOCLIENT_EYE_OFFSET", 0, true }, // 0x52
{ "TOCLIENT_DELETE_PARTICLESPAWNER", 0, true }, // 0x53
{ "TOCLIENT_CLOUD_PARAMS", 0, true }, // 0x54
{ "TOCLIENT_FADE_SOUND", 0, true }, // 0x55
{ "TOCLIENT_UPDATE_PLAYER_LIST", 0, true }, // 0x56
{ "TOCLIENT_MODCHANNEL_MSG", 0, true }, // 0x57
{ "TOCLIENT_MODCHANNEL_SIGNAL", 0, true }, // 0x58
{ "TOCLIENT_NODEMETA_CHANGED", 0, true }, // 0x59
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
null_command_factory,
{ "TOSERVER_SRP_BYTES_S_B", 0, true }, // 0x60
{ "TOCLIENT_FORMSPEC_PREPEND", 0, true }, // 0x61
};
| pgimeno/minetest | src/network/serveropcodes.cpp | C++ | mit | 9,811 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "server.h"
#include "networkprotocol.h"
class NetworkPacket;
enum ToServerConnectionState {
TOSERVER_STATE_NOT_CONNECTED,
TOSERVER_STATE_STARTUP,
TOSERVER_STATE_INGAME,
TOSERVER_STATE_ALL,
};
struct ToServerCommandHandler
{
const std::string name;
ToServerConnectionState state;
void (Server::*handler)(NetworkPacket* pkt);
};
struct ClientCommandFactory
{
const char* name;
u8 channel;
bool reliable;
};
extern const ToServerCommandHandler toServerCommandTable[TOSERVER_NUM_MSG_TYPES];
extern const ClientCommandFactory clientCommandFactoryTable[TOCLIENT_NUM_MSG_TYPES];
| pgimeno/minetest | src/network/serveropcodes.h | C++ | mit | 1,473 |
/*
Minetest
Copyright (C) 2015 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "chatmessage.h"
#include "server.h"
#include "log.h"
#include "content_sao.h"
#include "emerge.h"
#include "mapblock.h"
#include "modchannels.h"
#include "nodedef.h"
#include "remoteplayer.h"
#include "rollback_interface.h"
#include "scripting_server.h"
#include "settings.h"
#include "tool.h"
#include "version.h"
#include "network/connection.h"
#include "network/networkprotocol.h"
#include "network/serveropcodes.h"
#include "util/auth.h"
#include "util/base64.h"
#include "util/pointedthing.h"
#include "util/serialize.h"
#include "util/srp.h"
void Server::handleCommand_Deprecated(NetworkPacket* pkt)
{
infostream << "Server: " << toServerCommandTable[pkt->getCommand()].name
<< " not supported anymore" << std::endl;
}
void Server::handleCommand_Init(NetworkPacket* pkt)
{
if(pkt->getSize() < 1)
return;
RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
std::string addr_s;
try {
Address address = getPeerAddress(pkt->getPeerId());
addr_s = address.serializeString();
}
catch (con::PeerNotFoundException &e) {
/*
* no peer for this packet found
* most common reason is peer timeout, e.g. peer didn't
* respond for some time, your server was overloaded or
* things like that.
*/
infostream << "Server::ProcessData(): Canceling: peer "
<< pkt->getPeerId() << " not found" << std::endl;
return;
}
// If net_proto_version is set, this client has already been handled
if (client->getState() > CS_Created) {
verbosestream << "Server: Ignoring multiple TOSERVER_INITs from "
<< addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
return;
}
verbosestream << "Server: Got TOSERVER_INIT from " << addr_s << " (peer_id="
<< pkt->getPeerId() << ")" << std::endl;
// Do not allow multiple players in simple singleplayer mode.
// This isn't a perfect way to do it, but will suffice for now
if (m_simple_singleplayer_mode && m_clients.getClientIDs().size() > 1) {
infostream << "Server: Not allowing another client (" << addr_s
<< ") to connect in simple singleplayer mode" << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SINGLEPLAYER);
return;
}
// First byte after command is maximum supported
// serialization version
u8 client_max;
u16 supp_compr_modes;
u16 min_net_proto_version = 0;
u16 max_net_proto_version;
std::string playerName;
*pkt >> client_max >> supp_compr_modes >> min_net_proto_version
>> max_net_proto_version >> playerName;
u8 our_max = SER_FMT_VER_HIGHEST_READ;
// Use the highest version supported by both
u8 depl_serial_v = std::min(client_max, our_max);
// If it's lower than the lowest supported, give up.
if (depl_serial_v < SER_FMT_VER_LOWEST_READ)
depl_serial_v = SER_FMT_VER_INVALID;
if (depl_serial_v == SER_FMT_VER_INVALID) {
actionstream << "Server: A mismatched client tried to connect from "
<< addr_s << std::endl;
infostream<<"Server: Cannot negotiate serialization version with "
<< addr_s << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
return;
}
client->setPendingSerializationVersion(depl_serial_v);
/*
Read and check network protocol version
*/
u16 net_proto_version = 0;
// Figure out a working version if it is possible at all
if (max_net_proto_version >= SERVER_PROTOCOL_VERSION_MIN ||
min_net_proto_version <= SERVER_PROTOCOL_VERSION_MAX) {
// If maximum is larger than our maximum, go with our maximum
if (max_net_proto_version > SERVER_PROTOCOL_VERSION_MAX)
net_proto_version = SERVER_PROTOCOL_VERSION_MAX;
// Else go with client's maximum
else
net_proto_version = max_net_proto_version;
}
verbosestream << "Server: " << addr_s << ": Protocol version: min: "
<< min_net_proto_version << ", max: " << max_net_proto_version
<< ", chosen: " << net_proto_version << std::endl;
client->net_proto_version = net_proto_version;
if ((g_settings->getBool("strict_protocol_version_checking") &&
net_proto_version != LATEST_PROTOCOL_VERSION) ||
net_proto_version < SERVER_PROTOCOL_VERSION_MIN ||
net_proto_version > SERVER_PROTOCOL_VERSION_MAX) {
actionstream << "Server: A mismatched client tried to connect from "
<< addr_s << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_VERSION);
return;
}
/*
Validate player name
*/
const char* playername = playerName.c_str();
size_t pns = playerName.size();
if (pns == 0 || pns > PLAYERNAME_SIZE) {
actionstream << "Server: Player with "
<< ((pns > PLAYERNAME_SIZE) ? "a too long" : "an empty")
<< " name tried to connect from " << addr_s << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
return;
}
if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
actionstream << "Server: Player with an invalid name "
<< "tried to connect from " << addr_s << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME);
return;
}
m_clients.setPlayerName(pkt->getPeerId(), playername);
//TODO (later) case insensitivity
std::string legacyPlayerNameCasing = playerName;
if (!isSingleplayer() && strcasecmp(playername, "singleplayer") == 0) {
actionstream << "Server: Player with the name \"singleplayer\" "
<< "tried to connect from " << addr_s << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_NAME);
return;
}
{
std::string reason;
if (m_script->on_prejoinplayer(playername, addr_s, &reason)) {
actionstream << "Server: Player with the name \"" << playerName << "\" "
<< "tried to connect from " << addr_s << " "
<< "but it was disallowed for the following reason: "
<< reason << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
return;
}
}
infostream << "Server: New connection: \"" << playerName << "\" from "
<< addr_s << " (peer_id=" << pkt->getPeerId() << ")" << std::endl;
// Enforce user limit.
// Don't enforce for users that have some admin right or mod permits it.
if (m_clients.isUserLimitReached() &&
playername != g_settings->get("name") &&
!m_script->can_bypass_userlimit(playername, addr_s)) {
actionstream << "Server: " << playername << " tried to join from "
<< addr_s << ", but there" << " are already max_users="
<< g_settings->getU16("max_users") << " players." << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_TOO_MANY_USERS);
return;
}
/*
Compose auth methods for answer
*/
std::string encpwd; // encrypted Password field for the user
bool has_auth = m_script->getAuth(playername, &encpwd, NULL);
u32 auth_mechs = 0;
client->chosen_mech = AUTH_MECHANISM_NONE;
if (has_auth) {
std::vector<std::string> pwd_components = str_split(encpwd, '#');
if (pwd_components.size() == 4) {
if (pwd_components[1] == "1") { // 1 means srp
auth_mechs |= AUTH_MECHANISM_SRP;
client->enc_pwd = encpwd;
} else {
actionstream << "User " << playername
<< " tried to log in, but password field"
<< " was invalid (unknown mechcode)." << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
return;
}
} else if (base64_is_valid(encpwd)) {
auth_mechs |= AUTH_MECHANISM_LEGACY_PASSWORD;
client->enc_pwd = encpwd;
} else {
actionstream << "User " << playername
<< " tried to log in, but password field"
<< " was invalid (invalid base64)." << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
return;
}
} else {
std::string default_password = g_settings->get("default_password");
if (default_password.length() == 0) {
auth_mechs |= AUTH_MECHANISM_FIRST_SRP;
} else {
// Take care of default passwords.
client->enc_pwd = get_encoded_srp_verifier(playerName, default_password);
auth_mechs |= AUTH_MECHANISM_SRP;
// Allocate player in db, but only on successful login.
client->create_player_on_auth_success = true;
}
}
/*
Answer with a TOCLIENT_HELLO
*/
verbosestream << "Sending TOCLIENT_HELLO with auth method field: "
<< auth_mechs << std::endl;
NetworkPacket resp_pkt(TOCLIENT_HELLO, 1 + 4
+ legacyPlayerNameCasing.size(), pkt->getPeerId());
u16 depl_compress_mode = NETPROTO_COMPRESSION_NONE;
resp_pkt << depl_serial_v << depl_compress_mode << net_proto_version
<< auth_mechs << legacyPlayerNameCasing;
Send(&resp_pkt);
client->allowed_auth_mechs = auth_mechs;
client->setDeployedCompressionMode(depl_compress_mode);
m_clients.event(pkt->getPeerId(), CSE_Hello);
}
void Server::handleCommand_Init2(NetworkPacket* pkt)
{
verbosestream << "Server: Got TOSERVER_INIT2 from "
<< pkt->getPeerId() << std::endl;
m_clients.event(pkt->getPeerId(), CSE_GotInit2);
u16 protocol_version = m_clients.getProtocolVersion(pkt->getPeerId());
std::string lang;
if (pkt->getSize() > 0)
*pkt >> lang;
/*
Send some initialization data
*/
infostream << "Server: Sending content to "
<< getPlayerName(pkt->getPeerId()) << std::endl;
// Send player movement settings
SendMovement(pkt->getPeerId());
// Send item definitions
SendItemDef(pkt->getPeerId(), m_itemdef, protocol_version);
// Send node definitions
SendNodeDef(pkt->getPeerId(), m_nodedef, protocol_version);
m_clients.event(pkt->getPeerId(), CSE_SetDefinitionsSent);
// Send media announcement
sendMediaAnnouncement(pkt->getPeerId(), lang);
// Send detached inventories
sendDetachedInventories(pkt->getPeerId());
// Send time of day
u16 time = m_env->getTimeOfDay();
float time_speed = g_settings->getFloat("time_speed");
SendTimeOfDay(pkt->getPeerId(), time, time_speed);
SendCSMRestrictionFlags(pkt->getPeerId());
// Warnings about protocol version can be issued here
if (getClient(pkt->getPeerId())->net_proto_version < LATEST_PROTOCOL_VERSION) {
SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
L"# Server: WARNING: YOUR CLIENT'S VERSION MAY NOT BE FULLY COMPATIBLE "
L"WITH THIS SERVER!"));
}
}
void Server::handleCommand_RequestMedia(NetworkPacket* pkt)
{
std::vector<std::string> tosend;
u16 numfiles;
*pkt >> numfiles;
infostream << "Sending " << numfiles << " files to "
<< getPlayerName(pkt->getPeerId()) << std::endl;
verbosestream << "TOSERVER_REQUEST_MEDIA: " << std::endl;
for (u16 i = 0; i < numfiles; i++) {
std::string name;
*pkt >> name;
tosend.push_back(name);
verbosestream << "TOSERVER_REQUEST_MEDIA: requested file "
<< name << std::endl;
}
sendRequestedMedia(pkt->getPeerId(), tosend);
}
void Server::handleCommand_ClientReady(NetworkPacket* pkt)
{
session_t peer_id = pkt->getPeerId();
PlayerSAO* playersao = StageTwoClientInit(peer_id);
if (playersao == NULL) {
actionstream
<< "TOSERVER_CLIENT_READY stage 2 client init failed for peer_id: "
<< peer_id << std::endl;
DisconnectPeer(peer_id);
return;
}
if (pkt->getSize() < 8) {
errorstream
<< "TOSERVER_CLIENT_READY client sent inconsistent data, disconnecting peer_id: "
<< peer_id << std::endl;
DisconnectPeer(peer_id);
return;
}
u8 major_ver, minor_ver, patch_ver, reserved;
std::string full_ver;
*pkt >> major_ver >> minor_ver >> patch_ver >> reserved >> full_ver;
m_clients.setClientVersion(
peer_id, major_ver, minor_ver, patch_ver,
full_ver);
const std::vector<std::string> &players = m_clients.getPlayerNames();
NetworkPacket list_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, peer_id);
list_pkt << (u8) PLAYER_LIST_INIT << (u16) players.size();
for (const std::string &player: players) {
list_pkt << player;
}
m_clients.send(peer_id, 0, &list_pkt, true);
NetworkPacket notice_pkt(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT);
// (u16) 1 + std::string represents a pseudo vector serialization representation
notice_pkt << (u8) PLAYER_LIST_ADD << (u16) 1 << std::string(playersao->getPlayer()->getName());
m_clients.sendToAll(¬ice_pkt);
m_clients.event(peer_id, CSE_SetClientReady);
m_script->on_joinplayer(playersao);
// Send shutdown timer if shutdown has been scheduled
if (m_shutdown_state.isTimerRunning()) {
SendChatMessage(pkt->getPeerId(), m_shutdown_state.getShutdownTimerMessage());
}
}
void Server::handleCommand_GotBlocks(NetworkPacket* pkt)
{
if (pkt->getSize() < 1)
return;
/*
[0] u16 command
[2] u8 count
[3] v3s16 pos_0
[3+6] v3s16 pos_1
...
*/
u8 count;
*pkt >> count;
RemoteClient *client = getClient(pkt->getPeerId());
if ((s16)pkt->getSize() < 1 + (int)count * 6) {
throw con::InvalidIncomingDataException
("GOTBLOCKS length is too short");
}
for (u16 i = 0; i < count; i++) {
v3s16 p;
*pkt >> p;
client->GotBlock(p);
}
}
void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao,
NetworkPacket *pkt)
{
if (pkt->getRemainingBytes() < 12 + 12 + 4 + 4 + 4 + 1 + 1)
return;
v3s32 ps, ss;
s32 f32pitch, f32yaw;
u8 f32fov;
*pkt >> ps;
*pkt >> ss;
*pkt >> f32pitch;
*pkt >> f32yaw;
f32 pitch = (f32)f32pitch / 100.0f;
f32 yaw = (f32)f32yaw / 100.0f;
u32 keyPressed = 0;
// default behavior (in case an old client doesn't send these)
f32 fov = 0;
u8 wanted_range = 0;
*pkt >> keyPressed;
*pkt >> f32fov;
fov = (f32)f32fov / 80.0f;
*pkt >> wanted_range;
v3f position((f32)ps.X / 100.0f, (f32)ps.Y / 100.0f, (f32)ps.Z / 100.0f);
v3f speed((f32)ss.X / 100.0f, (f32)ss.Y / 100.0f, (f32)ss.Z / 100.0f);
pitch = modulo360f(pitch);
yaw = wrapDegrees_0_360(yaw);
playersao->setBasePosition(position);
player->setSpeed(speed);
playersao->setLookPitch(pitch);
playersao->setPlayerYaw(yaw);
playersao->setFov(fov);
playersao->setWantedRange(wanted_range);
player->keyPressed = keyPressed;
player->control.up = (keyPressed & 1);
player->control.down = (keyPressed & 2);
player->control.left = (keyPressed & 4);
player->control.right = (keyPressed & 8);
player->control.jump = (keyPressed & 16);
player->control.aux1 = (keyPressed & 32);
player->control.sneak = (keyPressed & 64);
player->control.LMB = (keyPressed & 128);
player->control.RMB = (keyPressed & 256);
if (playersao->checkMovementCheat()) {
// Call callbacks
m_script->on_cheat(playersao, "moved_too_fast");
SendMovePlayer(pkt->getPeerId());
}
}
void Server::handleCommand_PlayerPos(NetworkPacket* pkt)
{
RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
if (player == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player object for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
// If player is dead we don't care of this packet
if (playersao->isDead()) {
verbosestream << "TOSERVER_PLAYERPOS: " << player->getName()
<< " is dead. Ignoring packet";
return;
}
process_PlayerPos(player, playersao, pkt);
}
void Server::handleCommand_DeletedBlocks(NetworkPacket* pkt)
{
if (pkt->getSize() < 1)
return;
/*
[0] u16 command
[2] u8 count
[3] v3s16 pos_0
[3+6] v3s16 pos_1
...
*/
u8 count;
*pkt >> count;
RemoteClient *client = getClient(pkt->getPeerId());
if ((s16)pkt->getSize() < 1 + (int)count * 6) {
throw con::InvalidIncomingDataException
("DELETEDBLOCKS length is too short");
}
for (u16 i = 0; i < count; i++) {
v3s16 p;
*pkt >> p;
client->SetBlockNotSent(p);
}
}
void Server::handleCommand_InventoryAction(NetworkPacket* pkt)
{
RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
if (player == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player object for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
// Strip command and create a stream
std::string datastring(pkt->getString(0), pkt->getSize());
verbosestream << "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) {
infostream << "TOSERVER_INVENTORY_ACTION: "
<< "InventoryAction::deSerialize() returned NULL"
<< std::endl;
return;
}
// If something goes wrong, this player is to blame
RollbackScopeActor rollback_scope(m_rollback,
std::string("player:")+player->getName());
/*
Note: Always set inventory not sent, to repair cases
where the client made a bad prediction.
*/
/*
Handle restrictions and special cases of the move action
*/
if (a->getType() == IAction::Move) {
IMoveAction *ma = (IMoveAction*)a;
ma->from_inv.applyCurrentPlayer(player->getName());
ma->to_inv.applyCurrentPlayer(player->getName());
setInventoryModified(ma->from_inv, false);
if (ma->from_inv != ma->to_inv) {
setInventoryModified(ma->to_inv, false);
}
bool from_inv_is_current_player =
(ma->from_inv.type == InventoryLocation::PLAYER) &&
(ma->from_inv.name == player->getName());
bool to_inv_is_current_player =
(ma->to_inv.type == InventoryLocation::PLAYER) &&
(ma->to_inv.name == player->getName());
InventoryLocation *remote = from_inv_is_current_player ?
&ma->to_inv : &ma->from_inv;
// Check for out-of-range interaction
if (remote->type == InventoryLocation::NODEMETA) {
v3f node_pos = intToFloat(remote->p, BS);
v3f player_pos = player->getPlayerSAO()->getEyePosition();
f32 d = player_pos.getDistanceFrom(node_pos);
if (!checkInteractDistance(player, d, "inventory"))
return;
}
/*
Disable moving items out of craftpreview
*/
if (ma->from_list == "craftpreview") {
infostream << "Ignoring IMoveAction from "
<< (ma->from_inv.dump()) << ":" << ma->from_list
<< " to " << (ma->to_inv.dump()) << ":" << ma->to_list
<< " because src is " << ma->from_list << std::endl;
delete a;
return;
}
/*
Disable moving items into craftresult and craftpreview
*/
if (ma->to_list == "craftpreview" || ma->to_list == "craftresult") {
infostream << "Ignoring IMoveAction from "
<< (ma->from_inv.dump()) << ":" << ma->from_list
<< " to " << (ma->to_inv.dump()) << ":" << ma->to_list
<< " because dst is " << ma->to_list << std::endl;
delete a;
return;
}
// Disallow moving items in elsewhere than player's inventory
// if not allowed to interact
if (!checkPriv(player->getName(), "interact") &&
(!from_inv_is_current_player ||
!to_inv_is_current_player)) {
infostream << "Cannot move outside of player's inventory: "
<< "No interact privilege" << std::endl;
delete a;
return;
}
}
/*
Handle restrictions and special cases of the drop action
*/
else if (a->getType() == IAction::Drop) {
IDropAction *da = (IDropAction*)a;
da->from_inv.applyCurrentPlayer(player->getName());
setInventoryModified(da->from_inv, false);
/*
Disable dropping items out of craftpreview
*/
if (da->from_list == "craftpreview") {
infostream << "Ignoring IDropAction from "
<< (da->from_inv.dump()) << ":" << da->from_list
<< " because src is " << da->from_list << std::endl;
delete a;
return;
}
// Disallow dropping items if not allowed to interact
if (!checkPriv(player->getName(), "interact")) {
delete a;
return;
}
// Disallow dropping items if dead
if (playersao->isDead()) {
infostream << "Ignoring IDropAction from "
<< (da->from_inv.dump()) << ":" << da->from_list
<< " because player is dead." << std::endl;
delete a;
return;
}
}
/*
Handle restrictions and special cases of the craft action
*/
else if (a->getType() == IAction::Craft) {
ICraftAction *ca = (ICraftAction*)a;
ca->craft_inv.applyCurrentPlayer(player->getName());
setInventoryModified(ca->craft_inv, false);
//bool craft_inv_is_current_player =
// (ca->craft_inv.type == InventoryLocation::PLAYER) &&
// (ca->craft_inv.name == player->getName());
// Disallow crafting if not allowed to interact
if (!checkPriv(player->getName(), "interact")) {
infostream << "Cannot craft: "
<< "No interact privilege" << std::endl;
delete a;
return;
}
}
// Do the action
a->apply(this, playersao, this);
// Eat the action
delete a;
SendInventory(playersao);
}
void Server::handleCommand_ChatMessage(NetworkPacket* pkt)
{
/*
u16 command
u16 length
wstring message
*/
u16 len;
*pkt >> len;
std::wstring message;
for (u16 i = 0; i < len; i++) {
u16 tmp_wchar;
*pkt >> tmp_wchar;
message += (wchar_t)tmp_wchar;
}
RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
if (player == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
// Get player name of this client
std::string name = player->getName();
std::wstring wname = narrow_to_wide(name);
std::wstring answer_to_sender = handleChat(name, wname, message, true, player);
if (!answer_to_sender.empty()) {
// Send the answer to sender
SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_NORMAL,
answer_to_sender, wname));
}
}
void Server::handleCommand_Damage(NetworkPacket* pkt)
{
u16 damage;
*pkt >> damage;
RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
if (player == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player object for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
if (g_settings->getBool("enable_damage")) {
if (playersao->isDead()) {
verbosestream << "Server::ProcessData(): Info: "
"Ignoring damage as player " << player->getName()
<< " is already dead." << std::endl;
return;
}
actionstream << player->getName() << " damaged by "
<< (int)damage << " hp at " << PP(playersao->getBasePosition() / BS)
<< std::endl;
PlayerHPChangeReason reason(PlayerHPChangeReason::FALL);
playersao->setHP((s32)playersao->getHP() - (s32)damage, reason);
SendPlayerHPOrDie(playersao, reason);
}
}
void Server::handleCommand_Password(NetworkPacket* pkt)
{
if (pkt->getSize() != PASSWORD_SIZE * 2)
return;
std::string oldpwd;
std::string newpwd;
// Deny for clients using the new protocol
RemoteClient* client = getClient(pkt->getPeerId(), CS_Created);
if (client->net_proto_version >= 25) {
infostream << "Server::handleCommand_Password(): Denying change: "
<< " Client protocol version for peer_id=" << pkt->getPeerId()
<< " too new!" << std::endl;
return;
}
for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
char c = pkt->getChar(i);
if (c == 0)
break;
oldpwd += c;
}
for (u16 i = 0; i < PASSWORD_SIZE - 1; i++) {
char c = pkt->getChar(PASSWORD_SIZE + i);
if (c == 0)
break;
newpwd += c;
}
RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
if (player == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
if (!base64_is_valid(newpwd)) {
infostream<<"Server: " << player->getName() <<
" supplied invalid password hash" << std::endl;
// Wrong old password supplied!!
SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
L"Invalid new password hash supplied. Password NOT changed."));
return;
}
infostream << "Server: Client requests a password change from "
<< "'" << oldpwd << "' to '" << newpwd << "'" << std::endl;
std::string playername = player->getName();
std::string checkpwd;
m_script->getAuth(playername, &checkpwd, NULL);
if (oldpwd != checkpwd) {
infostream << "Server: invalid old password" << std::endl;
// Wrong old password supplied!!
SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
L"Invalid old password supplied. Password NOT changed."));
return;
}
bool success = m_script->setPassword(playername, newpwd);
if (success) {
actionstream << player->getName() << " changes password" << std::endl;
SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
L"Password change successful."));
} else {
actionstream << player->getName() << " tries to change password but "
<< "it fails" << std::endl;
SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
L"Password change failed or unavailable."));
}
}
void Server::handleCommand_PlayerItem(NetworkPacket* pkt)
{
if (pkt->getSize() < 2)
return;
RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
if (player == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player object for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
u16 item;
*pkt >> item;
playersao->setWieldIndex(item);
}
void Server::handleCommand_Respawn(NetworkPacket* pkt)
{
RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
if (player == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
assert(playersao);
if (!playersao->isDead())
return;
RespawnPlayer(pkt->getPeerId());
actionstream << player->getName() << " respawns at "
<< PP(playersao->getBasePosition() / BS) << std::endl;
// ActiveObject is added to environment in AsyncRunStep after
// the previous addition has been successfully removed
}
bool Server::checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what)
{
PlayerSAO *playersao = player->getPlayerSAO();
const InventoryList *hlist = playersao->getInventory()->getList("hand");
const ItemDefinition &playeritem_def =
playersao->getWieldedItem().getDefinition(m_itemdef);
const ItemDefinition &hand_def =
hlist ? hlist->getItem(0).getDefinition(m_itemdef) : m_itemdef->get("");
float max_d = BS * playeritem_def.range;
float max_d_hand = BS * hand_def.range;
if (max_d < 0 && max_d_hand >= 0)
max_d = max_d_hand;
else if (max_d < 0)
max_d = BS * 4.0f;
// Cube diagonal * 1.5 for maximal supported node extents:
// sqrt(3) * 1.5 ≅ 2.6
if (d > max_d + 2.6f * BS) {
actionstream << "Player " << player->getName()
<< " tried to access " << what
<< " from too far: "
<< "d=" << d <<", max_d=" << max_d
<< ". ignoring." << std::endl;
// Call callbacks
m_script->on_cheat(playersao, "interacted_too_far");
return false;
}
return true;
}
void Server::handleCommand_Interact(NetworkPacket* pkt)
{
/*
[0] u16 command
[2] u8 action
[3] u16 item
[5] u32 length of the next item (plen)
[9] serialized PointedThing
[9 + plen] player position information
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
5: rightclick air ("activate")
*/
u8 action;
u16 item_i;
*pkt >> action;
*pkt >> item_i;
std::istringstream tmp_is(pkt->readLongString(), std::ios::binary);
PointedThing pointed;
pointed.deSerialize(tmp_is);
verbosestream << "TOSERVER_INTERACT: action=" << (int)action << ", item="
<< item_i << ", pointed=" << pointed.dump() << std::endl;
RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
if (player == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player object for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
if (playersao->isDead()) {
actionstream << "Server: NoCheat: " << player->getName()
<< " tried to interact while dead; ignoring." << std::endl;
if (pointed.type == POINTEDTHING_NODE) {
// Re-send block to revert change on client-side
RemoteClient *client = getClient(pkt->getPeerId());
v3s16 blockpos = getNodeBlockPos(pointed.node_undersurface);
client->SetBlockNotSent(blockpos);
}
// Call callbacks
m_script->on_cheat(playersao, "interacted_while_dead");
return;
}
process_PlayerPos(player, playersao, pkt);
v3f player_pos = playersao->getLastGoodPosition();
// Update wielded item
playersao->setWieldIndex(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) {
verbosestream << "TOSERVER_INTERACT: "
"pointed object is NULL" << std::endl;
return;
}
}
v3f pointed_pos_under = player_pos;
v3f pointed_pos_above = player_pos;
if (pointed.type == POINTEDTHING_NODE) {
pointed_pos_under = intToFloat(p_under, BS);
pointed_pos_above = intToFloat(p_above, BS);
}
else if (pointed.type == POINTEDTHING_OBJECT) {
pointed_pos_under = pointed_object->getBasePosition();
pointed_pos_above = pointed_pos_under;
}
/*
Make sure the player is allowed to do it
*/
if (!checkPriv(player->getName(), "interact")) {
actionstream<<player->getName()<<" attempted to interact with "
<<pointed.dump()<<" without 'interact' privilege"
<<std::endl;
// Re-send block to revert change on client-side
RemoteClient *client = getClient(pkt->getPeerId());
// Digging completed -> under
if (action == 2) {
v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
client->SetBlockNotSent(blockpos);
}
// Placement -> above
else if (action == 3) {
v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
client->SetBlockNotSent(blockpos);
}
return;
}
/*
Check that target is reasonably close
(only when digging or placing things)
*/
static thread_local const bool enable_anticheat =
!g_settings->getBool("disable_anticheat");
if ((action == 0 || action == 2 || action == 3 || action == 4) &&
enable_anticheat && !isSingleplayer()) {
float d = playersao->getEyePosition()
.getDistanceFrom(pointed_pos_under);
if (!checkInteractDistance(player, d, pointed.dump())) {
// Re-send block to revert change on client-side
RemoteClient *client = getClient(pkt->getPeerId());
v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
client->SetBlockNotSent(blockpos);
return;
}
}
/*
If something goes wrong, this player is to blame
*/
RollbackScopeActor rollback_scope(m_rollback,
std::string("player:")+player->getName());
/*
0: start digging or punch object
*/
if (action == 0) {
if (pointed.type == POINTEDTHING_NODE) {
MapNode n(CONTENT_IGNORE);
bool pos_ok;
n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
if (!pos_ok) {
infostream << "Server: Not punching: Node not found."
<< " Adding block to emerge queue."
<< std::endl;
m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
getNodeBlockPos(p_above), false);
}
if (n.getContent() != CONTENT_IGNORE)
m_script->node_on_punch(p_under, n, playersao, pointed);
// Cheat prevention
playersao->noCheatDigStart(p_under);
}
else if (pointed.type == POINTEDTHING_OBJECT) {
// Skip if object can't be interacted with anymore
if (pointed_object->isGone())
return;
actionstream<<player->getName()<<" punches object "
<<pointed.object_id<<": "
<<pointed_object->getDescription()<<std::endl;
ItemStack punchitem = playersao->getWieldedItemOrHand();
ToolCapabilities toolcap =
punchitem.getToolCapabilities(m_itemdef);
v3f dir = (pointed_object->getBasePosition() -
(playersao->getBasePosition() + playersao->getEyeOffset())
).normalize();
float time_from_last_punch =
playersao->resetTimeFromLastPunch();
u16 src_original_hp = pointed_object->getHP();
u16 dst_origin_hp = playersao->getHP();
pointed_object->punch(dir, &toolcap, playersao,
time_from_last_punch);
// If the object is a player and its HP changed
if (src_original_hp != pointed_object->getHP() &&
pointed_object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
SendPlayerHPOrDie((PlayerSAO *)pointed_object,
PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, playersao));
}
// If the puncher is a player and its HP changed
if (dst_origin_hp != playersao->getHP())
SendPlayerHPOrDie(playersao,
PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, pointed_object));
}
} // action == 0
/*
1: stop digging
*/
else if (action == 1) {
} // action == 1
/*
2: Digging completed
*/
else if (action == 2) {
// Only digging of nodes
if (pointed.type == POINTEDTHING_NODE) {
bool pos_ok;
MapNode n = m_env->getMap().getNodeNoEx(p_under, &pos_ok);
if (!pos_ok) {
infostream << "Server: Not finishing digging: Node not found."
<< " Adding block to emerge queue."
<< std::endl;
m_emerge->enqueueBlockEmerge(pkt->getPeerId(),
getNodeBlockPos(p_above), false);
}
/* Cheat prevention */
bool is_valid_dig = true;
if (enable_anticheat && !isSingleplayer()) {
v3s16 nocheat_p = playersao->getNoCheatDigPos();
float nocheat_t = playersao->getNoCheatDigTime();
playersao->noCheatDigEnd();
// If player didn't start digging this, ignore dig
if (nocheat_p != p_under) {
infostream << "Server: NoCheat: " << player->getName()
<< " started digging "
<< PP(nocheat_p) << " and completed digging "
<< PP(p_under) << "; not digging." << std::endl;
is_valid_dig = false;
// Call callbacks
m_script->on_cheat(playersao, "finished_unknown_dig");
}
// Get player's wielded item
ItemStack playeritem = playersao->getWieldedItemOrHand();
ToolCapabilities playeritem_toolcap =
playeritem.getToolCapabilities(m_itemdef);
// Get diggability and expected digging time
DigParams params = getDigParams(m_nodedef->get(n).groups,
&playeritem_toolcap);
// If can't dig, try hand
if (!params.diggable) {
InventoryList *hlist = playersao->getInventory()->getList("hand");
const ToolCapabilities *tp = hlist
? &hlist->getItem(0).getToolCapabilities(m_itemdef)
: m_itemdef->get("").tool_capabilities;
if (tp)
params = getDigParams(m_nodedef->get(n).groups, tp);
}
// If can't dig, ignore dig
if (!params.diggable) {
infostream << "Server: NoCheat: " << player->getName()
<< " completed digging " << PP(p_under)
<< ", which is not diggable with tool. not digging."
<< std::endl;
is_valid_dig = false;
// Call callbacks
m_script->on_cheat(playersao, "dug_unbreakable");
}
// Check digging time
// If already invalidated, we don't have to
if (!is_valid_dig) {
// Well not our problem then
}
// Clean and long dig
else if (params.time > 2.0 && nocheat_t * 1.2 > params.time) {
// All is good, but grab time from pool; don't care if
// it's actually available
playersao->getDigPool().grab(params.time);
}
// Short or laggy dig
// Try getting the time from pool
else if (playersao->getDigPool().grab(params.time)) {
// All is good
}
// Dig not possible
else {
infostream << "Server: NoCheat: " << player->getName()
<< " completed digging " << PP(p_under)
<< "too fast; not digging." << std::endl;
is_valid_dig = false;
// Call callbacks
m_script->on_cheat(playersao, "dug_too_fast");
}
}
/* Actually dig node */
if (is_valid_dig && n.getContent() != CONTENT_IGNORE)
m_script->node_on_dig(p_under, n, playersao);
v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
RemoteClient *client = getClient(pkt->getPeerId());
// Send unusual result (that is, node not being removed)
if (m_env->getMap().getNodeNoEx(p_under).getContent() != CONTENT_AIR) {
// Re-send block to revert change on client-side
client->SetBlockNotSent(blockpos);
}
else {
client->ResendBlockIfOnWire(blockpos);
}
}
} // action == 2
/*
3: place block or right-click object
*/
else if (action == 3) {
ItemStack item = playersao->getWieldedItem();
// Reset build time counter
if (pointed.type == POINTEDTHING_NODE &&
item.getDefinition(m_itemdef).type == ITEM_NODE)
getClient(pkt->getPeerId())->m_time_from_building = 0.0;
if (pointed.type == POINTEDTHING_OBJECT) {
// Right click object
// Skip if object can't be interacted with anymore
if (pointed_object->isGone())
return;
actionstream << player->getName() << " right-clicks object "
<< pointed.object_id << ": "
<< pointed_object->getDescription() << std::endl;
// Do stuff
pointed_object->rightClick(playersao);
}
else if (m_script->item_OnPlace(
item, playersao, pointed)) {
// Placement was handled in lua
// Apply returned ItemStack
if (playersao->setWieldedItem(item)) {
SendInventory(playersao);
}
}
// If item has node placement prediction, always send the
// blocks to make sure the client knows what exactly happened
RemoteClient *client = getClient(pkt->getPeerId());
v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
if (!item.getDefinition(m_itemdef).node_placement_prediction.empty()) {
client->SetBlockNotSent(blockpos);
if (blockpos2 != blockpos) {
client->SetBlockNotSent(blockpos2);
}
}
else {
client->ResendBlockIfOnWire(blockpos);
if (blockpos2 != blockpos) {
client->ResendBlockIfOnWire(blockpos2);
}
}
} // action == 3
/*
4: use
*/
else if (action == 4) {
ItemStack item = playersao->getWieldedItem();
actionstream << player->getName() << " uses " << item.name
<< ", pointing at " << pointed.dump() << std::endl;
if (m_script->item_OnUse(
item, playersao, pointed)) {
// Apply returned ItemStack
if (playersao->setWieldedItem(item)) {
SendInventory(playersao);
}
}
} // action == 4
/*
5: rightclick air
*/
else if (action == 5) {
ItemStack item = playersao->getWieldedItem();
actionstream << player->getName() << " activates "
<< item.name << std::endl;
if (m_script->item_OnSecondaryUse(
item, playersao)) {
if( playersao->setWieldedItem(item)) {
SendInventory(playersao);
}
}
}
/*
Catch invalid actions
*/
else {
warningstream << "Server: Invalid action "
<< action << std::endl;
}
}
void Server::handleCommand_RemovedSounds(NetworkPacket* pkt)
{
u16 num;
*pkt >> num;
for (u16 k = 0; k < num; k++) {
s32 id;
*pkt >> id;
std::unordered_map<s32, ServerPlayingSound>::iterator i =
m_playing_sounds.find(id);
if (i == m_playing_sounds.end())
continue;
ServerPlayingSound &psound = i->second;
psound.clients.erase(pkt->getPeerId());
if (psound.clients.empty())
m_playing_sounds.erase(i++);
}
}
void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt)
{
v3s16 p;
std::string formname;
u16 num;
*pkt >> p >> formname >> num;
StringMap fields;
for (u16 k = 0; k < num; k++) {
std::string fieldname;
*pkt >> fieldname;
fields[fieldname] = pkt->readLongString();
}
RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
if (player == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player object for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
// If something goes wrong, this player is to blame
RollbackScopeActor rollback_scope(m_rollback,
std::string("player:")+player->getName());
// Check the target node for rollback data; leave others unnoticed
RollbackNode rn_old(&m_env->getMap(), p, this);
m_script->node_on_receive_fields(p, formname, fields, playersao);
// Report rollback data
RollbackNode rn_new(&m_env->getMap(), p, this);
if (rollback() && rn_new != rn_old) {
RollbackAction action;
action.setSetNode(p, rn_old, rn_new);
rollback()->reportAction(action);
}
}
void Server::handleCommand_InventoryFields(NetworkPacket* pkt)
{
std::string client_formspec_name;
u16 num;
*pkt >> client_formspec_name >> num;
StringMap fields;
for (u16 k = 0; k < num; k++) {
std::string fieldname;
*pkt >> fieldname;
fields[fieldname] = pkt->readLongString();
}
RemotePlayer *player = m_env->getPlayer(pkt->getPeerId());
if (player == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
PlayerSAO *playersao = player->getPlayerSAO();
if (playersao == NULL) {
errorstream << "Server::ProcessData(): Canceling: "
"No player object for peer_id=" << pkt->getPeerId()
<< " disconnecting peer!" << std::endl;
DisconnectPeer(pkt->getPeerId());
return;
}
if (client_formspec_name.empty()) { // pass through inventory submits
m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
return;
}
// verify that we displayed the formspec to the user
const auto peer_state_iterator = m_formspec_state_data.find(pkt->getPeerId());
if (peer_state_iterator != m_formspec_state_data.end()) {
const std::string &server_formspec_name = peer_state_iterator->second;
if (client_formspec_name == server_formspec_name) {
auto it = fields.find("quit");
if (it != fields.end() && it->second == "true")
m_formspec_state_data.erase(peer_state_iterator);
m_script->on_playerReceiveFields(playersao, client_formspec_name, fields);
return;
}
actionstream << "'" << player->getName()
<< "' submitted formspec ('" << client_formspec_name
<< "') but the name of the formspec doesn't match the"
" expected name ('" << server_formspec_name << "')";
} else {
actionstream << "'" << player->getName()
<< "' submitted formspec ('" << client_formspec_name
<< "') but server hasn't sent formspec to client";
}
actionstream << ", possible exploitation attempt" << std::endl;
}
void Server::handleCommand_FirstSrp(NetworkPacket* pkt)
{
RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
ClientState cstate = client->getState();
std::string playername = client->getName();
std::string salt;
std::string verification_key;
std::string addr_s = getPeerAddress(pkt->getPeerId()).serializeString();
u8 is_empty;
*pkt >> salt >> verification_key >> is_empty;
verbosestream << "Server: Got TOSERVER_FIRST_SRP from " << addr_s
<< ", with is_empty=" << (is_empty == 1) << std::endl;
// Either this packet is sent because the user is new or to change the password
if (cstate == CS_HelloSent) {
if (!client->isMechAllowed(AUTH_MECHANISM_FIRST_SRP)) {
actionstream << "Server: Client from " << addr_s
<< " tried to set password without being "
<< "authenticated, or the username being new." << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
return;
}
if (!isSingleplayer() &&
g_settings->getBool("disallow_empty_password") &&
is_empty == 1) {
actionstream << "Server: " << playername
<< " supplied empty password from " << addr_s << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_EMPTY_PASSWORD);
return;
}
std::string initial_ver_key;
initial_ver_key = encode_srp_verifier(verification_key, salt);
m_script->createAuth(playername, initial_ver_key);
acceptAuth(pkt->getPeerId(), false);
} else {
if (cstate < CS_SudoMode) {
infostream << "Server::ProcessData(): Ignoring TOSERVER_FIRST_SRP from "
<< addr_s << ": " << "Client has wrong state " << cstate << "."
<< std::endl;
return;
}
m_clients.event(pkt->getPeerId(), CSE_SudoLeave);
std::string pw_db_field = encode_srp_verifier(verification_key, salt);
bool success = m_script->setPassword(playername, pw_db_field);
if (success) {
actionstream << playername << " changes password" << std::endl;
SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
L"Password change successful."));
} else {
actionstream << playername << " tries to change password but "
<< "it fails" << std::endl;
SendChatMessage(pkt->getPeerId(), ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
L"Password change failed or unavailable."));
}
}
}
void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
{
RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
ClientState cstate = client->getState();
bool wantSudo = (cstate == CS_Active);
if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
actionstream << "Server: got SRP _A packet in wrong state "
<< cstate << " from "
<< getPeerAddress(pkt->getPeerId()).serializeString()
<< ". Ignoring." << std::endl;
return;
}
if (client->chosen_mech != AUTH_MECHANISM_NONE) {
actionstream << "Server: got SRP _A packet, while auth"
<< "is already going on with mech " << client->chosen_mech
<< " from " << getPeerAddress(pkt->getPeerId()).serializeString()
<< " (wantSudo=" << wantSudo << "). Ignoring." << std::endl;
if (wantSudo) {
DenySudoAccess(pkt->getPeerId());
return;
}
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
return;
}
std::string bytes_A;
u8 based_on;
*pkt >> bytes_A >> based_on;
infostream << "Server: TOSERVER_SRP_BYTES_A received with "
<< "based_on=" << int(based_on) << " and len_A="
<< bytes_A.length() << "." << std::endl;
AuthMechanism chosen = (based_on == 0) ?
AUTH_MECHANISM_LEGACY_PASSWORD : AUTH_MECHANISM_SRP;
if (wantSudo) {
if (!client->isSudoMechAllowed(chosen)) {
actionstream << "Server: Player \"" << client->getName()
<< "\" at " << getPeerAddress(pkt->getPeerId()).serializeString()
<< " tried to change password using unallowed mech "
<< chosen << "." << std::endl;
DenySudoAccess(pkt->getPeerId());
return;
}
} else {
if (!client->isMechAllowed(chosen)) {
actionstream << "Server: Client tried to authenticate from "
<< getPeerAddress(pkt->getPeerId()).serializeString()
<< " using unallowed mech " << chosen << "." << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
return;
}
}
client->chosen_mech = chosen;
std::string salt;
std::string verifier;
if (based_on == 0) {
generate_srp_verifier_and_salt(client->getName(), client->enc_pwd,
&verifier, &salt);
} else if (!decode_srp_verifier_and_salt(client->enc_pwd, &verifier, &salt)) {
// Non-base64 errors should have been catched in the init handler
actionstream << "Server: User " << client->getName()
<< " tried to log in, but srp verifier field"
<< " was invalid (most likely invalid base64)." << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
return;
}
char *bytes_B = 0;
size_t len_B = 0;
client->auth_data = srp_verifier_new(SRP_SHA256, SRP_NG_2048,
client->getName().c_str(),
(const unsigned char *) salt.c_str(), salt.size(),
(const unsigned char *) verifier.c_str(), verifier.size(),
(const unsigned char *) bytes_A.c_str(), bytes_A.size(),
NULL, 0,
(unsigned char **) &bytes_B, &len_B, NULL, NULL);
if (!bytes_B) {
actionstream << "Server: User " << client->getName()
<< " tried to log in, SRP-6a safety check violated in _A handler."
<< std::endl;
if (wantSudo) {
DenySudoAccess(pkt->getPeerId());
return;
}
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
return;
}
NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
resp_pkt << salt << std::string(bytes_B, len_B);
Send(&resp_pkt);
}
void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
{
RemoteClient* client = getClient(pkt->getPeerId(), CS_Invalid);
ClientState cstate = client->getState();
bool wantSudo = (cstate == CS_Active);
verbosestream << "Server: Received TOCLIENT_SRP_BYTES_M." << std::endl;
if (!((cstate == CS_HelloSent) || (cstate == CS_Active))) {
actionstream << "Server: got SRP _M packet in wrong state "
<< cstate << " from "
<< getPeerAddress(pkt->getPeerId()).serializeString()
<< ". Ignoring." << std::endl;
return;
}
if (client->chosen_mech != AUTH_MECHANISM_SRP &&
client->chosen_mech != AUTH_MECHANISM_LEGACY_PASSWORD) {
actionstream << "Server: got SRP _M packet, while auth"
<< "is going on with mech " << client->chosen_mech
<< " from " << getPeerAddress(pkt->getPeerId()).serializeString()
<< " (wantSudo=" << wantSudo << "). Denying." << std::endl;
if (wantSudo) {
DenySudoAccess(pkt->getPeerId());
return;
}
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
return;
}
std::string bytes_M;
*pkt >> bytes_M;
if (srp_verifier_get_session_key_length((SRPVerifier *) client->auth_data)
!= bytes_M.size()) {
actionstream << "Server: User " << client->getName()
<< " at " << getPeerAddress(pkt->getPeerId()).serializeString()
<< " sent bytes_M with invalid length " << bytes_M.size() << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
return;
}
unsigned char *bytes_HAMK = 0;
srp_verifier_verify_session((SRPVerifier *) client->auth_data,
(unsigned char *)bytes_M.c_str(), &bytes_HAMK);
if (!bytes_HAMK) {
if (wantSudo) {
actionstream << "Server: User " << client->getName()
<< " at " << getPeerAddress(pkt->getPeerId()).serializeString()
<< " tried to change their password, but supplied wrong"
<< " (SRP) password for authentication." << std::endl;
DenySudoAccess(pkt->getPeerId());
return;
}
std::string ip = getPeerAddress(pkt->getPeerId()).serializeString();
actionstream << "Server: User " << client->getName()
<< " at " << ip
<< " supplied wrong password (auth mechanism: SRP)."
<< std::endl;
m_script->on_auth_failure(client->getName(), ip);
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD);
return;
}
if (client->create_player_on_auth_success) {
std::string playername = client->getName();
m_script->createAuth(playername, client->enc_pwd);
std::string checkpwd; // not used, but needed for passing something
if (!m_script->getAuth(playername, &checkpwd, NULL)) {
actionstream << "Server: " << playername << " cannot be authenticated"
<< " (auth handler does not work?)" << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_SERVER_FAIL);
return;
}
client->create_player_on_auth_success = false;
}
acceptAuth(pkt->getPeerId(), wantSudo);
}
/*
* Mod channels
*/
void Server::handleCommand_ModChannelJoin(NetworkPacket *pkt)
{
std::string channel_name;
*pkt >> channel_name;
NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
pkt->getPeerId());
// Send signal to client to notify join succeed or not
if (g_settings->getBool("enable_mod_channels") &&
m_modchannel_mgr->joinChannel(channel_name, pkt->getPeerId())) {
resp_pkt << (u8) MODCHANNEL_SIGNAL_JOIN_OK;
infostream << "Peer " << pkt->getPeerId() << " joined channel " << channel_name
<< std::endl;
}
else {
resp_pkt << (u8)MODCHANNEL_SIGNAL_JOIN_FAILURE;
infostream << "Peer " << pkt->getPeerId() << " tried to join channel "
<< channel_name << ", but was already registered." << std::endl;
}
resp_pkt << channel_name;
Send(&resp_pkt);
}
void Server::handleCommand_ModChannelLeave(NetworkPacket *pkt)
{
std::string channel_name;
*pkt >> channel_name;
NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
pkt->getPeerId());
// Send signal to client to notify join succeed or not
if (g_settings->getBool("enable_mod_channels") &&
m_modchannel_mgr->leaveChannel(channel_name, pkt->getPeerId())) {
resp_pkt << (u8)MODCHANNEL_SIGNAL_LEAVE_OK;
infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
<< std::endl;
} else {
resp_pkt << (u8) MODCHANNEL_SIGNAL_LEAVE_FAILURE;
infostream << "Peer " << pkt->getPeerId() << " left channel " << channel_name
<< ", but was not registered." << std::endl;
}
resp_pkt << channel_name;
Send(&resp_pkt);
}
void Server::handleCommand_ModChannelMsg(NetworkPacket *pkt)
{
std::string channel_name, channel_msg;
*pkt >> channel_name >> channel_msg;
verbosestream << "Mod channel message received from peer " << pkt->getPeerId()
<< " on channel " << channel_name << " message: " << channel_msg << std::endl;
// If mod channels are not enabled, discard message
if (!g_settings->getBool("enable_mod_channels")) {
return;
}
// If channel not registered, signal it and ignore message
if (!m_modchannel_mgr->channelRegistered(channel_name)) {
NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_SIGNAL, 1 + 2 + channel_name.size(),
pkt->getPeerId());
resp_pkt << (u8)MODCHANNEL_SIGNAL_CHANNEL_NOT_REGISTERED << channel_name;
Send(&resp_pkt);
return;
}
// @TODO: filter, rate limit
broadcastModChannelMessage(channel_name, channel_msg, pkt->getPeerId());
}
| pgimeno/minetest | src/network/serverpackethandler.cpp | C++ | mit | 55,519 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "socket.h"
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <sstream>
#include <iomanip>
#include "util/string.h"
#include "util/numeric.h"
#include "constants.h"
#include "debug.h"
#include "settings.h"
#include "log.h"
#ifdef _WIN32
// Without this some of the network functions are not found on mingw
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#define LAST_SOCKET_ERR() WSAGetLastError()
typedef SOCKET socket_t;
typedef int socklen_t;
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#define LAST_SOCKET_ERR() (errno)
typedef int socket_t;
#endif
// Set to true to enable verbose debug output
bool socket_enable_debug_output = false; // yuck
static bool g_sockets_initialized = false;
// Initialize sockets
void sockets_init()
{
#ifdef _WIN32
// Windows needs sockets to be initialized before use
WSADATA WsaData;
if (WSAStartup(MAKEWORD(2, 2), &WsaData) != NO_ERROR)
throw SocketException("WSAStartup failed");
#endif
g_sockets_initialized = true;
}
void sockets_cleanup()
{
#ifdef _WIN32
// On Windows, cleanup sockets after use
WSACleanup();
#endif
}
/*
UDPSocket
*/
UDPSocket::UDPSocket(bool ipv6)
{
init(ipv6, false);
}
bool UDPSocket::init(bool ipv6, bool noExceptions)
{
if (!g_sockets_initialized) {
dstream << "Sockets not initialized" << std::endl;
return false;
}
// Use IPv6 if specified
m_addr_family = ipv6 ? AF_INET6 : AF_INET;
m_handle = socket(m_addr_family, SOCK_DGRAM, IPPROTO_UDP);
if (socket_enable_debug_output) {
dstream << "UDPSocket(" << (int)m_handle
<< ")::UDPSocket(): ipv6 = " << (ipv6 ? "true" : "false")
<< std::endl;
}
if (m_handle <= 0) {
if (noExceptions) {
return false;
}
throw SocketException(std::string("Failed to create socket: error ") +
itos(LAST_SOCKET_ERR()));
}
setTimeoutMs(0);
if (m_addr_family == AF_INET6) {
// Allow our socket to accept both IPv4 and IPv6 connections
// required on Windows:
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb513665(v=vs.85).aspx
int value = 0;
setsockopt(m_handle, IPPROTO_IPV6, IPV6_V6ONLY,
reinterpret_cast<char *>(&value), sizeof(value));
}
return true;
}
UDPSocket::~UDPSocket()
{
if (socket_enable_debug_output) {
dstream << "UDPSocket( " << (int)m_handle << ")::~UDPSocket()"
<< std::endl;
}
#ifdef _WIN32
closesocket(m_handle);
#else
close(m_handle);
#endif
}
void UDPSocket::Bind(Address addr)
{
if (socket_enable_debug_output) {
dstream << "UDPSocket(" << (int)m_handle
<< ")::Bind(): " << addr.serializeString() << ":"
<< addr.getPort() << std::endl;
}
if (addr.getFamily() != m_addr_family) {
static const char *errmsg =
"Socket and bind address families do not match";
errorstream << "Bind failed: " << errmsg << std::endl;
throw SocketException(errmsg);
}
if (m_addr_family == AF_INET6) {
struct sockaddr_in6 address;
memset(&address, 0, sizeof(address));
address = addr.getAddress6();
address.sin6_family = AF_INET6;
address.sin6_port = htons(addr.getPort());
if (bind(m_handle, (const struct sockaddr *)&address,
sizeof(struct sockaddr_in6)) < 0) {
dstream << (int)m_handle << ": Bind failed: " << strerror(errno)
<< std::endl;
throw SocketException("Failed to bind socket");
}
} else {
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
address = addr.getAddress();
address.sin_family = AF_INET;
address.sin_port = htons(addr.getPort());
if (bind(m_handle, (const struct sockaddr *)&address,
sizeof(struct sockaddr_in)) < 0) {
dstream << (int)m_handle << ": Bind failed: " << strerror(errno)
<< std::endl;
throw SocketException("Failed to bind socket");
}
}
}
void UDPSocket::Send(const Address &destination, const void *data, int size)
{
bool dumping_packet = false; // for INTERNET_SIMULATOR
if (INTERNET_SIMULATOR)
dumping_packet = myrand() % INTERNET_SIMULATOR_PACKET_LOSS == 0;
if (socket_enable_debug_output) {
// Print packet destination and size
dstream << (int)m_handle << " -> ";
destination.print(&dstream);
dstream << ", size=" << size;
// Print packet contents
dstream << ", data=";
for (int i = 0; i < size && i < 20; i++) {
if (i % 2 == 0)
dstream << " ";
unsigned int a = ((const unsigned char *)data)[i];
dstream << std::hex << std::setw(2) << std::setfill('0') << a;
}
if (size > 20)
dstream << "...";
if (dumping_packet)
dstream << " (DUMPED BY INTERNET_SIMULATOR)";
dstream << std::endl;
}
if (dumping_packet) {
// Lol let's forget it
dstream << "UDPSocket::Send(): INTERNET_SIMULATOR: dumping packet."
<< std::endl;
return;
}
if (destination.getFamily() != m_addr_family)
throw SendFailedException("Address family mismatch");
int sent;
if (m_addr_family == AF_INET6) {
struct sockaddr_in6 address = destination.getAddress6();
address.sin6_port = htons(destination.getPort());
sent = sendto(m_handle, (const char *)data, size, 0,
(struct sockaddr *)&address, sizeof(struct sockaddr_in6));
} else {
struct sockaddr_in address = destination.getAddress();
address.sin_port = htons(destination.getPort());
sent = sendto(m_handle, (const char *)data, size, 0,
(struct sockaddr *)&address, sizeof(struct sockaddr_in));
}
if (sent != size)
throw SendFailedException("Failed to send packet");
}
int UDPSocket::Receive(Address &sender, void *data, int size)
{
// Return on timeout
if (!WaitData(m_timeout_ms))
return -1;
int received;
if (m_addr_family == AF_INET6) {
struct sockaddr_in6 address;
memset(&address, 0, sizeof(address));
socklen_t address_len = sizeof(address);
received = recvfrom(m_handle, (char *)data, size, 0,
(struct sockaddr *)&address, &address_len);
if (received < 0)
return -1;
u16 address_port = ntohs(address.sin6_port);
IPv6AddressBytes bytes;
memcpy(bytes.bytes, address.sin6_addr.s6_addr, 16);
sender = Address(&bytes, address_port);
} else {
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
socklen_t address_len = sizeof(address);
received = recvfrom(m_handle, (char *)data, size, 0,
(struct sockaddr *)&address, &address_len);
if (received < 0)
return -1;
u32 address_ip = ntohl(address.sin_addr.s_addr);
u16 address_port = ntohs(address.sin_port);
sender = Address(address_ip, address_port);
}
if (socket_enable_debug_output) {
// Print packet sender and size
dstream << (int)m_handle << " <- ";
sender.print(&dstream);
dstream << ", size=" << received;
// Print packet contents
dstream << ", data=";
for (int i = 0; i < received && i < 20; i++) {
if (i % 2 == 0)
dstream << " ";
unsigned int a = ((const unsigned char *)data)[i];
dstream << std::hex << std::setw(2) << std::setfill('0') << a;
}
if (received > 20)
dstream << "...";
dstream << std::endl;
}
return received;
}
int UDPSocket::GetHandle()
{
return m_handle;
}
void UDPSocket::setTimeoutMs(int timeout_ms)
{
m_timeout_ms = timeout_ms;
}
bool UDPSocket::WaitData(int timeout_ms)
{
fd_set readset;
int result;
// Initialize the set
FD_ZERO(&readset);
FD_SET(m_handle, &readset);
// Initialize time out struct
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = timeout_ms * 1000;
// select()
result = select(m_handle + 1, &readset, NULL, NULL, &tv);
if (result == 0)
return false;
if (result < 0 && (errno == EINTR || errno == EBADF)) {
// N.B. select() fails when sockets are destroyed on Connection's dtor
// with EBADF. Instead of doing tricky synchronization, allow this
// thread to exit but don't throw an exception.
return false;
}
if (result < 0) {
dstream << m_handle << ": Select failed: " << strerror(errno)
<< std::endl;
#ifdef _WIN32
int e = WSAGetLastError();
dstream << (int)m_handle << ": WSAGetLastError()=" << e << std::endl;
if (e == 10004 /* WSAEINTR */ || e == 10009 /* WSAEBADF */) {
infostream << "Ignoring WSAEINTR/WSAEBADF." << std::endl;
return false;
}
#endif
throw SocketException("Select failed");
} else if (!FD_ISSET(m_handle, &readset)) {
// No data
return false;
}
// There is data
return true;
}
| pgimeno/minetest | src/network/socket.cpp | C++ | mit | 9,181 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#ifdef _WIN32
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#endif
#include <ostream>
#include <cstring>
#include "address.h"
#include "irrlichttypes.h"
#include "networkexceptions.h"
extern bool socket_enable_debug_output;
void sockets_init();
void sockets_cleanup();
class UDPSocket
{
public:
UDPSocket() = default;
UDPSocket(bool ipv6);
~UDPSocket();
void Bind(Address addr);
bool init(bool ipv6, bool noExceptions = false);
// void Close();
// bool IsOpen();
void Send(const Address &destination, const void *data, int size);
// Returns -1 if there is no data
int Receive(Address &sender, void *data, int size);
int GetHandle(); // For debugging purposes only
void setTimeoutMs(int timeout_ms);
// Returns true if there is data, false if timeout occurred
bool WaitData(int timeout_ms);
private:
int m_handle;
int m_timeout_ms;
int m_addr_family;
};
| pgimeno/minetest | src/network/socket.h | C++ | mit | 1,806 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "nodedef.h"
#include "itemdef.h"
#ifndef SERVER
#include "client/mesh.h"
#include "client/shader.h"
#include "client/client.h"
#include "client/renderingengine.h"
#include "client/tile.h"
#include <IMeshManipulator.h>
#endif
#include "log.h"
#include "settings.h"
#include "nameidmapping.h"
#include "util/numeric.h"
#include "util/serialize.h"
#include "exceptions.h"
#include "debug.h"
#include "gamedef.h"
#include "mapnode.h"
#include <fstream> // Used in applyTextureOverrides()
#include <algorithm>
#include <cmath>
/*
NodeBox
*/
void NodeBox::reset()
{
type = NODEBOX_REGULAR;
// default is empty
fixed.clear();
// default is sign/ladder-like
wall_top = aabb3f(-BS/2, BS/2-BS/16., -BS/2, BS/2, BS/2, BS/2);
wall_bottom = aabb3f(-BS/2, -BS/2, -BS/2, BS/2, -BS/2+BS/16., BS/2);
wall_side = aabb3f(-BS/2, -BS/2, -BS/2, -BS/2+BS/16., BS/2, BS/2);
// no default for other parts
connect_top.clear();
connect_bottom.clear();
connect_front.clear();
connect_left.clear();
connect_back.clear();
connect_right.clear();
disconnected_top.clear();
disconnected_bottom.clear();
disconnected_front.clear();
disconnected_left.clear();
disconnected_back.clear();
disconnected_right.clear();
disconnected.clear();
disconnected_sides.clear();
}
void NodeBox::serialize(std::ostream &os, u16 protocol_version) const
{
// Protocol >= 36
const u8 version = 6;
writeU8(os, version);
switch (type) {
case NODEBOX_LEVELED:
case NODEBOX_FIXED:
writeU8(os, type);
writeU16(os, fixed.size());
for (const aabb3f &nodebox : fixed) {
writeV3F32(os, nodebox.MinEdge);
writeV3F32(os, nodebox.MaxEdge);
}
break;
case NODEBOX_WALLMOUNTED:
writeU8(os, type);
writeV3F32(os, wall_top.MinEdge);
writeV3F32(os, wall_top.MaxEdge);
writeV3F32(os, wall_bottom.MinEdge);
writeV3F32(os, wall_bottom.MaxEdge);
writeV3F32(os, wall_side.MinEdge);
writeV3F32(os, wall_side.MaxEdge);
break;
case NODEBOX_CONNECTED:
writeU8(os, type);
#define WRITEBOX(box) \
writeU16(os, (box).size()); \
for (const aabb3f &i: (box)) { \
writeV3F32(os, i.MinEdge); \
writeV3F32(os, i.MaxEdge); \
};
WRITEBOX(fixed);
WRITEBOX(connect_top);
WRITEBOX(connect_bottom);
WRITEBOX(connect_front);
WRITEBOX(connect_left);
WRITEBOX(connect_back);
WRITEBOX(connect_right);
WRITEBOX(disconnected_top);
WRITEBOX(disconnected_bottom);
WRITEBOX(disconnected_front);
WRITEBOX(disconnected_left);
WRITEBOX(disconnected_back);
WRITEBOX(disconnected_right);
WRITEBOX(disconnected);
WRITEBOX(disconnected_sides);
break;
default:
writeU8(os, type);
break;
}
}
void NodeBox::deSerialize(std::istream &is)
{
int version = readU8(is);
if (version < 6)
throw SerializationError("unsupported NodeBox version");
reset();
type = (enum NodeBoxType)readU8(is);
if(type == NODEBOX_FIXED || type == NODEBOX_LEVELED)
{
u16 fixed_count = readU16(is);
while(fixed_count--)
{
aabb3f box;
box.MinEdge = readV3F32(is);
box.MaxEdge = readV3F32(is);
fixed.push_back(box);
}
}
else if(type == NODEBOX_WALLMOUNTED)
{
wall_top.MinEdge = readV3F32(is);
wall_top.MaxEdge = readV3F32(is);
wall_bottom.MinEdge = readV3F32(is);
wall_bottom.MaxEdge = readV3F32(is);
wall_side.MinEdge = readV3F32(is);
wall_side.MaxEdge = readV3F32(is);
}
else if (type == NODEBOX_CONNECTED)
{
#define READBOXES(box) { \
count = readU16(is); \
(box).reserve(count); \
while (count--) { \
v3f min = readV3F32(is); \
v3f max = readV3F32(is); \
(box).emplace_back(min, max); }; }
u16 count;
READBOXES(fixed);
READBOXES(connect_top);
READBOXES(connect_bottom);
READBOXES(connect_front);
READBOXES(connect_left);
READBOXES(connect_back);
READBOXES(connect_right);
READBOXES(disconnected_top);
READBOXES(disconnected_bottom);
READBOXES(disconnected_front);
READBOXES(disconnected_left);
READBOXES(disconnected_back);
READBOXES(disconnected_right);
READBOXES(disconnected);
READBOXES(disconnected_sides);
}
}
/*
TileDef
*/
#define TILE_FLAG_BACKFACE_CULLING (1 << 0)
#define TILE_FLAG_TILEABLE_HORIZONTAL (1 << 1)
#define TILE_FLAG_TILEABLE_VERTICAL (1 << 2)
#define TILE_FLAG_HAS_COLOR (1 << 3)
#define TILE_FLAG_HAS_SCALE (1 << 4)
#define TILE_FLAG_HAS_ALIGN_STYLE (1 << 5)
void TileDef::serialize(std::ostream &os, u16 protocol_version) const
{
// protocol_version >= 36
u8 version = 6;
writeU8(os, version);
os << serializeString(name);
animation.serialize(os, version);
bool has_scale = scale > 0;
u16 flags = 0;
if (backface_culling)
flags |= TILE_FLAG_BACKFACE_CULLING;
if (tileable_horizontal)
flags |= TILE_FLAG_TILEABLE_HORIZONTAL;
if (tileable_vertical)
flags |= TILE_FLAG_TILEABLE_VERTICAL;
if (has_color)
flags |= TILE_FLAG_HAS_COLOR;
if (has_scale)
flags |= TILE_FLAG_HAS_SCALE;
if (align_style != ALIGN_STYLE_NODE)
flags |= TILE_FLAG_HAS_ALIGN_STYLE;
writeU16(os, flags);
if (has_color) {
writeU8(os, color.getRed());
writeU8(os, color.getGreen());
writeU8(os, color.getBlue());
}
if (has_scale)
writeU8(os, scale);
if (align_style != ALIGN_STYLE_NODE)
writeU8(os, align_style);
}
void TileDef::deSerialize(std::istream &is, u8 contentfeatures_version,
NodeDrawType drawtype)
{
int version = readU8(is);
if (version < 6)
throw SerializationError("unsupported TileDef version");
name = deSerializeString(is);
animation.deSerialize(is, version);
u16 flags = readU16(is);
backface_culling = flags & TILE_FLAG_BACKFACE_CULLING;
tileable_horizontal = flags & TILE_FLAG_TILEABLE_HORIZONTAL;
tileable_vertical = flags & TILE_FLAG_TILEABLE_VERTICAL;
has_color = flags & TILE_FLAG_HAS_COLOR;
bool has_scale = flags & TILE_FLAG_HAS_SCALE;
bool has_align_style = flags & TILE_FLAG_HAS_ALIGN_STYLE;
if (has_color) {
color.setRed(readU8(is));
color.setGreen(readU8(is));
color.setBlue(readU8(is));
}
scale = has_scale ? readU8(is) : 0;
if (has_align_style)
align_style = static_cast<AlignStyle>(readU8(is));
else
align_style = ALIGN_STYLE_NODE;
}
void TextureSettings::readSettings()
{
connected_glass = g_settings->getBool("connected_glass");
opaque_water = g_settings->getBool("opaque_water");
bool enable_shaders = g_settings->getBool("enable_shaders");
bool enable_bumpmapping = g_settings->getBool("enable_bumpmapping");
bool enable_parallax_occlusion = g_settings->getBool("enable_parallax_occlusion");
bool smooth_lighting = g_settings->getBool("smooth_lighting");
enable_mesh_cache = g_settings->getBool("enable_mesh_cache");
enable_minimap = g_settings->getBool("enable_minimap");
node_texture_size = g_settings->getU16("texture_min_size");
std::string leaves_style_str = g_settings->get("leaves_style");
std::string world_aligned_mode_str = g_settings->get("world_aligned_mode");
std::string autoscale_mode_str = g_settings->get("autoscale_mode");
// Mesh cache is not supported in combination with smooth lighting
if (smooth_lighting)
enable_mesh_cache = false;
use_normal_texture = enable_shaders &&
(enable_bumpmapping || enable_parallax_occlusion);
if (leaves_style_str == "fancy") {
leaves_style = LEAVES_FANCY;
} else if (leaves_style_str == "simple") {
leaves_style = LEAVES_SIMPLE;
} else {
leaves_style = LEAVES_OPAQUE;
}
if (world_aligned_mode_str == "enable")
world_aligned_mode = WORLDALIGN_ENABLE;
else if (world_aligned_mode_str == "force_solid")
world_aligned_mode = WORLDALIGN_FORCE;
else if (world_aligned_mode_str == "force_nodebox")
world_aligned_mode = WORLDALIGN_FORCE_NODEBOX;
else
world_aligned_mode = WORLDALIGN_DISABLE;
if (autoscale_mode_str == "enable")
autoscale_mode = AUTOSCALE_ENABLE;
else if (autoscale_mode_str == "force")
autoscale_mode = AUTOSCALE_FORCE;
else
autoscale_mode = AUTOSCALE_DISABLE;
}
/*
ContentFeatures
*/
ContentFeatures::ContentFeatures()
{
reset();
}
void ContentFeatures::reset()
{
/*
Cached stuff
*/
#ifndef SERVER
solidness = 2;
visual_solidness = 0;
backface_culling = true;
#endif
has_on_construct = false;
has_on_destruct = false;
has_after_destruct = false;
/*
Actual data
NOTE: Most of this is always overridden by the default values given
in builtin.lua
*/
name = "";
groups.clear();
// Unknown nodes can be dug
groups["dig_immediate"] = 2;
drawtype = NDT_NORMAL;
mesh = "";
#ifndef SERVER
for (auto &i : mesh_ptr)
i = NULL;
minimap_color = video::SColor(0, 0, 0, 0);
#endif
visual_scale = 1.0;
for (auto &i : tiledef)
i = TileDef();
for (auto &j : tiledef_special)
j = TileDef();
alpha = 255;
post_effect_color = video::SColor(0, 0, 0, 0);
param_type = CPT_NONE;
param_type_2 = CPT2_NONE;
is_ground_content = false;
light_propagates = false;
sunlight_propagates = false;
walkable = true;
pointable = true;
diggable = true;
climbable = false;
buildable_to = false;
floodable = false;
rightclickable = true;
leveled = 0;
liquid_type = LIQUID_NONE;
liquid_alternative_flowing = "";
liquid_alternative_source = "";
liquid_viscosity = 0;
liquid_renewable = true;
liquid_range = LIQUID_LEVEL_MAX+1;
drowning = 0;
light_source = 0;
damage_per_second = 0;
node_box = NodeBox();
selection_box = NodeBox();
collision_box = NodeBox();
waving = 0;
legacy_facedir_simple = false;
legacy_wallmounted = false;
sound_footstep = SimpleSoundSpec();
sound_dig = SimpleSoundSpec("__group");
sound_dug = SimpleSoundSpec();
connects_to.clear();
connects_to_ids.clear();
connect_sides = 0;
color = video::SColor(0xFFFFFFFF);
palette_name = "";
palette = NULL;
node_dig_prediction = "air";
}
void ContentFeatures::serialize(std::ostream &os, u16 protocol_version) const
{
const u8 version = CONTENTFEATURES_VERSION;
writeU8(os, version);
// general
os << serializeString(name);
writeU16(os, groups.size());
for (const auto &group : groups) {
os << serializeString(group.first);
writeS16(os, group.second);
}
writeU8(os, param_type);
writeU8(os, param_type_2);
// visual
writeU8(os, drawtype);
os << serializeString(mesh);
writeF32(os, visual_scale);
writeU8(os, 6);
for (const TileDef &td : tiledef)
td.serialize(os, protocol_version);
for (const TileDef &td : tiledef_overlay)
td.serialize(os, protocol_version);
writeU8(os, CF_SPECIAL_COUNT);
for (const TileDef &td : tiledef_special) {
td.serialize(os, protocol_version);
}
writeU8(os, alpha);
writeU8(os, color.getRed());
writeU8(os, color.getGreen());
writeU8(os, color.getBlue());
os << serializeString(palette_name);
writeU8(os, waving);
writeU8(os, connect_sides);
writeU16(os, connects_to_ids.size());
for (u16 connects_to_id : connects_to_ids)
writeU16(os, connects_to_id);
writeARGB8(os, post_effect_color);
writeU8(os, leveled);
// lighting
writeU8(os, light_propagates);
writeU8(os, sunlight_propagates);
writeU8(os, light_source);
// map generation
writeU8(os, is_ground_content);
// interaction
writeU8(os, walkable);
writeU8(os, pointable);
writeU8(os, diggable);
writeU8(os, climbable);
writeU8(os, buildable_to);
writeU8(os, rightclickable);
writeU32(os, damage_per_second);
// liquid
writeU8(os, liquid_type);
os << serializeString(liquid_alternative_flowing);
os << serializeString(liquid_alternative_source);
writeU8(os, liquid_viscosity);
writeU8(os, liquid_renewable);
writeU8(os, liquid_range);
writeU8(os, drowning);
writeU8(os, floodable);
// node boxes
node_box.serialize(os, protocol_version);
selection_box.serialize(os, protocol_version);
collision_box.serialize(os, protocol_version);
// sound
sound_footstep.serialize(os, version);
sound_dig.serialize(os, version);
sound_dug.serialize(os, version);
// legacy
writeU8(os, legacy_facedir_simple);
writeU8(os, legacy_wallmounted);
os << serializeString(node_dig_prediction);
}
void ContentFeatures::correctAlpha(TileDef *tiles, int length)
{
// alpha == 0 means that the node is using texture alpha
if (alpha == 0 || alpha == 255)
return;
for (int i = 0; i < length; i++) {
if (tiles[i].name.empty())
continue;
std::stringstream s;
s << tiles[i].name << "^[noalpha^[opacity:" << ((int)alpha);
tiles[i].name = s.str();
}
}
void ContentFeatures::deSerialize(std::istream &is)
{
// version detection
const u8 version = readU8(is);
if (version < CONTENTFEATURES_VERSION)
throw SerializationError("unsupported ContentFeatures version");
// general
name = deSerializeString(is);
groups.clear();
u32 groups_size = readU16(is);
for (u32 i = 0; i < groups_size; i++) {
std::string name = deSerializeString(is);
int value = readS16(is);
groups[name] = value;
}
param_type = (enum ContentParamType) readU8(is);
param_type_2 = (enum ContentParamType2) readU8(is);
// visual
drawtype = (enum NodeDrawType) readU8(is);
mesh = deSerializeString(is);
visual_scale = readF32(is);
if (readU8(is) != 6)
throw SerializationError("unsupported tile count");
for (TileDef &td : tiledef)
td.deSerialize(is, version, drawtype);
for (TileDef &td : tiledef_overlay)
td.deSerialize(is, version, drawtype);
if (readU8(is) != CF_SPECIAL_COUNT)
throw SerializationError("unsupported CF_SPECIAL_COUNT");
for (TileDef &td : tiledef_special)
td.deSerialize(is, version, drawtype);
alpha = readU8(is);
color.setRed(readU8(is));
color.setGreen(readU8(is));
color.setBlue(readU8(is));
palette_name = deSerializeString(is);
waving = readU8(is);
connect_sides = readU8(is);
u16 connects_to_size = readU16(is);
connects_to_ids.clear();
for (u16 i = 0; i < connects_to_size; i++)
connects_to_ids.push_back(readU16(is));
post_effect_color = readARGB8(is);
leveled = readU8(is);
// lighting-related
light_propagates = readU8(is);
sunlight_propagates = readU8(is);
light_source = readU8(is);
light_source = MYMIN(light_source, LIGHT_MAX);
// map generation
is_ground_content = readU8(is);
// interaction
walkable = readU8(is);
pointable = readU8(is);
diggable = readU8(is);
climbable = readU8(is);
buildable_to = readU8(is);
rightclickable = readU8(is);
damage_per_second = readU32(is);
// liquid
liquid_type = (enum LiquidType) readU8(is);
liquid_alternative_flowing = deSerializeString(is);
liquid_alternative_source = deSerializeString(is);
liquid_viscosity = readU8(is);
liquid_renewable = readU8(is);
liquid_range = readU8(is);
drowning = readU8(is);
floodable = readU8(is);
// node boxes
node_box.deSerialize(is);
selection_box.deSerialize(is);
collision_box.deSerialize(is);
// sounds
sound_footstep.deSerialize(is, version);
sound_dig.deSerialize(is, version);
sound_dug.deSerialize(is, version);
// read legacy properties
legacy_facedir_simple = readU8(is);
legacy_wallmounted = readU8(is);
try {
node_dig_prediction = deSerializeString(is);
} catch(SerializationError &e) {};
}
#ifndef SERVER
static void fillTileAttribs(ITextureSource *tsrc, TileLayer *layer,
const TileSpec &tile, const TileDef &tiledef, video::SColor color,
u8 material_type, u32 shader_id, bool backface_culling,
const TextureSettings &tsettings)
{
layer->shader_id = shader_id;
layer->texture = tsrc->getTextureForMesh(tiledef.name, &layer->texture_id);
layer->material_type = material_type;
bool has_scale = tiledef.scale > 0;
if (((tsettings.autoscale_mode == AUTOSCALE_ENABLE) && !has_scale) ||
(tsettings.autoscale_mode == AUTOSCALE_FORCE)) {
auto texture_size = layer->texture->getOriginalSize();
float base_size = tsettings.node_texture_size;
float size = std::fmin(texture_size.Width, texture_size.Height);
layer->scale = std::fmax(base_size, size) / base_size;
} else if (has_scale) {
layer->scale = tiledef.scale;
} else {
layer->scale = 1;
}
if (!tile.world_aligned)
layer->scale = 1;
// Normal texture and shader flags texture
if (tsettings.use_normal_texture) {
layer->normal_texture = tsrc->getNormalTexture(tiledef.name);
}
layer->flags_texture = tsrc->getShaderFlagsTexture(layer->normal_texture ? true : false);
// Material flags
layer->material_flags = 0;
if (backface_culling)
layer->material_flags |= MATERIAL_FLAG_BACKFACE_CULLING;
if (tiledef.animation.type != TAT_NONE)
layer->material_flags |= MATERIAL_FLAG_ANIMATION;
if (tiledef.tileable_horizontal)
layer->material_flags |= MATERIAL_FLAG_TILEABLE_HORIZONTAL;
if (tiledef.tileable_vertical)
layer->material_flags |= MATERIAL_FLAG_TILEABLE_VERTICAL;
// Color
layer->has_color = tiledef.has_color;
if (tiledef.has_color)
layer->color = tiledef.color;
else
layer->color = color;
// Animation parameters
int frame_count = 1;
if (layer->material_flags & MATERIAL_FLAG_ANIMATION) {
int frame_length_ms;
tiledef.animation.determineParams(layer->texture->getOriginalSize(),
&frame_count, &frame_length_ms, NULL);
layer->animation_frame_count = frame_count;
layer->animation_frame_length_ms = frame_length_ms;
}
if (frame_count == 1) {
layer->material_flags &= ~MATERIAL_FLAG_ANIMATION;
} else {
std::ostringstream os(std::ios::binary);
if (!layer->frames) {
layer->frames = std::make_shared<std::vector<FrameSpec>>();
}
layer->frames->resize(frame_count);
for (int i = 0; i < frame_count; i++) {
FrameSpec frame;
os.str("");
os << tiledef.name;
tiledef.animation.getTextureModifer(os,
layer->texture->getOriginalSize(), i);
frame.texture = tsrc->getTextureForMesh(os.str(), &frame.texture_id);
if (layer->normal_texture)
frame.normal_texture = tsrc->getNormalTexture(os.str());
frame.flags_texture = layer->flags_texture;
(*layer->frames)[i] = frame;
}
}
}
#endif
#ifndef SERVER
bool isWorldAligned(AlignStyle style, WorldAlignMode mode, NodeDrawType drawtype)
{
if (style == ALIGN_STYLE_WORLD)
return true;
if (mode == WORLDALIGN_DISABLE)
return false;
if (style == ALIGN_STYLE_USER_DEFINED)
return true;
if (drawtype == NDT_NORMAL)
return mode >= WORLDALIGN_FORCE;
if (drawtype == NDT_NODEBOX)
return mode >= WORLDALIGN_FORCE_NODEBOX;
return false;
}
void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc,
scene::IMeshManipulator *meshmanip, Client *client, const TextureSettings &tsettings)
{
// minimap pixel color - the average color of a texture
if (tsettings.enable_minimap && !tiledef[0].name.empty())
minimap_color = tsrc->getTextureAverageColor(tiledef[0].name);
// Figure out the actual tiles to use
TileDef tdef[6];
for (u32 j = 0; j < 6; j++) {
tdef[j] = tiledef[j];
if (tdef[j].name.empty())
tdef[j].name = "unknown_node.png";
}
// also the overlay tiles
TileDef tdef_overlay[6];
for (u32 j = 0; j < 6; j++)
tdef_overlay[j] = tiledef_overlay[j];
// also the special tiles
TileDef tdef_spec[6];
for (u32 j = 0; j < CF_SPECIAL_COUNT; j++)
tdef_spec[j] = tiledef_special[j];
bool is_liquid = false;
u8 material_type = (alpha == 255) ?
TILE_MATERIAL_BASIC : TILE_MATERIAL_ALPHA;
switch (drawtype) {
default:
case NDT_NORMAL:
material_type = (alpha == 255) ?
TILE_MATERIAL_OPAQUE : TILE_MATERIAL_ALPHA;
solidness = 2;
break;
case NDT_AIRLIKE:
solidness = 0;
break;
case NDT_LIQUID:
assert(liquid_type == LIQUID_SOURCE);
if (tsettings.opaque_water)
alpha = 255;
solidness = 1;
is_liquid = true;
break;
case NDT_FLOWINGLIQUID:
assert(liquid_type == LIQUID_FLOWING);
solidness = 0;
if (tsettings.opaque_water)
alpha = 255;
is_liquid = true;
break;
case NDT_GLASSLIKE:
solidness = 0;
visual_solidness = 1;
break;
case NDT_GLASSLIKE_FRAMED:
solidness = 0;
visual_solidness = 1;
break;
case NDT_GLASSLIKE_FRAMED_OPTIONAL:
solidness = 0;
visual_solidness = 1;
drawtype = tsettings.connected_glass ? NDT_GLASSLIKE_FRAMED : NDT_GLASSLIKE;
break;
case NDT_ALLFACES:
solidness = 0;
visual_solidness = 1;
break;
case NDT_ALLFACES_OPTIONAL:
if (tsettings.leaves_style == LEAVES_FANCY) {
drawtype = NDT_ALLFACES;
solidness = 0;
visual_solidness = 1;
} else if (tsettings.leaves_style == LEAVES_SIMPLE) {
for (u32 j = 0; j < 6; j++) {
if (!tdef_spec[j].name.empty())
tdef[j].name = tdef_spec[j].name;
}
drawtype = NDT_GLASSLIKE;
solidness = 0;
visual_solidness = 1;
} else {
drawtype = NDT_NORMAL;
solidness = 2;
for (TileDef &td : tdef)
td.name += std::string("^[noalpha");
}
if (waving >= 1)
material_type = TILE_MATERIAL_WAVING_LEAVES;
break;
case NDT_PLANTLIKE:
solidness = 0;
if (waving >= 1)
material_type = TILE_MATERIAL_WAVING_PLANTS;
break;
case NDT_FIRELIKE:
solidness = 0;
break;
case NDT_MESH:
case NDT_NODEBOX:
solidness = 0;
if (waving == 1)
material_type = TILE_MATERIAL_WAVING_PLANTS;
else if (waving == 2)
material_type = TILE_MATERIAL_WAVING_LEAVES;
else if (waving == 3)
material_type = TILE_MATERIAL_WAVING_LIQUID_BASIC;
break;
case NDT_TORCHLIKE:
case NDT_SIGNLIKE:
case NDT_FENCELIKE:
case NDT_RAILLIKE:
solidness = 0;
break;
case NDT_PLANTLIKE_ROOTED:
solidness = 2;
break;
}
if (is_liquid) {
// Vertex alpha is no longer supported, correct if necessary.
correctAlpha(tdef, 6);
correctAlpha(tdef_overlay, 6);
correctAlpha(tdef_spec, CF_SPECIAL_COUNT);
if (waving == 3) {
material_type = (alpha == 255) ? TILE_MATERIAL_WAVING_LIQUID_OPAQUE :
TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT;
} else {
material_type = (alpha == 255) ? TILE_MATERIAL_LIQUID_OPAQUE :
TILE_MATERIAL_LIQUID_TRANSPARENT;
}
}
u32 tile_shader = shdsrc->getShader("nodes_shader", material_type, drawtype);
u8 overlay_material = material_type;
if (overlay_material == TILE_MATERIAL_OPAQUE)
overlay_material = TILE_MATERIAL_BASIC;
else if (overlay_material == TILE_MATERIAL_LIQUID_OPAQUE)
overlay_material = TILE_MATERIAL_LIQUID_TRANSPARENT;
u32 overlay_shader = shdsrc->getShader("nodes_shader", overlay_material, drawtype);
// Tiles (fill in f->tiles[])
for (u16 j = 0; j < 6; j++) {
tiles[j].world_aligned = isWorldAligned(tdef[j].align_style,
tsettings.world_aligned_mode, drawtype);
fillTileAttribs(tsrc, &tiles[j].layers[0], tiles[j], tdef[j],
color, material_type, tile_shader,
tdef[j].backface_culling, tsettings);
if (!tdef_overlay[j].name.empty())
fillTileAttribs(tsrc, &tiles[j].layers[1], tiles[j], tdef_overlay[j],
color, overlay_material, overlay_shader,
tdef[j].backface_culling, tsettings);
}
u8 special_material = material_type;
if (drawtype == NDT_PLANTLIKE_ROOTED) {
if (waving == 1)
special_material = TILE_MATERIAL_WAVING_PLANTS;
else if (waving == 2)
special_material = TILE_MATERIAL_WAVING_LEAVES;
}
u32 special_shader = shdsrc->getShader("nodes_shader", special_material, drawtype);
// Special tiles (fill in f->special_tiles[])
for (u16 j = 0; j < CF_SPECIAL_COUNT; j++)
fillTileAttribs(tsrc, &special_tiles[j].layers[0], special_tiles[j], tdef_spec[j],
color, special_material, special_shader,
tdef_spec[j].backface_culling, tsettings);
if (param_type_2 == CPT2_COLOR ||
param_type_2 == CPT2_COLORED_FACEDIR ||
param_type_2 == CPT2_COLORED_WALLMOUNTED)
palette = tsrc->getPalette(palette_name);
if (drawtype == NDT_MESH && !mesh.empty()) {
// Meshnode drawtype
// Read the mesh and apply scale
mesh_ptr[0] = client->getMesh(mesh);
if (mesh_ptr[0]){
v3f scale = v3f(1.0, 1.0, 1.0) * BS * visual_scale;
scaleMesh(mesh_ptr[0], scale);
recalculateBoundingBox(mesh_ptr[0]);
meshmanip->recalculateNormals(mesh_ptr[0], true, false);
}
}
//Cache 6dfacedir and wallmounted rotated clones of meshes
if (tsettings.enable_mesh_cache && mesh_ptr[0] &&
(param_type_2 == CPT2_FACEDIR
|| param_type_2 == CPT2_COLORED_FACEDIR)) {
for (u16 j = 1; j < 24; j++) {
mesh_ptr[j] = cloneMesh(mesh_ptr[0]);
rotateMeshBy6dFacedir(mesh_ptr[j], j);
recalculateBoundingBox(mesh_ptr[j]);
meshmanip->recalculateNormals(mesh_ptr[j], true, false);
}
} else if (tsettings.enable_mesh_cache && mesh_ptr[0]
&& (param_type_2 == CPT2_WALLMOUNTED ||
param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
static const u8 wm_to_6d[6] = { 20, 0, 16 + 1, 12 + 3, 8, 4 + 2 };
for (u16 j = 1; j < 6; j++) {
mesh_ptr[j] = cloneMesh(mesh_ptr[0]);
rotateMeshBy6dFacedir(mesh_ptr[j], wm_to_6d[j]);
recalculateBoundingBox(mesh_ptr[j]);
meshmanip->recalculateNormals(mesh_ptr[j], true, false);
}
rotateMeshBy6dFacedir(mesh_ptr[0], wm_to_6d[0]);
recalculateBoundingBox(mesh_ptr[0]);
meshmanip->recalculateNormals(mesh_ptr[0], true, false);
}
}
#endif
/*
NodeDefManager
*/
NodeDefManager::NodeDefManager()
{
clear();
}
NodeDefManager::~NodeDefManager()
{
#ifndef SERVER
for (ContentFeatures &f : m_content_features) {
for (auto &j : f.mesh_ptr) {
if (j)
j->drop();
}
}
#endif
}
void NodeDefManager::clear()
{
m_content_features.clear();
m_name_id_mapping.clear();
m_name_id_mapping_with_aliases.clear();
m_group_to_items.clear();
m_next_id = 0;
m_selection_box_union.reset(0,0,0);
m_selection_box_int_union.reset(0,0,0);
resetNodeResolveState();
u32 initial_length = 0;
initial_length = MYMAX(initial_length, CONTENT_UNKNOWN + 1);
initial_length = MYMAX(initial_length, CONTENT_AIR + 1);
initial_length = MYMAX(initial_length, CONTENT_IGNORE + 1);
m_content_features.resize(initial_length);
// Set CONTENT_UNKNOWN
{
ContentFeatures f;
f.name = "unknown";
// Insert directly into containers
content_t c = CONTENT_UNKNOWN;
m_content_features[c] = f;
addNameIdMapping(c, f.name);
}
// Set CONTENT_AIR
{
ContentFeatures f;
f.name = "air";
f.drawtype = NDT_AIRLIKE;
f.param_type = CPT_LIGHT;
f.light_propagates = true;
f.sunlight_propagates = true;
f.walkable = false;
f.pointable = false;
f.diggable = false;
f.buildable_to = true;
f.floodable = true;
f.is_ground_content = true;
// Insert directly into containers
content_t c = CONTENT_AIR;
m_content_features[c] = f;
addNameIdMapping(c, f.name);
}
// Set CONTENT_IGNORE
{
ContentFeatures f;
f.name = "ignore";
f.drawtype = NDT_AIRLIKE;
f.param_type = CPT_NONE;
f.light_propagates = false;
f.sunlight_propagates = false;
f.walkable = false;
f.pointable = false;
f.diggable = false;
f.buildable_to = true; // A way to remove accidental CONTENT_IGNOREs
f.is_ground_content = true;
// Insert directly into containers
content_t c = CONTENT_IGNORE;
m_content_features[c] = f;
addNameIdMapping(c, f.name);
}
}
bool NodeDefManager::getId(const std::string &name, content_t &result) const
{
std::unordered_map<std::string, content_t>::const_iterator
i = m_name_id_mapping_with_aliases.find(name);
if(i == m_name_id_mapping_with_aliases.end())
return false;
result = i->second;
return true;
}
content_t NodeDefManager::getId(const std::string &name) const
{
content_t id = CONTENT_IGNORE;
getId(name, id);
return id;
}
bool NodeDefManager::getIds(const std::string &name,
std::vector<content_t> &result) const
{
//TimeTaker t("getIds", NULL, PRECISION_MICRO);
if (name.substr(0,6) != "group:") {
content_t id = CONTENT_IGNORE;
bool exists = getId(name, id);
if (exists)
result.push_back(id);
return exists;
}
std::string group = name.substr(6);
std::unordered_map<std::string, std::vector<content_t>>::const_iterator
i = m_group_to_items.find(group);
if (i == m_group_to_items.end())
return true;
const std::vector<content_t> &items = i->second;
result.insert(result.end(), items.begin(), items.end());
//printf("getIds: %dus\n", t.stop());
return true;
}
const ContentFeatures& NodeDefManager::get(const std::string &name) const
{
content_t id = CONTENT_UNKNOWN;
getId(name, id);
return get(id);
}
// returns CONTENT_IGNORE if no free ID found
content_t NodeDefManager::allocateId()
{
for (content_t id = m_next_id;
id >= m_next_id; // overflow?
++id) {
while (id >= m_content_features.size()) {
m_content_features.emplace_back();
}
const ContentFeatures &f = m_content_features[id];
if (f.name.empty()) {
m_next_id = id + 1;
return id;
}
}
// If we arrive here, an overflow occurred in id.
// That means no ID was found
return CONTENT_IGNORE;
}
/*!
* Returns the smallest box that contains all boxes
* in the vector. Box_union is expanded.
* @param[in] boxes the vector containing the boxes
* @param[in, out] box_union the union of the arguments
*/
void boxVectorUnion(const std::vector<aabb3f> &boxes, aabb3f *box_union)
{
for (const aabb3f &box : boxes) {
box_union->addInternalBox(box);
}
}
/*!
* Returns a box that contains the nodebox in every case.
* The argument node_union is expanded.
* @param[in] nodebox the nodebox to be measured
* @param[in] features used to decide whether the nodebox
* can be rotated
* @param[in, out] box_union the union of the arguments
*/
void getNodeBoxUnion(const NodeBox &nodebox, const ContentFeatures &features,
aabb3f *box_union)
{
switch(nodebox.type) {
case NODEBOX_FIXED:
case NODEBOX_LEVELED: {
// Raw union
aabb3f half_processed(0, 0, 0, 0, 0, 0);
boxVectorUnion(nodebox.fixed, &half_processed);
// Set leveled boxes to maximal
if (nodebox.type == NODEBOX_LEVELED) {
half_processed.MaxEdge.Y = +BS / 2;
}
if (features.param_type_2 == CPT2_FACEDIR ||
features.param_type_2 == CPT2_COLORED_FACEDIR) {
// Get maximal coordinate
f32 coords[] = {
fabsf(half_processed.MinEdge.X),
fabsf(half_processed.MinEdge.Y),
fabsf(half_processed.MinEdge.Z),
fabsf(half_processed.MaxEdge.X),
fabsf(half_processed.MaxEdge.Y),
fabsf(half_processed.MaxEdge.Z) };
f32 max = 0;
for (float coord : coords) {
if (max < coord) {
max = coord;
}
}
// Add the union of all possible rotated boxes
box_union->addInternalPoint(-max, -max, -max);
box_union->addInternalPoint(+max, +max, +max);
} else {
box_union->addInternalBox(half_processed);
}
break;
}
case NODEBOX_WALLMOUNTED: {
// Add fix boxes
box_union->addInternalBox(nodebox.wall_top);
box_union->addInternalBox(nodebox.wall_bottom);
// Find maximal coordinate in the X-Z plane
f32 coords[] = {
fabsf(nodebox.wall_side.MinEdge.X),
fabsf(nodebox.wall_side.MinEdge.Z),
fabsf(nodebox.wall_side.MaxEdge.X),
fabsf(nodebox.wall_side.MaxEdge.Z) };
f32 max = 0;
for (float coord : coords) {
if (max < coord) {
max = coord;
}
}
// Add the union of all possible rotated boxes
box_union->addInternalPoint(-max, nodebox.wall_side.MinEdge.Y, -max);
box_union->addInternalPoint(max, nodebox.wall_side.MaxEdge.Y, max);
break;
}
case NODEBOX_CONNECTED: {
// Add all possible connected boxes
boxVectorUnion(nodebox.fixed, box_union);
boxVectorUnion(nodebox.connect_top, box_union);
boxVectorUnion(nodebox.connect_bottom, box_union);
boxVectorUnion(nodebox.connect_front, box_union);
boxVectorUnion(nodebox.connect_left, box_union);
boxVectorUnion(nodebox.connect_back, box_union);
boxVectorUnion(nodebox.connect_right, box_union);
boxVectorUnion(nodebox.disconnected_top, box_union);
boxVectorUnion(nodebox.disconnected_bottom, box_union);
boxVectorUnion(nodebox.disconnected_front, box_union);
boxVectorUnion(nodebox.disconnected_left, box_union);
boxVectorUnion(nodebox.disconnected_back, box_union);
boxVectorUnion(nodebox.disconnected_right, box_union);
boxVectorUnion(nodebox.disconnected, box_union);
boxVectorUnion(nodebox.disconnected_sides, box_union);
break;
}
default: {
// NODEBOX_REGULAR
box_union->addInternalPoint(-BS / 2, -BS / 2, -BS / 2);
box_union->addInternalPoint(+BS / 2, +BS / 2, +BS / 2);
}
}
}
inline void NodeDefManager::fixSelectionBoxIntUnion()
{
m_selection_box_int_union.MinEdge.X = floorf(
m_selection_box_union.MinEdge.X / BS + 0.5f);
m_selection_box_int_union.MinEdge.Y = floorf(
m_selection_box_union.MinEdge.Y / BS + 0.5f);
m_selection_box_int_union.MinEdge.Z = floorf(
m_selection_box_union.MinEdge.Z / BS + 0.5f);
m_selection_box_int_union.MaxEdge.X = ceilf(
m_selection_box_union.MaxEdge.X / BS - 0.5f);
m_selection_box_int_union.MaxEdge.Y = ceilf(
m_selection_box_union.MaxEdge.Y / BS - 0.5f);
m_selection_box_int_union.MaxEdge.Z = ceilf(
m_selection_box_union.MaxEdge.Z / BS - 0.5f);
}
// IWritableNodeDefManager
content_t NodeDefManager::set(const std::string &name, const ContentFeatures &def)
{
// Pre-conditions
assert(name != "");
assert(name != "ignore");
assert(name == def.name);
content_t id = CONTENT_IGNORE;
if (!m_name_id_mapping.getId(name, id)) { // ignore aliases
// Get new id
id = allocateId();
if (id == CONTENT_IGNORE) {
warningstream << "NodeDefManager: Absolute "
"limit reached" << std::endl;
return CONTENT_IGNORE;
}
assert(id != CONTENT_IGNORE);
addNameIdMapping(id, name);
}
m_content_features[id] = def;
verbosestream << "NodeDefManager: registering content id \"" << id
<< "\": name=\"" << def.name << "\""<<std::endl;
getNodeBoxUnion(def.selection_box, def, &m_selection_box_union);
fixSelectionBoxIntUnion();
// Add this content to the list of all groups it belongs to
// FIXME: This should remove a node from groups it no longer
// belongs to when a node is re-registered
for (const auto &group : def.groups) {
const std::string &group_name = group.first;
m_group_to_items[group_name].push_back(id);
}
return id;
}
content_t NodeDefManager::allocateDummy(const std::string &name)
{
assert(name != ""); // Pre-condition
ContentFeatures f;
f.name = name;
return set(name, f);
}
void NodeDefManager::removeNode(const std::string &name)
{
// Pre-condition
assert(name != "");
// Erase name from name ID mapping
content_t id = CONTENT_IGNORE;
if (m_name_id_mapping.getId(name, id)) {
m_name_id_mapping.eraseName(name);
m_name_id_mapping_with_aliases.erase(name);
}
// Erase node content from all groups it belongs to
for (std::unordered_map<std::string, std::vector<content_t>>::iterator iter_groups =
m_group_to_items.begin(); iter_groups != m_group_to_items.end();) {
std::vector<content_t> &items = iter_groups->second;
items.erase(std::remove(items.begin(), items.end(), id), items.end());
// Check if group is empty
if (items.empty())
m_group_to_items.erase(iter_groups++);
else
++iter_groups;
}
}
void NodeDefManager::updateAliases(IItemDefManager *idef)
{
std::set<std::string> all;
idef->getAll(all);
m_name_id_mapping_with_aliases.clear();
for (const std::string &name : all) {
const std::string &convert_to = idef->getAlias(name);
content_t id;
if (m_name_id_mapping.getId(convert_to, id)) {
m_name_id_mapping_with_aliases.insert(
std::make_pair(name, id));
}
}
}
void NodeDefManager::applyTextureOverrides(const std::string &override_filepath)
{
infostream << "NodeDefManager::applyTextureOverrides(): Applying "
"overrides to textures from " << override_filepath << std::endl;
std::ifstream infile(override_filepath.c_str());
std::string line;
int line_c = 0;
while (std::getline(infile, line)) {
line_c++;
if (trim(line).empty())
continue;
std::vector<std::string> splitted = str_split(line, ' ');
if (splitted.size() != 3) {
errorstream << override_filepath
<< ":" << line_c << " Could not apply texture override \""
<< line << "\": Syntax error" << std::endl;
continue;
}
content_t id;
if (!getId(splitted[0], id))
continue; // Ignore unknown node
ContentFeatures &nodedef = m_content_features[id];
if (splitted[1] == "top")
nodedef.tiledef[0].name = splitted[2];
else if (splitted[1] == "bottom")
nodedef.tiledef[1].name = splitted[2];
else if (splitted[1] == "right")
nodedef.tiledef[2].name = splitted[2];
else if (splitted[1] == "left")
nodedef.tiledef[3].name = splitted[2];
else if (splitted[1] == "back")
nodedef.tiledef[4].name = splitted[2];
else if (splitted[1] == "front")
nodedef.tiledef[5].name = splitted[2];
else if (splitted[1] == "all" || splitted[1] == "*")
for (TileDef &i : nodedef.tiledef)
i.name = splitted[2];
else if (splitted[1] == "sides")
for (int i = 2; i < 6; i++)
nodedef.tiledef[i].name = splitted[2];
else {
errorstream << override_filepath
<< ":" << line_c << " Could not apply texture override \""
<< line << "\": Unknown node side \""
<< splitted[1] << "\"" << std::endl;
continue;
}
}
}
void NodeDefManager::updateTextures(IGameDef *gamedef,
void (*progress_callback)(void *progress_args, u32 progress, u32 max_progress),
void *progress_callback_args)
{
#ifndef SERVER
infostream << "NodeDefManager::updateTextures(): Updating "
"textures in node definitions" << std::endl;
Client *client = (Client *)gamedef;
ITextureSource *tsrc = client->tsrc();
IShaderSource *shdsrc = client->getShaderSource();
scene::IMeshManipulator *meshmanip =
RenderingEngine::get_scene_manager()->getMeshManipulator();
TextureSettings tsettings;
tsettings.readSettings();
u32 size = m_content_features.size();
for (u32 i = 0; i < size; i++) {
ContentFeatures *f = &(m_content_features[i]);
f->updateTextures(tsrc, shdsrc, meshmanip, client, tsettings);
progress_callback(progress_callback_args, i, size);
}
#endif
}
void NodeDefManager::serialize(std::ostream &os, u16 protocol_version) const
{
writeU8(os, 1); // version
u16 count = 0;
std::ostringstream os2(std::ios::binary);
for (u32 i = 0; i < m_content_features.size(); i++) {
if (i == CONTENT_IGNORE || i == CONTENT_AIR
|| i == CONTENT_UNKNOWN)
continue;
const ContentFeatures *f = &m_content_features[i];
if (f->name.empty())
continue;
writeU16(os2, i);
// Wrap it in a string to allow different lengths without
// strict version incompatibilities
std::ostringstream wrapper_os(std::ios::binary);
f->serialize(wrapper_os, protocol_version);
os2<<serializeString(wrapper_os.str());
// must not overflow
u16 next = count + 1;
FATAL_ERROR_IF(next < count, "Overflow");
count++;
}
writeU16(os, count);
os << serializeLongString(os2.str());
}
void NodeDefManager::deSerialize(std::istream &is)
{
clear();
int version = readU8(is);
if (version != 1)
throw SerializationError("unsupported NodeDefinitionManager version");
u16 count = readU16(is);
std::istringstream is2(deSerializeLongString(is), std::ios::binary);
ContentFeatures f;
for (u16 n = 0; n < count; n++) {
u16 i = readU16(is2);
// Read it from the string wrapper
std::string wrapper = deSerializeString(is2);
std::istringstream wrapper_is(wrapper, std::ios::binary);
f.deSerialize(wrapper_is);
// Check error conditions
if (i == CONTENT_IGNORE || i == CONTENT_AIR || i == CONTENT_UNKNOWN) {
warningstream << "NodeDefManager::deSerialize(): "
"not changing builtin node " << i << std::endl;
continue;
}
if (f.name.empty()) {
warningstream << "NodeDefManager::deSerialize(): "
"received empty name" << std::endl;
continue;
}
// Ignore aliases
u16 existing_id;
if (m_name_id_mapping.getId(f.name, existing_id) && i != existing_id) {
warningstream << "NodeDefManager::deSerialize(): "
"already defined with different ID: " << f.name << std::endl;
continue;
}
// All is ok, add node definition with the requested ID
if (i >= m_content_features.size())
m_content_features.resize((u32)(i) + 1);
m_content_features[i] = f;
addNameIdMapping(i, f.name);
verbosestream << "deserialized " << f.name << std::endl;
getNodeBoxUnion(f.selection_box, f, &m_selection_box_union);
fixSelectionBoxIntUnion();
}
}
void NodeDefManager::addNameIdMapping(content_t i, std::string name)
{
m_name_id_mapping.set(i, name);
m_name_id_mapping_with_aliases.insert(std::make_pair(name, i));
}
NodeDefManager *createNodeDefManager()
{
return new NodeDefManager();
}
void NodeDefManager::pendNodeResolve(NodeResolver *nr) const
{
nr->m_ndef = this;
if (m_node_registration_complete)
nr->nodeResolveInternal();
else
m_pending_resolve_callbacks.push_back(nr);
}
bool NodeDefManager::cancelNodeResolveCallback(NodeResolver *nr) const
{
size_t len = m_pending_resolve_callbacks.size();
for (size_t i = 0; i != len; i++) {
if (nr != m_pending_resolve_callbacks[i])
continue;
len--;
m_pending_resolve_callbacks[i] = m_pending_resolve_callbacks[len];
m_pending_resolve_callbacks.resize(len);
return true;
}
return false;
}
void NodeDefManager::runNodeResolveCallbacks()
{
for (size_t i = 0; i != m_pending_resolve_callbacks.size(); i++) {
NodeResolver *nr = m_pending_resolve_callbacks[i];
nr->nodeResolveInternal();
}
m_pending_resolve_callbacks.clear();
}
void NodeDefManager::resetNodeResolveState()
{
m_node_registration_complete = false;
m_pending_resolve_callbacks.clear();
}
void NodeDefManager::mapNodeboxConnections()
{
for (ContentFeatures &f : m_content_features) {
if (f.drawtype != NDT_NODEBOX || f.node_box.type != NODEBOX_CONNECTED)
continue;
for (const std::string &name : f.connects_to) {
getIds(name, f.connects_to_ids);
}
}
}
bool NodeDefManager::nodeboxConnects(MapNode from, MapNode to,
u8 connect_face) const
{
const ContentFeatures &f1 = get(from);
if ((f1.drawtype != NDT_NODEBOX) || (f1.node_box.type != NODEBOX_CONNECTED))
return false;
// lookup target in connected set
if (!CONTAINS(f1.connects_to_ids, to.param0))
return false;
const ContentFeatures &f2 = get(to);
if ((f2.drawtype == NDT_NODEBOX) && (f2.node_box.type == NODEBOX_CONNECTED))
// ignores actually looking if back connection exists
return CONTAINS(f2.connects_to_ids, from.param0);
// does to node declare usable faces?
if (f2.connect_sides > 0) {
if ((f2.param_type_2 == CPT2_FACEDIR ||
f2.param_type_2 == CPT2_COLORED_FACEDIR)
&& (connect_face >= 4)) {
static const u8 rot[33 * 4] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 4, 32, 16, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, // 4 - back
8, 4, 32, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, // 8 - right
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 8, 4, 32, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, // 16 - front
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 32, 16, 8, 4 // 32 - left
};
return (f2.connect_sides
& rot[(connect_face * 4) + (to.param2 & 0x1F)]);
}
return (f2.connect_sides & connect_face);
}
// the target is just a regular node, so connect no matter back connection
return true;
}
////
//// NodeResolver
////
NodeResolver::NodeResolver()
{
m_nodenames.reserve(16);
m_nnlistsizes.reserve(4);
}
NodeResolver::~NodeResolver()
{
if (!m_resolve_done && m_ndef)
m_ndef->cancelNodeResolveCallback(this);
}
void NodeResolver::nodeResolveInternal()
{
m_nodenames_idx = 0;
m_nnlistsizes_idx = 0;
resolveNodeNames();
m_resolve_done = true;
m_nodenames.clear();
m_nnlistsizes.clear();
}
bool NodeResolver::getIdFromNrBacklog(content_t *result_out,
const std::string &node_alt, content_t c_fallback, bool error_on_fallback)
{
if (m_nodenames_idx == m_nodenames.size()) {
*result_out = c_fallback;
errorstream << "NodeResolver: no more nodes in list" << std::endl;
return false;
}
content_t c;
std::string name = m_nodenames[m_nodenames_idx++];
bool success = m_ndef->getId(name, c);
if (!success && !node_alt.empty()) {
name = node_alt;
success = m_ndef->getId(name, c);
}
if (!success) {
if (error_on_fallback)
errorstream << "NodeResolver: failed to resolve node name '" << name
<< "'." << std::endl;
c = c_fallback;
}
*result_out = c;
return success;
}
bool NodeResolver::getIdsFromNrBacklog(std::vector<content_t> *result_out,
bool all_required, content_t c_fallback)
{
bool success = true;
if (m_nnlistsizes_idx == m_nnlistsizes.size()) {
errorstream << "NodeResolver: no more node lists" << std::endl;
return false;
}
size_t length = m_nnlistsizes[m_nnlistsizes_idx++];
while (length--) {
if (m_nodenames_idx == m_nodenames.size()) {
errorstream << "NodeResolver: no more nodes in list" << std::endl;
return false;
}
content_t c;
std::string &name = m_nodenames[m_nodenames_idx++];
if (name.substr(0,6) != "group:") {
if (m_ndef->getId(name, c)) {
result_out->push_back(c);
} else if (all_required) {
errorstream << "NodeResolver: failed to resolve node name '"
<< name << "'." << std::endl;
result_out->push_back(c_fallback);
success = false;
}
} else {
m_ndef->getIds(name, *result_out);
}
}
return success;
}
| pgimeno/minetest | src/nodedef.cpp | C++ | mit | 45,661 |
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "irrlichttypes_bloated.h"
#include <string>
#include <iostream>
#include <map>
#include "mapnode.h"
#include "nameidmapping.h"
#ifndef SERVER
#include "client/tile.h"
#include <IMeshManipulator.h>
class Client;
#endif
#include "itemgroup.h"
#include "sound.h" // SimpleSoundSpec
#include "constants.h" // BS
#include "tileanimation.h"
// PROTOCOL_VERSION >= 37
static const u8 CONTENTFEATURES_VERSION = 13;
class IItemDefManager;
class ITextureSource;
class IShaderSource;
class IGameDef;
class NodeResolver;
enum ContentParamType
{
CPT_NONE,
CPT_LIGHT,
};
enum ContentParamType2
{
CPT2_NONE,
// Need 8-bit param2
CPT2_FULL,
// Flowing liquid properties
CPT2_FLOWINGLIQUID,
// Direction for chests and furnaces and such
CPT2_FACEDIR,
// Direction for signs, torches and such
CPT2_WALLMOUNTED,
// Block level like FLOWINGLIQUID
CPT2_LEVELED,
// 2D rotation for things like plants
CPT2_DEGROTATE,
// Mesh options for plants
CPT2_MESHOPTIONS,
// Index for palette
CPT2_COLOR,
// 3 bits of palette index, then facedir
CPT2_COLORED_FACEDIR,
// 5 bits of palette index, then wallmounted
CPT2_COLORED_WALLMOUNTED,
// Glasslike framed drawtype internal liquid level, param2 values 0 to 63
CPT2_GLASSLIKE_LIQUID_LEVEL,
};
enum LiquidType
{
LIQUID_NONE,
LIQUID_FLOWING,
LIQUID_SOURCE,
};
enum NodeBoxType
{
NODEBOX_REGULAR, // Regular block; allows buildable_to
NODEBOX_FIXED, // Static separately defined box(es)
NODEBOX_WALLMOUNTED, // Box for wall mounted nodes; (top, bottom, side)
NODEBOX_LEVELED, // Same as fixed, but with dynamic height from param2. for snow, ...
NODEBOX_CONNECTED, // optionally draws nodeboxes if a neighbor node attaches
};
struct NodeBox
{
enum NodeBoxType type;
// NODEBOX_REGULAR (no parameters)
// NODEBOX_FIXED
std::vector<aabb3f> fixed;
// NODEBOX_WALLMOUNTED
aabb3f wall_top;
aabb3f wall_bottom;
aabb3f wall_side; // being at the -X side
// NODEBOX_CONNECTED
std::vector<aabb3f> connect_top;
std::vector<aabb3f> connect_bottom;
std::vector<aabb3f> connect_front;
std::vector<aabb3f> connect_left;
std::vector<aabb3f> connect_back;
std::vector<aabb3f> connect_right;
std::vector<aabb3f> disconnected_top;
std::vector<aabb3f> disconnected_bottom;
std::vector<aabb3f> disconnected_front;
std::vector<aabb3f> disconnected_left;
std::vector<aabb3f> disconnected_back;
std::vector<aabb3f> disconnected_right;
std::vector<aabb3f> disconnected;
std::vector<aabb3f> disconnected_sides;
NodeBox()
{ reset(); }
void reset();
void serialize(std::ostream &os, u16 protocol_version) const;
void deSerialize(std::istream &is);
};
struct MapNode;
class NodeMetadata;
enum LeavesStyle {
LEAVES_FANCY,
LEAVES_SIMPLE,
LEAVES_OPAQUE,
};
enum AutoScale : u8 {
AUTOSCALE_DISABLE,
AUTOSCALE_ENABLE,
AUTOSCALE_FORCE,
};
enum WorldAlignMode : u8 {
WORLDALIGN_DISABLE,
WORLDALIGN_ENABLE,
WORLDALIGN_FORCE,
WORLDALIGN_FORCE_NODEBOX,
};
class TextureSettings {
public:
LeavesStyle leaves_style;
WorldAlignMode world_aligned_mode;
AutoScale autoscale_mode;
int node_texture_size;
bool opaque_water;
bool connected_glass;
bool use_normal_texture;
bool enable_mesh_cache;
bool enable_minimap;
TextureSettings() = default;
void readSettings();
};
enum NodeDrawType
{
// A basic solid block
NDT_NORMAL,
// Nothing is drawn
NDT_AIRLIKE,
// Do not draw face towards same kind of flowing/source liquid
NDT_LIQUID,
// A very special kind of thing
NDT_FLOWINGLIQUID,
// Glass-like, don't draw faces towards other glass
NDT_GLASSLIKE,
// Leaves-like, draw all faces no matter what
NDT_ALLFACES,
// Enabled -> ndt_allfaces, disabled -> ndt_normal
NDT_ALLFACES_OPTIONAL,
// Single plane perpendicular to a surface
NDT_TORCHLIKE,
// Single plane parallel to a surface
NDT_SIGNLIKE,
// 2 vertical planes in a 'X' shape diagonal to XZ axes.
// paramtype2 = "meshoptions" allows various forms, sizes and
// vertical and horizontal random offsets.
NDT_PLANTLIKE,
// Fenceposts that connect to neighbouring fenceposts with horizontal bars
NDT_FENCELIKE,
// Selects appropriate junction texture to connect like rails to
// neighbouring raillikes.
NDT_RAILLIKE,
// Custom Lua-definable structure of multiple cuboids
NDT_NODEBOX,
// Glass-like, draw connected frames and all visible faces.
// param2 > 0 defines 64 levels of internal liquid
// Uses 3 textures, one for frames, second for faces,
// optional third is a 'special tile' for the liquid.
NDT_GLASSLIKE_FRAMED,
// Draw faces slightly rotated and only on neighbouring nodes
NDT_FIRELIKE,
// Enabled -> ndt_glasslike_framed, disabled -> ndt_glasslike
NDT_GLASSLIKE_FRAMED_OPTIONAL,
// Uses static meshes
NDT_MESH,
// Combined plantlike-on-solid
NDT_PLANTLIKE_ROOTED,
};
// Mesh options for NDT_PLANTLIKE with CPT2_MESHOPTIONS
static const u8 MO_MASK_STYLE = 0x07;
static const u8 MO_BIT_RANDOM_OFFSET = 0x08;
static const u8 MO_BIT_SCALE_SQRT2 = 0x10;
static const u8 MO_BIT_RANDOM_OFFSET_Y = 0x20;
enum PlantlikeStyle {
PLANT_STYLE_CROSS,
PLANT_STYLE_CROSS2,
PLANT_STYLE_STAR,
PLANT_STYLE_HASH,
PLANT_STYLE_HASH2,
};
enum AlignStyle : u8 {
ALIGN_STYLE_NODE,
ALIGN_STYLE_WORLD,
ALIGN_STYLE_USER_DEFINED,
};
/*
Stand-alone definition of a TileSpec (basically a server-side TileSpec)
*/
struct TileDef
{
std::string name = "";
bool backface_culling = true; // Takes effect only in special cases
bool tileable_horizontal = true;
bool tileable_vertical = true;
//! If true, the tile has its own color.
bool has_color = false;
//! The color of the tile.
video::SColor color = video::SColor(0xFFFFFFFF);
AlignStyle align_style = ALIGN_STYLE_NODE;
u8 scale = 0;
struct TileAnimationParams animation;
TileDef()
{
animation.type = TAT_NONE;
}
void serialize(std::ostream &os, u16 protocol_version) const;
void deSerialize(std::istream &is, u8 contentfeatures_version,
NodeDrawType drawtype);
};
#define CF_SPECIAL_COUNT 6
struct ContentFeatures
{
/*
Cached stuff
*/
#ifndef SERVER
// 0 1 2 3 4 5
// up down right left back front
TileSpec tiles[6];
// Special tiles
// - Currently used for flowing liquids
TileSpec special_tiles[CF_SPECIAL_COUNT];
u8 solidness; // Used when choosing which face is drawn
u8 visual_solidness; // When solidness=0, this tells how it looks like
bool backface_culling;
#endif
// Server-side cached callback existence for fast skipping
bool has_on_construct;
bool has_on_destruct;
bool has_after_destruct;
/*
Actual data
*/
// --- GENERAL PROPERTIES ---
std::string name; // "" = undefined node
ItemGroupList groups; // Same as in itemdef
// Type of MapNode::param1
ContentParamType param_type;
// Type of MapNode::param2
ContentParamType2 param_type_2;
// --- VISUAL PROPERTIES ---
enum NodeDrawType drawtype;
std::string mesh;
#ifndef SERVER
scene::IMesh *mesh_ptr[24];
video::SColor minimap_color;
#endif
float visual_scale; // Misc. scale parameter
TileDef tiledef[6];
// These will be drawn over the base tiles.
TileDef tiledef_overlay[6];
TileDef tiledef_special[CF_SPECIAL_COUNT]; // eg. flowing liquid
// If 255, the node is opaque.
// Otherwise it uses texture alpha.
u8 alpha;
// The color of the node.
video::SColor color;
std::string palette_name;
std::vector<video::SColor> *palette;
// Used for waving leaves/plants
u8 waving;
// for NDT_CONNECTED pairing
u8 connect_sides;
std::vector<std::string> connects_to;
std::vector<content_t> connects_to_ids;
// Post effect color, drawn when the camera is inside the node.
video::SColor post_effect_color;
// Flowing liquid or snow, value = default level
u8 leveled;
// --- LIGHTING-RELATED ---
bool light_propagates;
bool sunlight_propagates;
// Amount of light the node emits
u8 light_source;
// --- MAP GENERATION ---
// True for all ground-like things like stone and mud, false for eg. trees
bool is_ground_content;
// --- INTERACTION PROPERTIES ---
// This is used for collision detection.
// Also for general solidness queries.
bool walkable;
// Player can point to these
bool pointable;
// Player can dig these
bool diggable;
// Player can climb these
bool climbable;
// Player can build on these
bool buildable_to;
// Player cannot build to these (placement prediction disabled)
bool rightclickable;
u32 damage_per_second;
// client dig prediction
std::string node_dig_prediction;
// --- LIQUID PROPERTIES ---
// Whether the node is non-liquid, source liquid or flowing liquid
enum LiquidType liquid_type;
// If the content is liquid, this is the flowing version of the liquid.
std::string liquid_alternative_flowing;
// If the content is liquid, this is the source version of the liquid.
std::string liquid_alternative_source;
// Viscosity for fluid flow, ranging from 1 to 7, with
// 1 giving almost instantaneous propagation and 7 being
// the slowest possible
u8 liquid_viscosity;
// Is liquid renewable (new liquid source will be created between 2 existing)
bool liquid_renewable;
// Number of flowing liquids surrounding source
u8 liquid_range;
u8 drowning;
// Liquids flow into and replace node
bool floodable;
// --- NODEBOXES ---
NodeBox node_box;
NodeBox selection_box;
NodeBox collision_box;
// --- SOUND PROPERTIES ---
SimpleSoundSpec sound_footstep;
SimpleSoundSpec sound_dig;
SimpleSoundSpec sound_dug;
// --- LEGACY ---
// Compatibility with old maps
// Set to true if paramtype used to be 'facedir_simple'
bool legacy_facedir_simple;
// Set to true if wall_mounted used to be set to true
bool legacy_wallmounted;
/*
Methods
*/
ContentFeatures();
~ContentFeatures() = default;
void reset();
void serialize(std::ostream &os, u16 protocol_version) const;
void deSerialize(std::istream &is);
/*!
* Since vertex alpha is no longer supported, this method
* adds opacity directly to the texture pixels.
*
* \param tiles array of the tile definitions.
* \param length length of tiles
*/
void correctAlpha(TileDef *tiles, int length);
/*
Some handy methods
*/
bool isLiquid() const{
return (liquid_type != LIQUID_NONE);
}
bool sameLiquid(const ContentFeatures &f) const{
if(!isLiquid() || !f.isLiquid()) return false;
return (liquid_alternative_flowing == f.liquid_alternative_flowing);
}
int getGroup(const std::string &group) const
{
return itemgroup_get(groups, group);
}
#ifndef SERVER
void updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc,
scene::IMeshManipulator *meshmanip, Client *client, const TextureSettings &tsettings);
#endif
};
/*!
* @brief This class is for getting the actual properties of nodes from their
* content ID.
*
* @details The nodes on the map are represented by three numbers (see MapNode).
* The first number (param0) is the type of a node. All node types have own
* properties (see ContentFeatures). This class is for storing and getting the
* properties of nodes.
* The manager is first filled with registered nodes, then as the game begins,
* functions only get `const` pointers to it, to prevent modification of
* registered nodes.
*/
class NodeDefManager {
public:
/*!
* Creates a NodeDefManager, and registers three ContentFeatures:
* \ref CONTENT_AIR, \ref CONTENT_UNKNOWN and \ref CONTENT_IGNORE.
*/
NodeDefManager();
~NodeDefManager();
/*!
* Returns the properties for the given content type.
* @param c content type of a node
* @return properties of the given content type, or \ref CONTENT_UNKNOWN
* if the given content type is not registered.
*/
inline const ContentFeatures& get(content_t c) const {
return
c < m_content_features.size() ?
m_content_features[c] : m_content_features[CONTENT_UNKNOWN];
}
/*!
* Returns the properties of the given node.
* @param n a map node
* @return properties of the given node or @ref CONTENT_UNKNOWN if the
* given content type is not registered.
*/
inline const ContentFeatures& get(const MapNode &n) const {
return get(n.getContent());
}
/*!
* Returns the node properties for a node name.
* @param name name of a node
* @return properties of the given node or @ref CONTENT_UNKNOWN if
* not found
*/
const ContentFeatures& get(const std::string &name) const;
/*!
* Returns the content ID for the given name.
* @param name a node name
* @param[out] result will contain the content ID if found, otherwise
* remains unchanged
* @return true if the ID was found, false otherwise
*/
bool getId(const std::string &name, content_t &result) const;
/*!
* Returns the content ID for the given name.
* @param name a node name
* @return ID of the node or @ref CONTENT_IGNORE if not found
*/
content_t getId(const std::string &name) const;
/*!
* Returns the content IDs of the given node name or node group name.
* Group names start with "group:".
* @param name a node name or node group name
* @param[out] result will be appended with matching IDs
* @return true if `name` is a valid node name or a (not necessarily
* valid) group name
*/
bool getIds(const std::string &name, std::vector<content_t> &result) const;
/*!
* Returns the smallest box in integer node coordinates that
* contains all nodes' selection boxes. The returned box might be larger
* than the minimal size if the largest node is removed from the manager.
*/
inline core::aabbox3d<s16> getSelectionBoxIntUnion() const {
return m_selection_box_int_union;
}
/*!
* Checks whether a node connects to an adjacent node.
* @param from the node to be checked
* @param to the adjacent node
* @param connect_face a bit field indicating which face of the node is
* adjacent to the other node.
* Bits: +y (least significant), -y, -z, -x, +z, +x (most significant).
* @return true if the node connects, false otherwise
*/
bool nodeboxConnects(MapNode from, MapNode to,
u8 connect_face) const;
/*!
* Registers a NodeResolver to wait for the registration of
* ContentFeatures. Once the node registration finishes, all
* listeners are notified.
*/
void pendNodeResolve(NodeResolver *nr) const;
/*!
* Stops listening to the NodeDefManager.
* @return true if the listener was registered before, false otherwise
*/
bool cancelNodeResolveCallback(NodeResolver *nr) const;
/*!
* Registers a new node type with the given name and allocates a new
* content ID.
* Should not be called with an already existing name.
* @param name name of the node, must match with `def.name`.
* @param def definition of the registered node type.
* @return ID of the registered node or @ref CONTENT_IGNORE if
* the function could not allocate an ID.
*/
content_t set(const std::string &name, const ContentFeatures &def);
/*!
* Allocates a blank node ID for the given name.
* @param name name of a node
* @return allocated ID or @ref CONTENT_IGNORE if could not allocate
* an ID.
*/
content_t allocateDummy(const std::string &name);
/*!
* Removes the given node name from the manager.
* The node ID will remain in the manager, but won't be linked to any name.
* @param name name to be removed
*/
void removeNode(const std::string &name);
/*!
* Regenerates the alias list (a map from names to node IDs).
* @param idef the item definition manager containing alias information
*/
void updateAliases(IItemDefManager *idef);
/*!
* Reads the used texture pack's override.txt, and replaces the textures
* of registered nodes with the ones specified there.
*
* Format of the input file: in each line
* `node_name top|bottom|right|left|front|back|all|*|sides texture_name.png`
*
* @param override_filepath path to 'texturepack/override.txt'
*/
void applyTextureOverrides(const std::string &override_filepath);
/*!
* Only the client uses this. Loads textures and shaders required for
* rendering the nodes.
* @param gamedef must be a Client.
* @param progress_cbk called each time a node is loaded. Arguments:
* `progress_cbk_args`, number of loaded ContentFeatures, number of
* total ContentFeatures.
* @param progress_cbk_args passed to the callback function
*/
void updateTextures(IGameDef *gamedef,
void (*progress_cbk)(void *progress_args, u32 progress, u32 max_progress),
void *progress_cbk_args);
/*!
* Writes the content of this manager to the given output stream.
* @param protocol_version serialization version of ContentFeatures
*/
void serialize(std::ostream &os, u16 protocol_version) const;
/*!
* Restores the manager from a serialized stream.
* This clears the previous state.
* @param is input stream containing a serialized NodeDefManager
*/
void deSerialize(std::istream &is);
/*!
* Used to indicate that node registration has finished.
* @param completed tells whether registration is complete
*/
inline void setNodeRegistrationStatus(bool completed) {
m_node_registration_complete = completed;
}
/*!
* Notifies the registered NodeResolver instances that node registration
* has finished, then unregisters all listeners.
* Must be called after node registration has finished!
*/
void runNodeResolveCallbacks();
/*!
* Sets the registration completion flag to false and unregisters all
* NodeResolver instances listening to the manager.
*/
void resetNodeResolveState();
/*!
* Resolves the IDs to which connecting nodes connect from names.
* Must be called after node registration has finished!
*/
void mapNodeboxConnections();
private:
/*!
* Resets the manager to its initial state.
* See the documentation of the constructor.
*/
void clear();
/*!
* Allocates a new content ID, and returns it.
* @return the allocated ID or \ref CONTENT_IGNORE if could not allocate
*/
content_t allocateId();
/*!
* Binds the given content ID and node name.
* Registers them in \ref m_name_id_mapping and
* \ref m_name_id_mapping_with_aliases.
* @param i a content ID
* @param name a node name
*/
void addNameIdMapping(content_t i, std::string name);
/*!
* Recalculates m_selection_box_int_union based on
* m_selection_box_union.
*/
void fixSelectionBoxIntUnion();
//! Features indexed by ID.
std::vector<ContentFeatures> m_content_features;
//! A mapping for fast conversion between names and IDs
NameIdMapping m_name_id_mapping;
/*!
* Like @ref m_name_id_mapping, but maps only from names to IDs, and
* includes aliases too. Updated by \ref updateAliases().
* Note: Not serialized.
*/
std::unordered_map<std::string, content_t> m_name_id_mapping_with_aliases;
/*!
* A mapping from group names to a vector of content types that belong
* to it. Necessary for a direct lookup in \ref getIds().
* Note: Not serialized.
*/
std::unordered_map<std::string, std::vector<content_t>> m_group_to_items;
/*!
* The next ID that might be free to allocate.
* It can be allocated already, because \ref CONTENT_AIR,
* \ref CONTENT_UNKNOWN and \ref CONTENT_IGNORE are registered when the
* manager is initialized, and new IDs are allocated from 0.
*/
content_t m_next_id;
//! True if all nodes have been registered.
bool m_node_registration_complete;
/*!
* The union of all nodes' selection boxes.
* Might be larger if big nodes are removed from the manager.
*/
aabb3f m_selection_box_union;
/*!
* The smallest box in integer node coordinates that
* contains all nodes' selection boxes.
* Might be larger if big nodes are removed from the manager.
*/
core::aabbox3d<s16> m_selection_box_int_union;
/*!
* NodeResolver instances to notify once node registration has finished.
* Even constant NodeDefManager instances can register listeners.
*/
mutable std::vector<NodeResolver *> m_pending_resolve_callbacks;
};
NodeDefManager *createNodeDefManager();
class NodeResolver {
public:
NodeResolver();
virtual ~NodeResolver();
virtual void resolveNodeNames() = 0;
bool getIdFromNrBacklog(content_t *result_out,
const std::string &node_alt, content_t c_fallback,
bool error_on_fallback = true);
bool getIdsFromNrBacklog(std::vector<content_t> *result_out,
bool all_required = false, content_t c_fallback = CONTENT_IGNORE);
void nodeResolveInternal();
u32 m_nodenames_idx = 0;
u32 m_nnlistsizes_idx = 0;
std::vector<std::string> m_nodenames;
std::vector<size_t> m_nnlistsizes;
const NodeDefManager *m_ndef = nullptr;
bool m_resolve_done = false;
};
| pgimeno/minetest | src/nodedef.h | C++ | mit | 21,220 |
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "nodemetadata.h"
#include "exceptions.h"
#include "gamedef.h"
#include "inventory.h"
#include "log.h"
#include "util/serialize.h"
#include "util/basic_macros.h"
#include "constants.h" // MAP_BLOCKSIZE
#include <sstream>
/*
NodeMetadata
*/
NodeMetadata::NodeMetadata(IItemDefManager *item_def_mgr):
m_inventory(new Inventory(item_def_mgr))
{}
NodeMetadata::~NodeMetadata()
{
delete m_inventory;
}
void NodeMetadata::serialize(std::ostream &os, u8 version, bool disk) const
{
int num_vars = disk ? m_stringvars.size() : countNonPrivate();
writeU32(os, num_vars);
for (const auto &sv : m_stringvars) {
bool priv = isPrivate(sv.first);
if (!disk && priv)
continue;
os << serializeString(sv.first);
os << serializeLongString(sv.second);
if (version >= 2)
writeU8(os, (priv) ? 1 : 0);
}
m_inventory->serialize(os);
}
void NodeMetadata::deSerialize(std::istream &is, u8 version)
{
clear();
int num_vars = readU32(is);
for(int i=0; i<num_vars; i++){
std::string name = deSerializeString(is);
std::string var = deSerializeLongString(is);
m_stringvars[name] = var;
if (version >= 2) {
if (readU8(is) == 1)
markPrivate(name, true);
}
}
m_inventory->deSerialize(is);
}
void NodeMetadata::clear()
{
Metadata::clear();
m_privatevars.clear();
m_inventory->clear();
}
bool NodeMetadata::empty() const
{
return Metadata::empty() && m_inventory->getLists().empty();
}
void NodeMetadata::markPrivate(const std::string &name, bool set)
{
if (set)
m_privatevars.insert(name);
else
m_privatevars.erase(name);
}
int NodeMetadata::countNonPrivate() const
{
// m_privatevars can contain names not actually present
// DON'T: return m_stringvars.size() - m_privatevars.size();
int n = 0;
for (const auto &sv : m_stringvars) {
if (!isPrivate(sv.first))
n++;
}
return n;
}
/*
NodeMetadataList
*/
void NodeMetadataList::serialize(std::ostream &os, u8 blockver, bool disk,
bool absolute_pos) const
{
/*
Version 0 is a placeholder for "nothing to see here; go away."
*/
u16 count = countNonEmpty();
if (count == 0) {
writeU8(os, 0); // version
return;
}
u8 version = (blockver > 27) ? 2 : 1;
writeU8(os, version);
writeU16(os, count);
for (NodeMetadataMap::const_iterator
i = m_data.begin();
i != m_data.end(); ++i) {
v3s16 p = i->first;
NodeMetadata *data = i->second;
if (data->empty())
continue;
if (absolute_pos) {
writeS16(os, p.X);
writeS16(os, p.Y);
writeS16(os, p.Z);
} else {
// Serialize positions within a mapblock
u16 p16 = (p.Z * MAP_BLOCKSIZE + p.Y) * MAP_BLOCKSIZE + p.X;
writeU16(os, p16);
}
data->serialize(os, version, disk);
}
}
void NodeMetadataList::deSerialize(std::istream &is,
IItemDefManager *item_def_mgr, bool absolute_pos)
{
clear();
u8 version = readU8(is);
if (version == 0) {
// Nothing
return;
}
if (version > 2) {
std::string err_str = std::string(FUNCTION_NAME)
+ ": version " + itos(version) + " not supported";
infostream << err_str << std::endl;
throw SerializationError(err_str);
}
u16 count = readU16(is);
for (u16 i = 0; i < count; i++) {
v3s16 p;
if (absolute_pos) {
p.X = readS16(is);
p.Y = readS16(is);
p.Z = readS16(is);
} else {
u16 p16 = readU16(is);
p.X = p16 & (MAP_BLOCKSIZE - 1);
p16 /= MAP_BLOCKSIZE;
p.Y = p16 & (MAP_BLOCKSIZE - 1);
p16 /= MAP_BLOCKSIZE;
p.Z = p16;
}
if (m_data.find(p) != m_data.end()) {
warningstream << "NodeMetadataList::deSerialize(): "
<< "already set data at position " << PP(p)
<< ": Ignoring." << std::endl;
continue;
}
NodeMetadata *data = new NodeMetadata(item_def_mgr);
data->deSerialize(is, version);
m_data[p] = data;
}
}
NodeMetadataList::~NodeMetadataList()
{
clear();
}
std::vector<v3s16> NodeMetadataList::getAllKeys()
{
std::vector<v3s16> keys;
NodeMetadataMap::const_iterator it;
for (it = m_data.begin(); it != m_data.end(); ++it)
keys.push_back(it->first);
return keys;
}
NodeMetadata *NodeMetadataList::get(v3s16 p)
{
NodeMetadataMap::const_iterator n = m_data.find(p);
if (n == m_data.end())
return NULL;
return n->second;
}
void NodeMetadataList::remove(v3s16 p)
{
NodeMetadata *olddata = get(p);
if (olddata) {
if (m_is_metadata_owner)
delete olddata;
m_data.erase(p);
}
}
void NodeMetadataList::set(v3s16 p, NodeMetadata *d)
{
remove(p);
m_data.insert(std::make_pair(p, d));
}
void NodeMetadataList::clear()
{
if (m_is_metadata_owner) {
NodeMetadataMap::const_iterator it;
for (it = m_data.begin(); it != m_data.end(); ++it)
delete it->second;
}
m_data.clear();
}
int NodeMetadataList::countNonEmpty() const
{
int n = 0;
NodeMetadataMap::const_iterator it;
for (it = m_data.begin(); it != m_data.end(); ++it) {
if (!it->second->empty())
n++;
}
return n;
}
| pgimeno/minetest | src/nodemetadata.cpp | C++ | mit | 5,608 |
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include <unordered_set>
#include "metadata.h"
/*
NodeMetadata stores arbitary amounts of data for special blocks.
Used for furnaces, chests and signs.
There are two interaction methods: inventory menu and text input.
Only one can be used for a single metadata, thus only inventory OR
text input should exist in a metadata.
*/
class Inventory;
class IItemDefManager;
class NodeMetadata : public Metadata
{
public:
NodeMetadata(IItemDefManager *item_def_mgr);
~NodeMetadata();
void serialize(std::ostream &os, u8 version, bool disk=true) const;
void deSerialize(std::istream &is, u8 version);
void clear();
bool empty() const;
// The inventory
Inventory *getInventory()
{
return m_inventory;
}
inline bool isPrivate(const std::string &name) const
{
return m_privatevars.count(name) != 0;
}
void markPrivate(const std::string &name, bool set);
private:
int countNonPrivate() const;
Inventory *m_inventory;
std::unordered_set<std::string> m_privatevars;
};
/*
List of metadata of all the nodes of a block
*/
typedef std::map<v3s16, NodeMetadata *> NodeMetadataMap;
class NodeMetadataList
{
public:
NodeMetadataList(bool is_metadata_owner = true) :
m_is_metadata_owner(is_metadata_owner)
{}
~NodeMetadataList();
void serialize(std::ostream &os, u8 blockver, bool disk = true,
bool absolute_pos = false) const;
void deSerialize(std::istream &is, IItemDefManager *item_def_mgr,
bool absolute_pos = false);
// Add all keys in this list to the vector keys
std::vector<v3s16> getAllKeys();
// Get pointer to data
NodeMetadata *get(v3s16 p);
// Deletes data
void remove(v3s16 p);
// Deletes old data and sets a new one
void set(v3s16 p, NodeMetadata *d);
// Deletes all
void clear();
size_t size() const { return m_data.size(); }
NodeMetadataMap::const_iterator begin()
{
return m_data.begin();
}
NodeMetadataMap::const_iterator end()
{
return m_data.end();
}
private:
int countNonEmpty() const;
bool m_is_metadata_owner;
NodeMetadataMap m_data;
};
| pgimeno/minetest | src/nodemetadata.h | C++ | mit | 2,827 |
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "nodetimer.h"
#include "log.h"
#include "serialization.h"
#include "util/serialize.h"
#include "constants.h" // MAP_BLOCKSIZE
/*
NodeTimer
*/
void NodeTimer::serialize(std::ostream &os) const
{
writeF1000(os, timeout);
writeF1000(os, elapsed);
}
void NodeTimer::deSerialize(std::istream &is)
{
timeout = readF1000(is);
elapsed = readF1000(is);
}
/*
NodeTimerList
*/
void NodeTimerList::serialize(std::ostream &os, u8 map_format_version) const
{
if (map_format_version == 24) {
// Version 0 is a placeholder for "nothing to see here; go away."
if (m_timers.empty()) {
writeU8(os, 0); // version
return;
}
writeU8(os, 1); // version
writeU16(os, m_timers.size());
}
if (map_format_version >= 25) {
writeU8(os, 2 + 4 + 4); // length of the data for a single timer
writeU16(os, m_timers.size());
}
for (const auto &timer : m_timers) {
NodeTimer t = timer.second;
NodeTimer nt = NodeTimer(t.timeout,
t.timeout - (f32)(timer.first - m_time), t.position);
v3s16 p = t.position;
u16 p16 = p.Z * MAP_BLOCKSIZE * MAP_BLOCKSIZE + p.Y * MAP_BLOCKSIZE + p.X;
writeU16(os, p16);
nt.serialize(os);
}
}
void NodeTimerList::deSerialize(std::istream &is, u8 map_format_version)
{
clear();
if (map_format_version == 24) {
u8 timer_version = readU8(is);
if(timer_version == 0)
return;
if(timer_version != 1)
throw SerializationError("unsupported NodeTimerList version");
}
if (map_format_version >= 25) {
u8 timer_data_len = readU8(is);
if(timer_data_len != 2+4+4)
throw SerializationError("unsupported NodeTimer data length");
}
u16 count = readU16(is);
for (u16 i = 0; i < count; i++) {
u16 p16 = readU16(is);
v3s16 p;
p.Z = p16 / MAP_BLOCKSIZE / MAP_BLOCKSIZE;
p16 &= MAP_BLOCKSIZE * MAP_BLOCKSIZE - 1;
p.Y = p16 / MAP_BLOCKSIZE;
p16 &= MAP_BLOCKSIZE - 1;
p.X = p16;
NodeTimer t(p);
t.deSerialize(is);
if (t.timeout <= 0) {
warningstream<<"NodeTimerList::deSerialize(): "
<<"invalid data at position"
<<"("<<p.X<<","<<p.Y<<","<<p.Z<<"): Ignoring."
<<std::endl;
continue;
}
if (m_iterators.find(p) != m_iterators.end()) {
warningstream<<"NodeTimerList::deSerialize(): "
<<"already set data at position"
<<"("<<p.X<<","<<p.Y<<","<<p.Z<<"): Ignoring."
<<std::endl;
continue;
}
insert(t);
}
}
std::vector<NodeTimer> NodeTimerList::step(float dtime)
{
std::vector<NodeTimer> elapsed_timers;
m_time += dtime;
if (m_next_trigger_time == -1. || m_time < m_next_trigger_time) {
return elapsed_timers;
}
std::multimap<double, NodeTimer>::iterator i = m_timers.begin();
// Process timers
for (; i != m_timers.end() && i->first <= m_time; ++i) {
NodeTimer t = i->second;
t.elapsed = t.timeout + (f32)(m_time - i->first);
elapsed_timers.push_back(t);
m_iterators.erase(t.position);
}
// Delete elapsed timers
m_timers.erase(m_timers.begin(), i);
if (m_timers.empty())
m_next_trigger_time = -1.;
else
m_next_trigger_time = m_timers.begin()->first;
return elapsed_timers;
}
| pgimeno/minetest | src/nodetimer.cpp | C++ | mit | 3,831 |
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "irr_v3d.h"
#include <iostream>
#include <map>
#include <vector>
/*
NodeTimer provides per-node timed callback functionality.
Can be used for:
- Furnaces, to keep the fire burnin'
- "activated" nodes that snap back to their original state
after a fixed amount of time (mesecons buttons, for example)
*/
class NodeTimer
{
public:
NodeTimer() = default;
NodeTimer(const v3s16 &position_):
position(position_) {}
NodeTimer(f32 timeout_, f32 elapsed_, v3s16 position_):
timeout(timeout_), elapsed(elapsed_), position(position_) {}
~NodeTimer() = default;
void serialize(std::ostream &os) const;
void deSerialize(std::istream &is);
f32 timeout = 0.0f;
f32 elapsed = 0.0f;
v3s16 position;
};
/*
List of timers of all the nodes of a block
*/
class NodeTimerList
{
public:
NodeTimerList() = default;
~NodeTimerList() = default;
void serialize(std::ostream &os, u8 map_format_version) const;
void deSerialize(std::istream &is, u8 map_format_version);
// Get timer
NodeTimer get(const v3s16 &p) {
std::map<v3s16, std::multimap<double, NodeTimer>::iterator>::iterator n =
m_iterators.find(p);
if (n == m_iterators.end())
return NodeTimer();
NodeTimer t = n->second->second;
t.elapsed = t.timeout - (n->second->first - m_time);
return t;
}
// Deletes timer
void remove(v3s16 p) {
std::map<v3s16, std::multimap<double, NodeTimer>::iterator>::iterator n =
m_iterators.find(p);
if(n != m_iterators.end()) {
double removed_time = n->second->first;
m_timers.erase(n->second);
m_iterators.erase(n);
// Yes, this is float equality, but it is not a problem
// since we only test equality of floats as an ordered type
// and thus we never lose precision
if (removed_time == m_next_trigger_time) {
if (m_timers.empty())
m_next_trigger_time = -1.;
else
m_next_trigger_time = m_timers.begin()->first;
}
}
}
// Undefined behaviour if there already is a timer
void insert(NodeTimer timer) {
v3s16 p = timer.position;
double trigger_time = m_time + (double)(timer.timeout - timer.elapsed);
std::multimap<double, NodeTimer>::iterator it =
m_timers.insert(std::pair<double, NodeTimer>(
trigger_time, timer
));
m_iterators.insert(
std::pair<v3s16, std::multimap<double, NodeTimer>::iterator>(p, it));
if (m_next_trigger_time == -1. || trigger_time < m_next_trigger_time)
m_next_trigger_time = trigger_time;
}
// Deletes old timer and sets a new one
inline void set(const NodeTimer &timer) {
remove(timer.position);
insert(timer);
}
// Deletes all timers
void clear() {
m_timers.clear();
m_iterators.clear();
m_next_trigger_time = -1.;
}
// Move forward in time, returns elapsed timers
std::vector<NodeTimer> step(float dtime);
private:
std::multimap<double, NodeTimer> m_timers;
std::map<v3s16, std::multimap<double, NodeTimer>::iterator> m_iterators;
double m_next_trigger_time = -1.0;
double m_time = 0.0;
};
| pgimeno/minetest | src/nodetimer.h | C++ | mit | 3,753 |
/*
* Minetest
* Copyright (C) 2010-2014 celeron55, Perttu Ahola <celeron55@gmail.com>
* Copyright (C) 2010-2014 kwolekr, Ryan Kwolek <kwolekr@minetest.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cmath>
#include "noise.h"
#include <iostream>
#include <cstring> // memset
#include "debug.h"
#include "util/numeric.h"
#include "util/string.h"
#include "exceptions.h"
#define NOISE_MAGIC_X 1619
#define NOISE_MAGIC_Y 31337
#define NOISE_MAGIC_Z 52591
#define NOISE_MAGIC_SEED 1013
typedef float (*Interp2dFxn)(
float v00, float v10, float v01, float v11,
float x, float y);
typedef float (*Interp3dFxn)(
float v000, float v100, float v010, float v110,
float v001, float v101, float v011, float v111,
float x, float y, float z);
float cos_lookup[16] = {
1.0f, 0.9238f, 0.7071f, 0.3826f, .0f, -0.3826f, -0.7071f, -0.9238f,
1.0f, -0.9238f, -0.7071f, -0.3826f, .0f, 0.3826f, 0.7071f, 0.9238f
};
FlagDesc flagdesc_noiseparams[] = {
{"defaults", NOISE_FLAG_DEFAULTS},
{"eased", NOISE_FLAG_EASED},
{"absvalue", NOISE_FLAG_ABSVALUE},
{"pointbuffer", NOISE_FLAG_POINTBUFFER},
{"simplex", NOISE_FLAG_SIMPLEX},
{NULL, 0}
};
///////////////////////////////////////////////////////////////////////////////
PcgRandom::PcgRandom(u64 state, u64 seq)
{
seed(state, seq);
}
void PcgRandom::seed(u64 state, u64 seq)
{
m_state = 0U;
m_inc = (seq << 1u) | 1u;
next();
m_state += state;
next();
}
u32 PcgRandom::next()
{
u64 oldstate = m_state;
m_state = oldstate * 6364136223846793005ULL + m_inc;
u32 xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u;
u32 rot = oldstate >> 59u;
return (xorshifted >> rot) | (xorshifted << ((-rot) & 31));
}
u32 PcgRandom::range(u32 bound)
{
// If the bound is 0, we cover the whole RNG's range
if (bound == 0)
return next();
/*
This is an optimization of the expression:
0x100000000ull % bound
since 64-bit modulo operations typically much slower than 32.
*/
u32 threshold = -bound % bound;
u32 r;
/*
If the bound is not a multiple of the RNG's range, it may cause bias,
e.g. a RNG has a range from 0 to 3 and we take want a number 0 to 2.
Using rand() % 3, the number 0 would be twice as likely to appear.
With a very large RNG range, the effect becomes less prevalent but
still present.
This can be solved by modifying the range of the RNG to become a
multiple of bound by dropping values above the a threshold.
In our example, threshold == 4 % 3 == 1, so reject values < 1
(that is, 0), thus making the range == 3 with no bias.
This loop may look dangerous, but will always terminate due to the
RNG's property of uniformity.
*/
while ((r = next()) < threshold)
;
return r % bound;
}
s32 PcgRandom::range(s32 min, s32 max)
{
if (max < min)
throw PrngException("Invalid range (max < min)");
// We have to cast to s64 because otherwise this could overflow,
// and signed overflow is undefined behavior.
u32 bound = (s64)max - (s64)min + 1;
return range(bound) + min;
}
void PcgRandom::bytes(void *out, size_t len)
{
u8 *outb = (u8 *)out;
int bytes_left = 0;
u32 r;
while (len--) {
if (bytes_left == 0) {
bytes_left = sizeof(u32);
r = next();
}
*outb = r & 0xFF;
outb++;
bytes_left--;
r >>= CHAR_BIT;
}
}
s32 PcgRandom::randNormalDist(s32 min, s32 max, int num_trials)
{
s32 accum = 0;
for (int i = 0; i != num_trials; i++)
accum += range(min, max);
return myround((float)accum / num_trials);
}
///////////////////////////////////////////////////////////////////////////////
float noise2d(int x, int y, s32 seed)
{
unsigned int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y
+ NOISE_MAGIC_SEED * seed) & 0x7fffffff;
n = (n >> 13) ^ n;
n = (n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff;
return 1.f - (float)(int)n / 0x40000000;
}
float noise3d(int x, int y, int z, s32 seed)
{
unsigned int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y + NOISE_MAGIC_Z * z
+ NOISE_MAGIC_SEED * seed) & 0x7fffffff;
n = (n >> 13) ^ n;
n = (n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff;
return 1.f - (float)(int)n / 0x40000000;
}
inline float dotProduct(float vx, float vy, float wx, float wy)
{
return vx * wx + vy * wy;
}
inline float linearInterpolation(float v0, float v1, float t)
{
return v0 + (v1 - v0) * t;
}
inline float biLinearInterpolation(
float v00, float v10,
float v01, float v11,
float x, float y)
{
float tx = easeCurve(x);
float ty = easeCurve(y);
float u = linearInterpolation(v00, v10, tx);
float v = linearInterpolation(v01, v11, tx);
return linearInterpolation(u, v, ty);
}
inline float biLinearInterpolationNoEase(
float v00, float v10,
float v01, float v11,
float x, float y)
{
float u = linearInterpolation(v00, v10, x);
float v = linearInterpolation(v01, v11, x);
return linearInterpolation(u, v, y);
}
float triLinearInterpolation(
float v000, float v100, float v010, float v110,
float v001, float v101, float v011, float v111,
float x, float y, float z)
{
float tx = easeCurve(x);
float ty = easeCurve(y);
float tz = easeCurve(z);
float u = biLinearInterpolationNoEase(v000, v100, v010, v110, tx, ty);
float v = biLinearInterpolationNoEase(v001, v101, v011, v111, tx, ty);
return linearInterpolation(u, v, tz);
}
float triLinearInterpolationNoEase(
float v000, float v100, float v010, float v110,
float v001, float v101, float v011, float v111,
float x, float y, float z)
{
float u = biLinearInterpolationNoEase(v000, v100, v010, v110, x, y);
float v = biLinearInterpolationNoEase(v001, v101, v011, v111, x, y);
return linearInterpolation(u, v, z);
}
float noise2d_gradient(float x, float y, s32 seed, bool eased)
{
// Calculate the integer coordinates
int x0 = myfloor(x);
int y0 = myfloor(y);
// Calculate the remaining part of the coordinates
float xl = x - (float)x0;
float yl = y - (float)y0;
// Get values for corners of square
float v00 = noise2d(x0, y0, seed);
float v10 = noise2d(x0+1, y0, seed);
float v01 = noise2d(x0, y0+1, seed);
float v11 = noise2d(x0+1, y0+1, seed);
// Interpolate
if (eased)
return biLinearInterpolation(v00, v10, v01, v11, xl, yl);
return biLinearInterpolationNoEase(v00, v10, v01, v11, xl, yl);
}
float noise3d_gradient(float x, float y, float z, s32 seed, bool eased)
{
// Calculate the integer coordinates
int x0 = myfloor(x);
int y0 = myfloor(y);
int z0 = myfloor(z);
// Calculate the remaining part of the coordinates
float xl = x - (float)x0;
float yl = y - (float)y0;
float zl = z - (float)z0;
// Get values for corners of cube
float v000 = noise3d(x0, y0, z0, seed);
float v100 = noise3d(x0 + 1, y0, z0, seed);
float v010 = noise3d(x0, y0 + 1, z0, seed);
float v110 = noise3d(x0 + 1, y0 + 1, z0, seed);
float v001 = noise3d(x0, y0, z0 + 1, seed);
float v101 = noise3d(x0 + 1, y0, z0 + 1, seed);
float v011 = noise3d(x0, y0 + 1, z0 + 1, seed);
float v111 = noise3d(x0 + 1, y0 + 1, z0 + 1, seed);
// Interpolate
if (eased) {
return triLinearInterpolation(
v000, v100, v010, v110,
v001, v101, v011, v111,
xl, yl, zl);
}
return triLinearInterpolationNoEase(
v000, v100, v010, v110,
v001, v101, v011, v111,
xl, yl, zl);
}
float noise2d_perlin(float x, float y, s32 seed,
int octaves, float persistence, bool eased)
{
float a = 0;
float f = 1.0;
float g = 1.0;
for (int i = 0; i < octaves; i++)
{
a += g * noise2d_gradient(x * f, y * f, seed + i, eased);
f *= 2.0;
g *= persistence;
}
return a;
}
float noise2d_perlin_abs(float x, float y, s32 seed,
int octaves, float persistence, bool eased)
{
float a = 0;
float f = 1.0;
float g = 1.0;
for (int i = 0; i < octaves; i++) {
a += g * std::fabs(noise2d_gradient(x * f, y * f, seed + i, eased));
f *= 2.0;
g *= persistence;
}
return a;
}
float noise3d_perlin(float x, float y, float z, s32 seed,
int octaves, float persistence, bool eased)
{
float a = 0;
float f = 1.0;
float g = 1.0;
for (int i = 0; i < octaves; i++) {
a += g * noise3d_gradient(x * f, y * f, z * f, seed + i, eased);
f *= 2.0;
g *= persistence;
}
return a;
}
float noise3d_perlin_abs(float x, float y, float z, s32 seed,
int octaves, float persistence, bool eased)
{
float a = 0;
float f = 1.0;
float g = 1.0;
for (int i = 0; i < octaves; i++) {
a += g * std::fabs(noise3d_gradient(x * f, y * f, z * f, seed + i, eased));
f *= 2.0;
g *= persistence;
}
return a;
}
float contour(float v)
{
v = std::fabs(v);
if (v >= 1.0)
return 0.0;
return (1.0 - v);
}
///////////////////////// [ New noise ] ////////////////////////////
float NoisePerlin2D(NoiseParams *np, float x, float y, s32 seed)
{
float a = 0;
float f = 1.0;
float g = 1.0;
x /= np->spread.X;
y /= np->spread.Y;
seed += np->seed;
for (size_t i = 0; i < np->octaves; i++) {
float noiseval = noise2d_gradient(x * f, y * f, seed + i,
np->flags & (NOISE_FLAG_DEFAULTS | NOISE_FLAG_EASED));
if (np->flags & NOISE_FLAG_ABSVALUE)
noiseval = std::fabs(noiseval);
a += g * noiseval;
f *= np->lacunarity;
g *= np->persist;
}
return np->offset + a * np->scale;
}
float NoisePerlin3D(NoiseParams *np, float x, float y, float z, s32 seed)
{
float a = 0;
float f = 1.0;
float g = 1.0;
x /= np->spread.X;
y /= np->spread.Y;
z /= np->spread.Z;
seed += np->seed;
for (size_t i = 0; i < np->octaves; i++) {
float noiseval = noise3d_gradient(x * f, y * f, z * f, seed + i,
np->flags & NOISE_FLAG_EASED);
if (np->flags & NOISE_FLAG_ABSVALUE)
noiseval = std::fabs(noiseval);
a += g * noiseval;
f *= np->lacunarity;
g *= np->persist;
}
return np->offset + a * np->scale;
}
Noise::Noise(NoiseParams *np_, s32 seed, u32 sx, u32 sy, u32 sz)
{
memcpy(&np, np_, sizeof(np));
this->seed = seed;
this->sx = sx;
this->sy = sy;
this->sz = sz;
allocBuffers();
}
Noise::~Noise()
{
delete[] gradient_buf;
delete[] persist_buf;
delete[] noise_buf;
delete[] result;
}
void Noise::allocBuffers()
{
if (sx < 1)
sx = 1;
if (sy < 1)
sy = 1;
if (sz < 1)
sz = 1;
this->noise_buf = NULL;
resizeNoiseBuf(sz > 1);
delete[] gradient_buf;
delete[] persist_buf;
delete[] result;
try {
size_t bufsize = sx * sy * sz;
this->persist_buf = NULL;
this->gradient_buf = new float[bufsize];
this->result = new float[bufsize];
} catch (std::bad_alloc &e) {
throw InvalidNoiseParamsException();
}
}
void Noise::setSize(u32 sx, u32 sy, u32 sz)
{
this->sx = sx;
this->sy = sy;
this->sz = sz;
allocBuffers();
}
void Noise::setSpreadFactor(v3f spread)
{
this->np.spread = spread;
resizeNoiseBuf(sz > 1);
}
void Noise::setOctaves(int octaves)
{
this->np.octaves = octaves;
resizeNoiseBuf(sz > 1);
}
void Noise::resizeNoiseBuf(bool is3d)
{
//maximum possible spread value factor
float ofactor = (np.lacunarity > 1.0) ?
pow(np.lacunarity, np.octaves - 1) :
np.lacunarity;
// noise lattice point count
// (int)(sz * spread * ofactor) is # of lattice points crossed due to length
float num_noise_points_x = sx * ofactor / np.spread.X;
float num_noise_points_y = sy * ofactor / np.spread.Y;
float num_noise_points_z = sz * ofactor / np.spread.Z;
// protect against obviously invalid parameters
if (num_noise_points_x > 1000000000.f ||
num_noise_points_y > 1000000000.f ||
num_noise_points_z > 1000000000.f)
throw InvalidNoiseParamsException();
// + 2 for the two initial endpoints
// + 1 for potentially crossing a boundary due to offset
size_t nlx = (size_t)std::ceil(num_noise_points_x) + 3;
size_t nly = (size_t)std::ceil(num_noise_points_y) + 3;
size_t nlz = is3d ? (size_t)std::ceil(num_noise_points_z) + 3 : 1;
delete[] noise_buf;
try {
noise_buf = new float[nlx * nly * nlz];
} catch (std::bad_alloc &e) {
throw InvalidNoiseParamsException();
}
}
/*
* NB: This algorithm is not optimal in terms of space complexity. The entire
* integer lattice of noise points could be done as 2 lines instead, and for 3D,
* 2 lines + 2 planes.
* However, this would require the noise calls to be interposed with the
* interpolation loops, which may trash the icache, leading to lower overall
* performance.
* Another optimization that could save half as many noise calls is to carry over
* values from the previous noise lattice as midpoints in the new lattice for the
* next octave.
*/
#define idx(x, y) ((y) * nlx + (x))
void Noise::gradientMap2D(
float x, float y,
float step_x, float step_y,
s32 seed)
{
float v00, v01, v10, v11, u, v, orig_u;
u32 index, i, j, noisex, noisey;
u32 nlx, nly;
s32 x0, y0;
bool eased = np.flags & (NOISE_FLAG_DEFAULTS | NOISE_FLAG_EASED);
Interp2dFxn interpolate = eased ?
biLinearInterpolation : biLinearInterpolationNoEase;
x0 = std::floor(x);
y0 = std::floor(y);
u = x - (float)x0;
v = y - (float)y0;
orig_u = u;
//calculate noise point lattice
nlx = (u32)(u + sx * step_x) + 2;
nly = (u32)(v + sy * step_y) + 2;
index = 0;
for (j = 0; j != nly; j++)
for (i = 0; i != nlx; i++)
noise_buf[index++] = noise2d(x0 + i, y0 + j, seed);
//calculate interpolations
index = 0;
noisey = 0;
for (j = 0; j != sy; j++) {
v00 = noise_buf[idx(0, noisey)];
v10 = noise_buf[idx(1, noisey)];
v01 = noise_buf[idx(0, noisey + 1)];
v11 = noise_buf[idx(1, noisey + 1)];
u = orig_u;
noisex = 0;
for (i = 0; i != sx; i++) {
gradient_buf[index++] = interpolate(v00, v10, v01, v11, u, v);
u += step_x;
if (u >= 1.0) {
u -= 1.0;
noisex++;
v00 = v10;
v01 = v11;
v10 = noise_buf[idx(noisex + 1, noisey)];
v11 = noise_buf[idx(noisex + 1, noisey + 1)];
}
}
v += step_y;
if (v >= 1.0) {
v -= 1.0;
noisey++;
}
}
}
#undef idx
#define idx(x, y, z) ((z) * nly * nlx + (y) * nlx + (x))
void Noise::gradientMap3D(
float x, float y, float z,
float step_x, float step_y, float step_z,
s32 seed)
{
float v000, v010, v100, v110;
float v001, v011, v101, v111;
float u, v, w, orig_u, orig_v;
u32 index, i, j, k, noisex, noisey, noisez;
u32 nlx, nly, nlz;
s32 x0, y0, z0;
Interp3dFxn interpolate = (np.flags & NOISE_FLAG_EASED) ?
triLinearInterpolation : triLinearInterpolationNoEase;
x0 = std::floor(x);
y0 = std::floor(y);
z0 = std::floor(z);
u = x - (float)x0;
v = y - (float)y0;
w = z - (float)z0;
orig_u = u;
orig_v = v;
//calculate noise point lattice
nlx = (u32)(u + sx * step_x) + 2;
nly = (u32)(v + sy * step_y) + 2;
nlz = (u32)(w + sz * step_z) + 2;
index = 0;
for (k = 0; k != nlz; k++)
for (j = 0; j != nly; j++)
for (i = 0; i != nlx; i++)
noise_buf[index++] = noise3d(x0 + i, y0 + j, z0 + k, seed);
//calculate interpolations
index = 0;
noisey = 0;
noisez = 0;
for (k = 0; k != sz; k++) {
v = orig_v;
noisey = 0;
for (j = 0; j != sy; j++) {
v000 = noise_buf[idx(0, noisey, noisez)];
v100 = noise_buf[idx(1, noisey, noisez)];
v010 = noise_buf[idx(0, noisey + 1, noisez)];
v110 = noise_buf[idx(1, noisey + 1, noisez)];
v001 = noise_buf[idx(0, noisey, noisez + 1)];
v101 = noise_buf[idx(1, noisey, noisez + 1)];
v011 = noise_buf[idx(0, noisey + 1, noisez + 1)];
v111 = noise_buf[idx(1, noisey + 1, noisez + 1)];
u = orig_u;
noisex = 0;
for (i = 0; i != sx; i++) {
gradient_buf[index++] = interpolate(
v000, v100, v010, v110,
v001, v101, v011, v111,
u, v, w);
u += step_x;
if (u >= 1.0) {
u -= 1.0;
noisex++;
v000 = v100;
v010 = v110;
v100 = noise_buf[idx(noisex + 1, noisey, noisez)];
v110 = noise_buf[idx(noisex + 1, noisey + 1, noisez)];
v001 = v101;
v011 = v111;
v101 = noise_buf[idx(noisex + 1, noisey, noisez + 1)];
v111 = noise_buf[idx(noisex + 1, noisey + 1, noisez + 1)];
}
}
v += step_y;
if (v >= 1.0) {
v -= 1.0;
noisey++;
}
}
w += step_z;
if (w >= 1.0) {
w -= 1.0;
noisez++;
}
}
}
#undef idx
float *Noise::perlinMap2D(float x, float y, float *persistence_map)
{
float f = 1.0, g = 1.0;
size_t bufsize = sx * sy;
x /= np.spread.X;
y /= np.spread.Y;
memset(result, 0, sizeof(float) * bufsize);
if (persistence_map) {
if (!persist_buf)
persist_buf = new float[bufsize];
for (size_t i = 0; i != bufsize; i++)
persist_buf[i] = 1.0;
}
for (size_t oct = 0; oct < np.octaves; oct++) {
gradientMap2D(x * f, y * f,
f / np.spread.X, f / np.spread.Y,
seed + np.seed + oct);
updateResults(g, persist_buf, persistence_map, bufsize);
f *= np.lacunarity;
g *= np.persist;
}
if (std::fabs(np.offset - 0.f) > 0.00001 || std::fabs(np.scale - 1.f) > 0.00001) {
for (size_t i = 0; i != bufsize; i++)
result[i] = result[i] * np.scale + np.offset;
}
return result;
}
float *Noise::perlinMap3D(float x, float y, float z, float *persistence_map)
{
float f = 1.0, g = 1.0;
size_t bufsize = sx * sy * sz;
x /= np.spread.X;
y /= np.spread.Y;
z /= np.spread.Z;
memset(result, 0, sizeof(float) * bufsize);
if (persistence_map) {
if (!persist_buf)
persist_buf = new float[bufsize];
for (size_t i = 0; i != bufsize; i++)
persist_buf[i] = 1.0;
}
for (size_t oct = 0; oct < np.octaves; oct++) {
gradientMap3D(x * f, y * f, z * f,
f / np.spread.X, f / np.spread.Y, f / np.spread.Z,
seed + np.seed + oct);
updateResults(g, persist_buf, persistence_map, bufsize);
f *= np.lacunarity;
g *= np.persist;
}
if (std::fabs(np.offset - 0.f) > 0.00001 || std::fabs(np.scale - 1.f) > 0.00001) {
for (size_t i = 0; i != bufsize; i++)
result[i] = result[i] * np.scale + np.offset;
}
return result;
}
void Noise::updateResults(float g, float *gmap,
const float *persistence_map, size_t bufsize)
{
// This looks very ugly, but it is 50-70% faster than having
// conditional statements inside the loop
if (np.flags & NOISE_FLAG_ABSVALUE) {
if (persistence_map) {
for (size_t i = 0; i != bufsize; i++) {
result[i] += gmap[i] * std::fabs(gradient_buf[i]);
gmap[i] *= persistence_map[i];
}
} else {
for (size_t i = 0; i != bufsize; i++)
result[i] += g * std::fabs(gradient_buf[i]);
}
} else {
if (persistence_map) {
for (size_t i = 0; i != bufsize; i++) {
result[i] += gmap[i] * gradient_buf[i];
gmap[i] *= persistence_map[i];
}
} else {
for (size_t i = 0; i != bufsize; i++)
result[i] += g * gradient_buf[i];
}
}
}
| pgimeno/minetest | src/noise.cpp | C++ | mit | 19,642 |
/*
* Minetest
* Copyright (C) 2010-2014 celeron55, Perttu Ahola <celeron55@gmail.com>
* Copyright (C) 2010-2014 kwolekr, Ryan Kwolek <kwolekr@minetest.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "irr_v3d.h"
#include "exceptions.h"
#include "util/string.h"
extern FlagDesc flagdesc_noiseparams[];
// Note: this class is not polymorphic so that its high level of
// optimizability may be preserved in the common use case
class PseudoRandom {
public:
const static u32 RANDOM_RANGE = 32767;
inline PseudoRandom(int seed=0):
m_next(seed)
{
}
inline void seed(int seed)
{
m_next = seed;
}
inline int next()
{
m_next = m_next * 1103515245 + 12345;
return (unsigned)(m_next / 65536) % (RANDOM_RANGE + 1);
}
inline int range(int min, int max)
{
if (max < min)
throw PrngException("Invalid range (max < min)");
/*
Here, we ensure the range is not too large relative to RANDOM_MAX,
as otherwise the effects of bias would become noticable. Unlike
PcgRandom, we cannot modify this RNG's range as it would change the
output of this RNG for reverse compatibility.
*/
if ((u32)(max - min) > (RANDOM_RANGE + 1) / 10)
throw PrngException("Range too large");
return (next() % (max - min + 1)) + min;
}
private:
int m_next;
};
class PcgRandom {
public:
const static s32 RANDOM_MIN = -0x7fffffff - 1;
const static s32 RANDOM_MAX = 0x7fffffff;
const static u32 RANDOM_RANGE = 0xffffffff;
PcgRandom(u64 state=0x853c49e6748fea9bULL, u64 seq=0xda3e39cb94b95bdbULL);
void seed(u64 state, u64 seq=0xda3e39cb94b95bdbULL);
u32 next();
u32 range(u32 bound);
s32 range(s32 min, s32 max);
void bytes(void *out, size_t len);
s32 randNormalDist(s32 min, s32 max, int num_trials=6);
private:
u64 m_state;
u64 m_inc;
};
#define NOISE_FLAG_DEFAULTS 0x01
#define NOISE_FLAG_EASED 0x02
#define NOISE_FLAG_ABSVALUE 0x04
//// TODO(hmmmm): implement these!
#define NOISE_FLAG_POINTBUFFER 0x08
#define NOISE_FLAG_SIMPLEX 0x10
struct NoiseParams {
float offset = 0.0f;
float scale = 1.0f;
v3f spread = v3f(250, 250, 250);
s32 seed = 12345;
u16 octaves = 3;
float persist = 0.6f;
float lacunarity = 2.0f;
u32 flags = NOISE_FLAG_DEFAULTS;
NoiseParams() = default;
NoiseParams(float offset_, float scale_, const v3f &spread_, s32 seed_,
u16 octaves_, float persist_, float lacunarity_,
u32 flags_=NOISE_FLAG_DEFAULTS)
{
offset = offset_;
scale = scale_;
spread = spread_;
seed = seed_;
octaves = octaves_;
persist = persist_;
lacunarity = lacunarity_;
flags = flags_;
}
};
class Noise {
public:
NoiseParams np;
s32 seed;
u32 sx;
u32 sy;
u32 sz;
float *noise_buf = nullptr;
float *gradient_buf = nullptr;
float *persist_buf = nullptr;
float *result = nullptr;
Noise(NoiseParams *np, s32 seed, u32 sx, u32 sy, u32 sz=1);
~Noise();
void setSize(u32 sx, u32 sy, u32 sz=1);
void setSpreadFactor(v3f spread);
void setOctaves(int octaves);
void gradientMap2D(
float x, float y,
float step_x, float step_y,
s32 seed);
void gradientMap3D(
float x, float y, float z,
float step_x, float step_y, float step_z,
s32 seed);
float *perlinMap2D(float x, float y, float *persistence_map=NULL);
float *perlinMap3D(float x, float y, float z, float *persistence_map=NULL);
inline float *perlinMap2D_PO(float x, float xoff, float y, float yoff,
float *persistence_map=NULL)
{
return perlinMap2D(
x + xoff * np.spread.X,
y + yoff * np.spread.Y,
persistence_map);
}
inline float *perlinMap3D_PO(float x, float xoff, float y, float yoff,
float z, float zoff, float *persistence_map=NULL)
{
return perlinMap3D(
x + xoff * np.spread.X,
y + yoff * np.spread.Y,
z + zoff * np.spread.Z,
persistence_map);
}
private:
void allocBuffers();
void resizeNoiseBuf(bool is3d);
void updateResults(float g, float *gmap, const float *persistence_map,
size_t bufsize);
};
float NoisePerlin2D(NoiseParams *np, float x, float y, s32 seed);
float NoisePerlin3D(NoiseParams *np, float x, float y, float z, s32 seed);
inline float NoisePerlin2D_PO(NoiseParams *np, float x, float xoff,
float y, float yoff, s32 seed)
{
return NoisePerlin2D(np,
x + xoff * np->spread.X,
y + yoff * np->spread.Y,
seed);
}
inline float NoisePerlin3D_PO(NoiseParams *np, float x, float xoff,
float y, float yoff, float z, float zoff, s32 seed)
{
return NoisePerlin3D(np,
x + xoff * np->spread.X,
y + yoff * np->spread.Y,
z + zoff * np->spread.Z,
seed);
}
// Return value: -1 ... 1
float noise2d(int x, int y, s32 seed);
float noise3d(int x, int y, int z, s32 seed);
float noise2d_gradient(float x, float y, s32 seed, bool eased=true);
float noise3d_gradient(float x, float y, float z, s32 seed, bool eased=false);
float noise2d_perlin(float x, float y, s32 seed,
int octaves, float persistence, bool eased=true);
float noise2d_perlin_abs(float x, float y, s32 seed,
int octaves, float persistence, bool eased=true);
float noise3d_perlin(float x, float y, float z, s32 seed,
int octaves, float persistence, bool eased=false);
float noise3d_perlin_abs(float x, float y, float z, s32 seed,
int octaves, float persistence, bool eased=false);
inline float easeCurve(float t)
{
return t * t * t * (t * (6.f * t - 15.f) + 10.f);
}
float contour(float v);
| pgimeno/minetest | src/noise.h | C++ | mit | 6,607 |
/*
Minetest
Copyright (C) 2010-2015 kwolekr, Ryan Kwolek <kwolekr@minetest.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "objdef.h"
#include "util/numeric.h"
#include "log.h"
#include "gamedef.h"
ObjDefManager::ObjDefManager(IGameDef *gamedef, ObjDefType type)
{
m_objtype = type;
m_ndef = gamedef ? gamedef->getNodeDefManager() : NULL;
}
ObjDefManager::~ObjDefManager()
{
for (size_t i = 0; i != m_objects.size(); i++)
delete m_objects[i];
}
ObjDefHandle ObjDefManager::add(ObjDef *obj)
{
assert(obj);
if (obj->name.length() && getByName(obj->name))
return OBJDEF_INVALID_HANDLE;
u32 index = addRaw(obj);
if (index == OBJDEF_INVALID_INDEX)
return OBJDEF_INVALID_HANDLE;
obj->handle = createHandle(index, m_objtype, obj->uid);
return obj->handle;
}
ObjDef *ObjDefManager::get(ObjDefHandle handle) const
{
u32 index = validateHandle(handle);
return (index != OBJDEF_INVALID_INDEX) ? getRaw(index) : NULL;
}
ObjDef *ObjDefManager::set(ObjDefHandle handle, ObjDef *obj)
{
u32 index = validateHandle(handle);
if (index == OBJDEF_INVALID_INDEX)
return NULL;
ObjDef *oldobj = setRaw(index, obj);
obj->uid = oldobj->uid;
obj->index = oldobj->index;
obj->handle = oldobj->handle;
return oldobj;
}
u32 ObjDefManager::addRaw(ObjDef *obj)
{
size_t nobjects = m_objects.size();
if (nobjects >= OBJDEF_MAX_ITEMS)
return -1;
obj->index = nobjects;
// Ensure UID is nonzero so that a valid handle == OBJDEF_INVALID_HANDLE
// is not possible. The slight randomness bias isn't very significant.
obj->uid = myrand() & OBJDEF_UID_MASK;
if (obj->uid == 0)
obj->uid = 1;
m_objects.push_back(obj);
infostream << "ObjDefManager: added " << getObjectTitle()
<< ": name=\"" << obj->name
<< "\" index=" << obj->index
<< " uid=" << obj->uid
<< std::endl;
return nobjects;
}
ObjDef *ObjDefManager::getRaw(u32 index) const
{
return m_objects[index];
}
ObjDef *ObjDefManager::setRaw(u32 index, ObjDef *obj)
{
ObjDef *old_obj = m_objects[index];
m_objects[index] = obj;
return old_obj;
}
ObjDef *ObjDefManager::getByName(const std::string &name) const
{
for (size_t i = 0; i != m_objects.size(); i++) {
ObjDef *obj = m_objects[i];
if (obj && !strcasecmp(name.c_str(), obj->name.c_str()))
return obj;
}
return NULL;
}
void ObjDefManager::clear()
{
for (size_t i = 0; i != m_objects.size(); i++)
delete m_objects[i];
m_objects.clear();
}
u32 ObjDefManager::validateHandle(ObjDefHandle handle) const
{
ObjDefType type;
u32 index;
u32 uid;
bool is_valid =
(handle != OBJDEF_INVALID_HANDLE) &&
decodeHandle(handle, &index, &type, &uid) &&
(type == m_objtype) &&
(index < m_objects.size()) &&
(m_objects[index]->uid == uid);
return is_valid ? index : -1;
}
ObjDefHandle ObjDefManager::createHandle(u32 index, ObjDefType type, u32 uid)
{
ObjDefHandle handle = 0;
set_bits(&handle, 0, 18, index);
set_bits(&handle, 18, 6, type);
set_bits(&handle, 24, 7, uid);
u32 parity = calc_parity(handle);
set_bits(&handle, 31, 1, parity);
return handle ^ OBJDEF_HANDLE_SALT;
}
bool ObjDefManager::decodeHandle(ObjDefHandle handle, u32 *index,
ObjDefType *type, u32 *uid)
{
handle ^= OBJDEF_HANDLE_SALT;
u32 parity = get_bits(handle, 31, 1);
set_bits(&handle, 31, 1, 0);
if (parity != calc_parity(handle))
return false;
*index = get_bits(handle, 0, 18);
*type = (ObjDefType)get_bits(handle, 18, 6);
*uid = get_bits(handle, 24, 7);
return true;
}
| pgimeno/minetest | src/objdef.cpp | C++ | mit | 4,171 |
/*
Minetest
Copyright (C) 2010-2015 kwolekr, Ryan Kwolek <kwolekr@minetest.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "util/basic_macros.h"
#include "porting.h"
class IGameDef;
class NodeDefManager;
#define OBJDEF_INVALID_INDEX ((u32)(-1))
#define OBJDEF_INVALID_HANDLE 0
#define OBJDEF_HANDLE_SALT 0x00585e6fu
#define OBJDEF_MAX_ITEMS (1 << 18)
#define OBJDEF_UID_MASK ((1 << 7) - 1)
typedef u32 ObjDefHandle;
enum ObjDefType {
OBJDEF_GENERIC,
OBJDEF_BIOME,
OBJDEF_ORE,
OBJDEF_DECORATION,
OBJDEF_SCHEMATIC,
};
class ObjDef {
public:
virtual ~ObjDef() = default;
u32 index;
u32 uid;
ObjDefHandle handle;
std::string name;
};
// WARNING: Ownership of ObjDefs is transferred to the ObjDefManager it is
// added/set to. Note that ObjDefs managed by ObjDefManager are NOT refcounted,
// so the same ObjDef instance must not be referenced multiple
class ObjDefManager {
public:
ObjDefManager(IGameDef *gamedef, ObjDefType type);
virtual ~ObjDefManager();
DISABLE_CLASS_COPY(ObjDefManager);
virtual const char *getObjectTitle() const { return "ObjDef"; }
virtual void clear();
virtual ObjDef *getByName(const std::string &name) const;
//// Add new/get/set object definitions by handle
virtual ObjDefHandle add(ObjDef *obj);
virtual ObjDef *get(ObjDefHandle handle) const;
virtual ObjDef *set(ObjDefHandle handle, ObjDef *obj);
//// Raw variants that work on indexes
virtual u32 addRaw(ObjDef *obj);
// It is generally assumed that getRaw() will always return a valid object
// This won't be true if people do odd things such as call setRaw() with NULL
virtual ObjDef *getRaw(u32 index) const;
virtual ObjDef *setRaw(u32 index, ObjDef *obj);
size_t getNumObjects() const { return m_objects.size(); }
ObjDefType getType() const { return m_objtype; }
const NodeDefManager *getNodeDef() const { return m_ndef; }
u32 validateHandle(ObjDefHandle handle) const;
static ObjDefHandle createHandle(u32 index, ObjDefType type, u32 uid);
static bool decodeHandle(ObjDefHandle handle, u32 *index,
ObjDefType *type, u32 *uid);
protected:
const NodeDefManager *m_ndef;
std::vector<ObjDef *> m_objects;
ObjDefType m_objtype;
};
| pgimeno/minetest | src/objdef.h | C++ | mit | 2,852 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "object_properties.h"
#include "irrlichttypes_bloated.h"
#include "exceptions.h"
#include "util/serialize.h"
#include "util/basic_macros.h"
#include <sstream>
ObjectProperties::ObjectProperties()
{
textures.emplace_back("unknown_object.png");
colors.emplace_back(255,255,255,255);
}
std::string ObjectProperties::dump()
{
std::ostringstream os(std::ios::binary);
os << "hp_max=" << hp_max;
os << ", breath_max=" << breath_max;
os << ", physical=" << physical;
os << ", collideWithObjects=" << collideWithObjects;
os << ", weight=" << weight;
os << ", collisionbox=" << PP(collisionbox.MinEdge) << "," << PP(collisionbox.MaxEdge);
os << ", visual=" << visual;
os << ", mesh=" << mesh;
os << ", visual_size=" << PP(visual_size);
os << ", textures=[";
for (const std::string &texture : textures) {
os << "\"" << texture << "\" ";
}
os << "]";
os << ", colors=[";
for (const video::SColor &color : colors) {
os << "\"" << color.getAlpha() << "," << color.getRed() << ","
<< color.getGreen() << "," << color.getBlue() << "\" ";
}
os << "]";
os << ", spritediv=" << PP2(spritediv);
os << ", initial_sprite_basepos=" << PP2(initial_sprite_basepos);
os << ", is_visible=" << is_visible;
os << ", makes_footstep_sound=" << makes_footstep_sound;
os << ", automatic_rotate="<< automatic_rotate;
os << ", backface_culling="<< backface_culling;
os << ", glow=" << glow;
os << ", nametag=" << nametag;
os << ", nametag_color=" << "\"" << nametag_color.getAlpha() << "," << nametag_color.getRed()
<< "," << nametag_color.getGreen() << "," << nametag_color.getBlue() << "\" ";
os << ", selectionbox=" << PP(selectionbox.MinEdge) << "," << PP(selectionbox.MaxEdge);
os << ", pointable=" << pointable;
os << ", static_save=" << static_save;
os << ", eye_height=" << eye_height;
os << ", zoom_fov=" << zoom_fov;
os << ", use_texture_alpha=" << use_texture_alpha;
return os.str();
}
void ObjectProperties::serialize(std::ostream &os) const
{
writeU8(os, 4); // PROTOCOL_VERSION >= 37
writeU16(os, hp_max);
writeU8(os, physical);
writeF32(os, weight);
writeV3F32(os, collisionbox.MinEdge);
writeV3F32(os, collisionbox.MaxEdge);
writeV3F32(os, selectionbox.MinEdge);
writeV3F32(os, selectionbox.MaxEdge);
writeU8(os, pointable);
os << serializeString(visual);
writeV3F32(os, visual_size);
writeU16(os, textures.size());
for (const std::string &texture : textures) {
os << serializeString(texture);
}
writeV2S16(os, spritediv);
writeV2S16(os, initial_sprite_basepos);
writeU8(os, is_visible);
writeU8(os, makes_footstep_sound);
writeF32(os, automatic_rotate);
// Added in protocol version 14
os << serializeString(mesh);
writeU16(os, colors.size());
for (video::SColor color : colors) {
writeARGB8(os, color);
}
writeU8(os, collideWithObjects);
writeF32(os, stepheight);
writeU8(os, automatic_face_movement_dir);
writeF32(os, automatic_face_movement_dir_offset);
writeU8(os, backface_culling);
os << serializeString(nametag);
writeARGB8(os, nametag_color);
writeF32(os, automatic_face_movement_max_rotation_per_sec);
os << serializeString(infotext);
os << serializeString(wield_item);
writeS8(os, glow);
writeU16(os, breath_max);
writeF32(os, eye_height);
writeF32(os, zoom_fov);
writeU8(os, use_texture_alpha);
// Add stuff only at the bottom.
// Never remove anything, because we don't want new versions of this
}
void ObjectProperties::deSerialize(std::istream &is)
{
int version = readU8(is);
if (version != 4)
throw SerializationError("unsupported ObjectProperties version");
hp_max = readU16(is);
physical = readU8(is);
weight = readF32(is);
collisionbox.MinEdge = readV3F32(is);
collisionbox.MaxEdge = readV3F32(is);
selectionbox.MinEdge = readV3F32(is);
selectionbox.MaxEdge = readV3F32(is);
pointable = readU8(is);
visual = deSerializeString(is);
visual_size = readV3F32(is);
textures.clear();
u32 texture_count = readU16(is);
for (u32 i = 0; i < texture_count; i++){
textures.push_back(deSerializeString(is));
}
spritediv = readV2S16(is);
initial_sprite_basepos = readV2S16(is);
is_visible = readU8(is);
makes_footstep_sound = readU8(is);
automatic_rotate = readF32(is);
mesh = deSerializeString(is);
colors.clear();
u32 color_count = readU16(is);
for (u32 i = 0; i < color_count; i++){
colors.push_back(readARGB8(is));
}
collideWithObjects = readU8(is);
stepheight = readF32(is);
automatic_face_movement_dir = readU8(is);
automatic_face_movement_dir_offset = readF32(is);
backface_culling = readU8(is);
nametag = deSerializeString(is);
nametag_color = readARGB8(is);
automatic_face_movement_max_rotation_per_sec = readF32(is);
infotext = deSerializeString(is);
wield_item = deSerializeString(is);
glow = readS8(is);
breath_max = readU16(is);
eye_height = readF32(is);
zoom_fov = readF32(is);
use_texture_alpha = readU8(is);
}
| pgimeno/minetest | src/object_properties.cpp | C++ | mit | 5,652 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include <string>
#include "irrlichttypes_bloated.h"
#include <iostream>
#include <map>
#include <vector>
struct ObjectProperties
{
u16 hp_max = 1;
u16 breath_max = 0;
bool physical = false;
bool collideWithObjects = true;
float weight = 5.0f;
// Values are BS=1
aabb3f collisionbox = aabb3f(-0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f);
aabb3f selectionbox = aabb3f(-0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f);
bool pointable = true;
std::string visual = "sprite";
std::string mesh = "";
v3f visual_size = v3f(1, 1, 1);
std::vector<std::string> textures;
std::vector<video::SColor> colors;
v2s16 spritediv = v2s16(1, 1);
v2s16 initial_sprite_basepos;
bool is_visible = true;
bool makes_footstep_sound = false;
f32 stepheight = 0.0f;
float automatic_rotate = 0.0f;
bool automatic_face_movement_dir = false;
f32 automatic_face_movement_dir_offset = 0.0f;
bool backface_culling = true;
s8 glow = 0;
std::string nametag = "";
video::SColor nametag_color = video::SColor(255, 255, 255, 255);
f32 automatic_face_movement_max_rotation_per_sec = -1.0f;
std::string infotext;
//! For dropped items, this contains item information.
std::string wield_item;
bool static_save = true;
float eye_height = 1.625f;
float zoom_fov = 0.0f;
bool use_texture_alpha = false;
ObjectProperties();
std::string dump();
void serialize(std::ostream &os) const;
void deSerialize(std::istream &is);
};
| pgimeno/minetest | src/object_properties.h | C++ | mit | 2,201 |
/*
Minetest
Copyright (C) 2013 sapier, sapier at gmx dot net
Copyright (C) 2016 est31, <MTest31@outlook.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/******************************************************************************/
/* Includes */
/******************************************************************************/
#include "pathfinder.h"
#include "serverenvironment.h"
#include "server.h"
#include "nodedef.h"
//#define PATHFINDER_DEBUG
//#define PATHFINDER_CALC_TIME
#ifdef PATHFINDER_DEBUG
#include <string>
#endif
#ifdef PATHFINDER_DEBUG
#include <iomanip>
#endif
#ifdef PATHFINDER_CALC_TIME
#include <sys/time.h>
#endif
/******************************************************************************/
/* Typedefs and macros */
/******************************************************************************/
#define LVL "(" << level << ")" <<
#ifdef PATHFINDER_DEBUG
#define DEBUG_OUT(a) std::cout << a
#define INFO_TARGET std::cout
#define VERBOSE_TARGET std::cout
#define ERROR_TARGET std::cout
#else
#define DEBUG_OUT(a) while(0)
#define INFO_TARGET infostream << "Pathfinder: "
#define VERBOSE_TARGET verbosestream << "Pathfinder: "
#define ERROR_TARGET warningstream << "Pathfinder: "
#endif
/******************************************************************************/
/* Class definitions */
/******************************************************************************/
/** representation of cost in specific direction */
class PathCost {
public:
/** default constructor */
PathCost() = default;
/** copy constructor */
PathCost(const PathCost &b);
/** assignment operator */
PathCost &operator= (const PathCost &b);
bool valid = false; /**< movement is possible */
int value = 0; /**< cost of movement */
int direction = 0; /**< y-direction of movement */
bool updated = false; /**< this cost has ben calculated */
};
/** representation of a mapnode to be used for pathfinding */
class PathGridnode {
public:
/** default constructor */
PathGridnode() = default;
/** copy constructor */
PathGridnode(const PathGridnode &b);
/**
* assignment operator
* @param b node to copy
*/
PathGridnode &operator= (const PathGridnode &b);
/**
* read cost in a specific direction
* @param dir direction of cost to fetch
*/
PathCost getCost(v3s16 dir);
/**
* set cost value for movement
* @param dir direction to set cost for
* @cost cost to set
*/
void setCost(v3s16 dir, const PathCost &cost);
bool valid = false; /**< node is on surface */
bool target = false; /**< node is target position */
bool source = false; /**< node is stating position */
int totalcost = -1; /**< cost to move here from starting point */
v3s16 sourcedir; /**< origin of movement for current cost */
v3s16 pos; /**< real position of node */
PathCost directions[4]; /**< cost in different directions */
/* debug values */
bool is_element = false; /**< node is element of path detected */
char type = 'u'; /**< type of node */
};
class Pathfinder;
/** Abstract class to manage the map data */
class GridNodeContainer {
public:
virtual PathGridnode &access(v3s16 p)=0;
virtual ~GridNodeContainer() = default;
protected:
Pathfinder *m_pathf;
void initNode(v3s16 ipos, PathGridnode *p_node);
};
class ArrayGridNodeContainer : public GridNodeContainer {
public:
virtual ~ArrayGridNodeContainer() = default;
ArrayGridNodeContainer(Pathfinder *pathf, v3s16 dimensions);
virtual PathGridnode &access(v3s16 p);
private:
v3s16 m_dimensions;
int m_x_stride;
int m_y_stride;
std::vector<PathGridnode> m_nodes_array;
};
class MapGridNodeContainer : public GridNodeContainer {
public:
virtual ~MapGridNodeContainer() = default;
MapGridNodeContainer(Pathfinder *pathf);
virtual PathGridnode &access(v3s16 p);
private:
std::map<v3s16, PathGridnode> m_nodes;
};
/** class doing pathfinding */
class Pathfinder {
public:
/**
* default constructor
*/
Pathfinder() = default;
~Pathfinder();
/**
* path evaluation function
* @param env environment to look for path
* @param source origin of path
* @param destination end position of path
* @param searchdistance maximum number of nodes to look in each direction
* @param max_jump maximum number of blocks a path may jump up
* @param max_drop maximum number of blocks a path may drop
* @param algo Algorithm to use for finding a path
*/
std::vector<v3s16> getPath(ServerEnvironment *env,
v3s16 source,
v3s16 destination,
unsigned int searchdistance,
unsigned int max_jump,
unsigned int max_drop,
PathAlgorithm algo);
private:
/* helper functions */
/**
* transform index pos to mappos
* @param ipos a index position
* @return map position
*/
v3s16 getRealPos(v3s16 ipos);
/**
* transform mappos to index pos
* @param pos a real pos
* @return index position
*/
v3s16 getIndexPos(v3s16 pos);
/**
* get gridnode at a specific index position
* @param ipos index position
* @return gridnode for index
*/
PathGridnode &getIndexElement(v3s16 ipos);
/**
* Get gridnode at a specific index position
* @return gridnode for index
*/
PathGridnode &getIdxElem(s16 x, s16 y, s16 z);
/**
* invert a 3d position
* @param pos 3d position
* @return pos *-1
*/
v3s16 invert(v3s16 pos);
/**
* check if a index is within current search area
* @param index position to validate
* @return true/false
*/
bool isValidIndex(v3s16 index);
/**
* translate position to float position
* @param pos integer position
* @return float position
*/
v3f tov3f(v3s16 pos);
/* algorithm functions */
/**
* calculate 2d manahttan distance to target on the xz plane
* @param pos position to calc distance
* @return integer distance
*/
int getXZManhattanDist(v3s16 pos);
/**
* get best direction based uppon heuristics
* @param directions list of unchecked directions
* @param g_pos mapnode to start from
* @return direction to check
*/
v3s16 getDirHeuristic(std::vector<v3s16> &directions, PathGridnode &g_pos);
/**
* build internal data representation of search area
* @return true/false if costmap creation was successfull
*/
bool buildCostmap();
/**
* calculate cost of movement
* @param pos real world position to start movement
* @param dir direction to move to
* @return cost information
*/
PathCost calcCost(v3s16 pos, v3s16 dir);
/**
* recursive update whole search areas total cost information
* @param ipos position to check next
* @param srcdir positionc checked last time
* @param total_cost cost of moving to ipos
* @param level current recursion depth
* @return true/false path to destination has been found
*/
bool updateAllCosts(v3s16 ipos, v3s16 srcdir, int current_cost, int level);
/**
* recursive try to find a patrh to destionation
* @param ipos position to check next
* @param srcdir positionc checked last time
* @param total_cost cost of moving to ipos
* @param level current recursion depth
* @return true/false path to destination has been found
*/
bool updateCostHeuristic(v3s16 ipos, v3s16 srcdir, int current_cost, int level);
/**
* recursive build a vector containing all nodes from source to destination
* @param path vector to add nodes to
* @param pos pos to check next
* @param level recursion depth
*/
void buildPath(std::vector<v3s16> &path, v3s16 pos, int level);
/* variables */
int m_max_index_x = 0; /**< max index of search area in x direction */
int m_max_index_y = 0; /**< max index of search area in y direction */
int m_max_index_z = 0; /**< max index of search area in z direction */
int m_searchdistance = 0; /**< max distance to search in each direction */
int m_maxdrop = 0; /**< maximum number of blocks a path may drop */
int m_maxjump = 0; /**< maximum number of blocks a path may jump */
int m_min_target_distance = 0; /**< current smalest path to target */
bool m_prefetch = true; /**< prefetch cost data */
v3s16 m_start; /**< source position */
v3s16 m_destination; /**< destination position */
core::aabbox3d<s16> m_limits; /**< position limits in real map coordinates */
/** contains all map data already collected and analyzed.
Access it via the getIndexElement/getIdxElem methods. */
friend class GridNodeContainer;
GridNodeContainer *m_nodes_container = nullptr;
ServerEnvironment *m_env = 0; /**< minetest environment pointer */
#ifdef PATHFINDER_DEBUG
/**
* print collected cost information
*/
void printCost();
/**
* print collected cost information in a specific direction
* @param dir direction to print
*/
void printCost(PathDirections dir);
/**
* print type of node as evaluated
*/
void printType();
/**
* print pathlenght for all nodes in search area
*/
void printPathLen();
/**
* print a path
* @param path path to show
*/
void printPath(std::vector<v3s16> path);
/**
* print y direction for all movements
*/
void printYdir();
/**
* print y direction for moving in a specific direction
* @param dir direction to show data
*/
void printYdir(PathDirections dir);
/**
* helper function to translate a direction to speaking text
* @param dir direction to translate
* @return textual name of direction
*/
std::string dirToName(PathDirections dir);
#endif
};
/******************************************************************************/
/* implementation */
/******************************************************************************/
std::vector<v3s16> get_path(ServerEnvironment* env,
v3s16 source,
v3s16 destination,
unsigned int searchdistance,
unsigned int max_jump,
unsigned int max_drop,
PathAlgorithm algo)
{
Pathfinder searchclass;
return searchclass.getPath(env,
source, destination,
searchdistance, max_jump, max_drop, algo);
}
/******************************************************************************/
PathCost::PathCost(const PathCost &b)
{
valid = b.valid;
direction = b.direction;
value = b.value;
updated = b.updated;
}
/******************************************************************************/
PathCost &PathCost::operator= (const PathCost &b)
{
valid = b.valid;
direction = b.direction;
value = b.value;
updated = b.updated;
return *this;
}
/******************************************************************************/
PathGridnode::PathGridnode(const PathGridnode &b)
: valid(b.valid),
target(b.target),
source(b.source),
totalcost(b.totalcost),
sourcedir(b.sourcedir),
pos(b.pos),
is_element(b.is_element),
type(b.type)
{
directions[DIR_XP] = b.directions[DIR_XP];
directions[DIR_XM] = b.directions[DIR_XM];
directions[DIR_ZP] = b.directions[DIR_ZP];
directions[DIR_ZM] = b.directions[DIR_ZM];
}
/******************************************************************************/
PathGridnode &PathGridnode::operator= (const PathGridnode &b)
{
valid = b.valid;
target = b.target;
source = b.source;
is_element = b.is_element;
totalcost = b.totalcost;
sourcedir = b.sourcedir;
pos = b.pos;
type = b.type;
directions[DIR_XP] = b.directions[DIR_XP];
directions[DIR_XM] = b.directions[DIR_XM];
directions[DIR_ZP] = b.directions[DIR_ZP];
directions[DIR_ZM] = b.directions[DIR_ZM];
return *this;
}
/******************************************************************************/
PathCost PathGridnode::getCost(v3s16 dir)
{
if (dir.X > 0) {
return directions[DIR_XP];
}
if (dir.X < 0) {
return directions[DIR_XM];
}
if (dir.Z > 0) {
return directions[DIR_ZP];
}
if (dir.Z < 0) {
return directions[DIR_ZM];
}
PathCost retval;
return retval;
}
/******************************************************************************/
void PathGridnode::setCost(v3s16 dir, const PathCost &cost)
{
if (dir.X > 0) {
directions[DIR_XP] = cost;
}
if (dir.X < 0) {
directions[DIR_XM] = cost;
}
if (dir.Z > 0) {
directions[DIR_ZP] = cost;
}
if (dir.Z < 0) {
directions[DIR_ZM] = cost;
}
}
void GridNodeContainer::initNode(v3s16 ipos, PathGridnode *p_node)
{
const NodeDefManager *ndef = m_pathf->m_env->getGameDef()->ndef();
PathGridnode &elem = *p_node;
v3s16 realpos = m_pathf->getRealPos(ipos);
MapNode current = m_pathf->m_env->getMap().getNodeNoEx(realpos);
MapNode below = m_pathf->m_env->getMap().getNodeNoEx(realpos + v3s16(0, -1, 0));
if ((current.param0 == CONTENT_IGNORE) ||
(below.param0 == CONTENT_IGNORE)) {
DEBUG_OUT("Pathfinder: " << PP(realpos) <<
" current or below is invalid element" << std::endl);
if (current.param0 == CONTENT_IGNORE) {
elem.type = 'i';
DEBUG_OUT(PP(ipos) << ": " << 'i' << std::endl);
}
return;
}
//don't add anything if it isn't an air node
if (ndef->get(current).walkable || !ndef->get(below).walkable) {
DEBUG_OUT("Pathfinder: " << PP(realpos)
<< " not on surface" << std::endl);
if (ndef->get(current).walkable) {
elem.type = 's';
DEBUG_OUT(PP(ipos) << ": " << 's' << std::endl);
} else {
elem.type = '-';
DEBUG_OUT(PP(ipos) << ": " << '-' << std::endl);
}
return;
}
elem.valid = true;
elem.pos = realpos;
elem.type = 'g';
DEBUG_OUT(PP(ipos) << ": " << 'a' << std::endl);
if (m_pathf->m_prefetch) {
elem.directions[DIR_XP] = m_pathf->calcCost(realpos, v3s16( 1, 0, 0));
elem.directions[DIR_XM] = m_pathf->calcCost(realpos, v3s16(-1, 0, 0));
elem.directions[DIR_ZP] = m_pathf->calcCost(realpos, v3s16( 0, 0, 1));
elem.directions[DIR_ZM] = m_pathf->calcCost(realpos, v3s16( 0, 0,-1));
}
}
ArrayGridNodeContainer::ArrayGridNodeContainer(Pathfinder *pathf, v3s16 dimensions) :
m_x_stride(dimensions.Y * dimensions.Z),
m_y_stride(dimensions.Z)
{
m_pathf = pathf;
m_nodes_array.resize(dimensions.X * dimensions.Y * dimensions.Z);
INFO_TARGET << "Pathfinder ArrayGridNodeContainer constructor." << std::endl;
for (int x = 0; x < dimensions.X; x++) {
for (int y = 0; y < dimensions.Y; y++) {
for (int z= 0; z < dimensions.Z; z++) {
v3s16 ipos(x, y, z);
initNode(ipos, &access(ipos));
}
}
}
}
PathGridnode &ArrayGridNodeContainer::access(v3s16 p)
{
return m_nodes_array[p.X * m_x_stride + p.Y * m_y_stride + p.Z];
}
MapGridNodeContainer::MapGridNodeContainer(Pathfinder *pathf)
{
m_pathf = pathf;
}
PathGridnode &MapGridNodeContainer::access(v3s16 p)
{
std::map<v3s16, PathGridnode>::iterator it = m_nodes.find(p);
if (it != m_nodes.end()) {
return it->second;
}
PathGridnode &n = m_nodes[p];
initNode(p, &n);
return n;
}
/******************************************************************************/
std::vector<v3s16> Pathfinder::getPath(ServerEnvironment *env,
v3s16 source,
v3s16 destination,
unsigned int searchdistance,
unsigned int max_jump,
unsigned int max_drop,
PathAlgorithm algo)
{
#ifdef PATHFINDER_CALC_TIME
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
#endif
std::vector<v3s16> retval;
//check parameters
if (env == 0) {
ERROR_TARGET << "missing environment pointer" << std::endl;
return retval;
}
m_searchdistance = searchdistance;
m_env = env;
m_maxjump = max_jump;
m_maxdrop = max_drop;
m_start = source;
m_destination = destination;
m_min_target_distance = -1;
m_prefetch = true;
if (algo == PA_PLAIN_NP) {
m_prefetch = false;
}
int min_x = MYMIN(source.X, destination.X);
int max_x = MYMAX(source.X, destination.X);
int min_y = MYMIN(source.Y, destination.Y);
int max_y = MYMAX(source.Y, destination.Y);
int min_z = MYMIN(source.Z, destination.Z);
int max_z = MYMAX(source.Z, destination.Z);
m_limits.MinEdge.X = min_x - searchdistance;
m_limits.MinEdge.Y = min_y - searchdistance;
m_limits.MinEdge.Z = min_z - searchdistance;
m_limits.MaxEdge.X = max_x + searchdistance;
m_limits.MaxEdge.Y = max_y + searchdistance;
m_limits.MaxEdge.Z = max_z + searchdistance;
v3s16 diff = m_limits.MaxEdge - m_limits.MinEdge;
m_max_index_x = diff.X;
m_max_index_y = diff.Y;
m_max_index_z = diff.Z;
delete m_nodes_container;
if (diff.getLength() > 5) {
m_nodes_container = new MapGridNodeContainer(this);
} else {
m_nodes_container = new ArrayGridNodeContainer(this, diff);
}
#ifdef PATHFINDER_DEBUG
printType();
printCost();
printYdir();
#endif
//validate and mark start and end pos
v3s16 StartIndex = getIndexPos(source);
v3s16 EndIndex = getIndexPos(destination);
PathGridnode &startpos = getIndexElement(StartIndex);
PathGridnode &endpos = getIndexElement(EndIndex);
if (!startpos.valid) {
VERBOSE_TARGET << "invalid startpos" <<
"Index: " << PP(StartIndex) <<
"Realpos: " << PP(getRealPos(StartIndex)) << std::endl;
return retval;
}
if (!endpos.valid) {
VERBOSE_TARGET << "invalid stoppos" <<
"Index: " << PP(EndIndex) <<
"Realpos: " << PP(getRealPos(EndIndex)) << std::endl;
return retval;
}
endpos.target = true;
startpos.source = true;
startpos.totalcost = 0;
bool update_cost_retval = false;
switch (algo) {
case PA_DIJKSTRA:
update_cost_retval = updateAllCosts(StartIndex, v3s16(0, 0, 0), 0, 0);
break;
case PA_PLAIN_NP:
case PA_PLAIN:
update_cost_retval = updateCostHeuristic(StartIndex, v3s16(0, 0, 0), 0, 0);
break;
default:
ERROR_TARGET << "missing PathAlgorithm"<< std::endl;
break;
}
if (update_cost_retval) {
#ifdef PATHFINDER_DEBUG
std::cout << "Path to target found!" << std::endl;
printPathLen();
#endif
//find path
std::vector<v3s16> path;
buildPath(path, EndIndex, 0);
#ifdef PATHFINDER_DEBUG
std::cout << "Full index path:" << std::endl;
printPath(path);
#endif
//finalize path
std::vector<v3s16> full_path;
full_path.reserve(path.size());
for (const v3s16 &i : path) {
full_path.push_back(getIndexElement(i).pos);
}
#ifdef PATHFINDER_DEBUG
std::cout << "full path:" << std::endl;
printPath(full_path);
#endif
#ifdef PATHFINDER_CALC_TIME
timespec ts2;
clock_gettime(CLOCK_REALTIME, &ts2);
int ms = (ts2.tv_nsec - ts.tv_nsec)/(1000*1000);
int us = ((ts2.tv_nsec - ts.tv_nsec) - (ms*1000*1000))/1000;
int ns = ((ts2.tv_nsec - ts.tv_nsec) - ( (ms*1000*1000) + (us*1000)));
std::cout << "Calculating path took: " << (ts2.tv_sec - ts.tv_sec) <<
"s " << ms << "ms " << us << "us " << ns << "ns " << std::endl;
#endif
return full_path;
}
else {
#ifdef PATHFINDER_DEBUG
printPathLen();
#endif
ERROR_TARGET << "failed to update cost map"<< std::endl;
}
//return
return retval;
}
Pathfinder::~Pathfinder()
{
delete m_nodes_container;
}
/******************************************************************************/
v3s16 Pathfinder::getRealPos(v3s16 ipos)
{
return m_limits.MinEdge + ipos;
}
/******************************************************************************/
PathCost Pathfinder::calcCost(v3s16 pos, v3s16 dir)
{
const NodeDefManager *ndef = m_env->getGameDef()->ndef();
PathCost retval;
retval.updated = true;
v3s16 pos2 = pos + dir;
//check limits
if (!m_limits.isPointInside(pos2)) {
DEBUG_OUT("Pathfinder: " << PP(pos2) <<
" no cost -> out of limits" << std::endl);
return retval;
}
MapNode node_at_pos2 = m_env->getMap().getNodeNoEx(pos2);
//did we get information about node?
if (node_at_pos2.param0 == CONTENT_IGNORE ) {
VERBOSE_TARGET << "Pathfinder: (1) area at pos: "
<< PP(pos2) << " not loaded";
return retval;
}
if (!ndef->get(node_at_pos2).walkable) {
MapNode node_below_pos2 =
m_env->getMap().getNodeNoEx(pos2 + v3s16(0, -1, 0));
//did we get information about node?
if (node_below_pos2.param0 == CONTENT_IGNORE ) {
VERBOSE_TARGET << "Pathfinder: (2) area at pos: "
<< PP((pos2 + v3s16(0, -1, 0))) << " not loaded";
return retval;
}
if (ndef->get(node_below_pos2).walkable) {
retval.valid = true;
retval.value = 1;
retval.direction = 0;
DEBUG_OUT("Pathfinder: "<< PP(pos)
<< " cost same height found" << std::endl);
}
else {
v3s16 testpos = pos2 - v3s16(0, -1, 0);
MapNode node_at_pos = m_env->getMap().getNodeNoEx(testpos);
while ((node_at_pos.param0 != CONTENT_IGNORE) &&
(!ndef->get(node_at_pos).walkable) &&
(testpos.Y > m_limits.MinEdge.Y)) {
testpos += v3s16(0, -1, 0);
node_at_pos = m_env->getMap().getNodeNoEx(testpos);
}
//did we find surface?
if ((testpos.Y >= m_limits.MinEdge.Y) &&
(node_at_pos.param0 != CONTENT_IGNORE) &&
(ndef->get(node_at_pos).walkable)) {
if ((pos2.Y - testpos.Y - 1) <= m_maxdrop) {
retval.valid = true;
retval.value = 2;
//difference of y-pos +1 (target node is ABOVE solid node)
retval.direction = ((testpos.Y - pos2.Y) +1);
DEBUG_OUT("Pathfinder cost below height found" << std::endl);
}
else {
INFO_TARGET << "Pathfinder:"
" distance to surface below to big: "
<< (testpos.Y - pos2.Y) << " max: " << m_maxdrop
<< std::endl;
}
}
else {
DEBUG_OUT("Pathfinder: no surface below found" << std::endl);
}
}
}
else {
v3s16 testpos = pos2;
MapNode node_at_pos = m_env->getMap().getNodeNoEx(testpos);
while ((node_at_pos.param0 != CONTENT_IGNORE) &&
(ndef->get(node_at_pos).walkable) &&
(testpos.Y < m_limits.MaxEdge.Y)) {
testpos += v3s16(0, 1, 0);
node_at_pos = m_env->getMap().getNodeNoEx(testpos);
}
//did we find surface?
if ((testpos.Y <= m_limits.MaxEdge.Y) &&
(!ndef->get(node_at_pos).walkable)) {
if (testpos.Y - pos2.Y <= m_maxjump) {
retval.valid = true;
retval.value = 2;
retval.direction = (testpos.Y - pos2.Y);
DEBUG_OUT("Pathfinder cost above found" << std::endl);
}
else {
DEBUG_OUT("Pathfinder: distance to surface above to big: "
<< (testpos.Y - pos2.Y) << " max: " << m_maxjump
<< std::endl);
}
}
else {
DEBUG_OUT("Pathfinder: no surface above found" << std::endl);
}
}
return retval;
}
/******************************************************************************/
v3s16 Pathfinder::getIndexPos(v3s16 pos)
{
return pos - m_limits.MinEdge;
}
/******************************************************************************/
PathGridnode &Pathfinder::getIndexElement(v3s16 ipos)
{
return m_nodes_container->access(ipos);
}
/******************************************************************************/
inline PathGridnode &Pathfinder::getIdxElem(s16 x, s16 y, s16 z)
{
return m_nodes_container->access(v3s16(x,y,z));
}
/******************************************************************************/
bool Pathfinder::isValidIndex(v3s16 index)
{
if ( (index.X < m_max_index_x) &&
(index.Y < m_max_index_y) &&
(index.Z < m_max_index_z) &&
(index.X >= 0) &&
(index.Y >= 0) &&
(index.Z >= 0))
return true;
return false;
}
/******************************************************************************/
v3s16 Pathfinder::invert(v3s16 pos)
{
v3s16 retval = pos;
retval.X *=-1;
retval.Y *=-1;
retval.Z *=-1;
return retval;
}
/******************************************************************************/
bool Pathfinder::updateAllCosts(v3s16 ipos,
v3s16 srcdir,
int current_cost,
int level)
{
PathGridnode &g_pos = getIndexElement(ipos);
g_pos.totalcost = current_cost;
g_pos.sourcedir = srcdir;
level ++;
//check if target has been found
if (g_pos.target) {
m_min_target_distance = current_cost;
DEBUG_OUT(LVL " Pathfinder: target found!" << std::endl);
return true;
}
bool retval = false;
std::vector<v3s16> directions;
directions.emplace_back(1,0, 0);
directions.emplace_back(-1,0, 0);
directions.emplace_back(0,0, 1);
directions.emplace_back(0,0,-1);
for (v3s16 &direction : directions) {
if (direction != srcdir) {
PathCost cost = g_pos.getCost(direction);
if (cost.valid) {
direction.Y = cost.direction;
v3s16 ipos2 = ipos + direction;
if (!isValidIndex(ipos2)) {
DEBUG_OUT(LVL " Pathfinder: " << PP(ipos2) <<
" out of range, max=" << PP(m_limits.MaxEdge) << std::endl);
continue;
}
PathGridnode &g_pos2 = getIndexElement(ipos2);
if (!g_pos2.valid) {
VERBOSE_TARGET << LVL "Pathfinder: no data for new position: "
<< PP(ipos2) << std::endl;
continue;
}
assert(cost.value > 0);
int new_cost = current_cost + cost.value;
// check if there already is a smaller path
if ((m_min_target_distance > 0) &&
(m_min_target_distance < new_cost)) {
return false;
}
if ((g_pos2.totalcost < 0) ||
(g_pos2.totalcost > new_cost)) {
DEBUG_OUT(LVL "Pathfinder: updating path at: "<<
PP(ipos2) << " from: " << g_pos2.totalcost << " to "<<
new_cost << std::endl);
if (updateAllCosts(ipos2, invert(direction),
new_cost, level)) {
retval = true;
}
}
else {
DEBUG_OUT(LVL "Pathfinder:"
" already found shorter path to: "
<< PP(ipos2) << std::endl);
}
}
else {
DEBUG_OUT(LVL "Pathfinder:"
" not moving to invalid direction: "
<< PP(directions[i]) << std::endl);
}
}
}
return retval;
}
/******************************************************************************/
int Pathfinder::getXZManhattanDist(v3s16 pos)
{
int min_x = MYMIN(pos.X, m_destination.X);
int max_x = MYMAX(pos.X, m_destination.X);
int min_z = MYMIN(pos.Z, m_destination.Z);
int max_z = MYMAX(pos.Z, m_destination.Z);
return (max_x - min_x) + (max_z - min_z);
}
/******************************************************************************/
v3s16 Pathfinder::getDirHeuristic(std::vector<v3s16> &directions, PathGridnode &g_pos)
{
int minscore = -1;
v3s16 retdir = v3s16(0, 0, 0);
v3s16 srcpos = g_pos.pos;
DEBUG_OUT("Pathfinder: remaining dirs at beginning:"
<< directions.size() << std::endl);
for (v3s16 &direction : directions) {
v3s16 pos1 = v3s16(srcpos.X + direction.X, 0, srcpos.Z+ direction.Z);
int cur_manhattan = getXZManhattanDist(pos1);
PathCost cost = g_pos.getCost(direction);
if (!cost.updated) {
cost = calcCost(g_pos.pos, direction);
g_pos.setCost(direction, cost);
}
if (cost.valid) {
int score = cost.value + cur_manhattan;
if ((minscore < 0)|| (score < minscore)) {
minscore = score;
retdir = direction;
}
}
}
if (retdir != v3s16(0, 0, 0)) {
for (std::vector<v3s16>::iterator iter = directions.begin();
iter != directions.end();
++iter) {
if(*iter == retdir) {
DEBUG_OUT("Pathfinder: removing return direction" << std::endl);
directions.erase(iter);
break;
}
}
}
else {
DEBUG_OUT("Pathfinder: didn't find any valid direction clearing"
<< std::endl);
directions.clear();
}
DEBUG_OUT("Pathfinder: remaining dirs at end:" << directions.size()
<< std::endl);
return retdir;
}
/******************************************************************************/
bool Pathfinder::updateCostHeuristic( v3s16 ipos,
v3s16 srcdir,
int current_cost,
int level)
{
PathGridnode &g_pos = getIndexElement(ipos);
g_pos.totalcost = current_cost;
g_pos.sourcedir = srcdir;
level ++;
//check if target has been found
if (g_pos.target) {
m_min_target_distance = current_cost;
DEBUG_OUT(LVL " Pathfinder: target found!" << std::endl);
return true;
}
bool retval = false;
std::vector<v3s16> directions;
directions.emplace_back(1, 0, 0);
directions.emplace_back(-1, 0, 0);
directions.emplace_back(0, 0, 1);
directions.emplace_back(0, 0, -1);
v3s16 direction = getDirHeuristic(directions, g_pos);
while (direction != v3s16(0, 0, 0) && (!retval)) {
if (direction != srcdir) {
PathCost cost = g_pos.getCost(direction);
if (cost.valid) {
direction.Y = cost.direction;
v3s16 ipos2 = ipos + direction;
if (!isValidIndex(ipos2)) {
DEBUG_OUT(LVL " Pathfinder: " << PP(ipos2) <<
" out of range, max=" << PP(m_limits.MaxEdge) << std::endl);
direction = getDirHeuristic(directions, g_pos);
continue;
}
PathGridnode &g_pos2 = getIndexElement(ipos2);
if (!g_pos2.valid) {
VERBOSE_TARGET << LVL "Pathfinder: no data for new position: "
<< PP(ipos2) << std::endl;
direction = getDirHeuristic(directions, g_pos);
continue;
}
assert(cost.value > 0);
int new_cost = current_cost + cost.value;
// check if there already is a smaller path
if ((m_min_target_distance > 0) &&
(m_min_target_distance < new_cost)) {
DEBUG_OUT(LVL "Pathfinder:"
" already longer than best already found path "
<< PP(ipos2) << std::endl);
return false;
}
if ((g_pos2.totalcost < 0) ||
(g_pos2.totalcost > new_cost)) {
DEBUG_OUT(LVL "Pathfinder: updating path at: "<<
PP(ipos2) << " from: " << g_pos2.totalcost << " to "<<
new_cost << " srcdir=" <<
PP(invert(direction))<< std::endl);
if (updateCostHeuristic(ipos2, invert(direction),
new_cost, level)) {
retval = true;
}
}
else {
DEBUG_OUT(LVL "Pathfinder:"
" already found shorter path to: "
<< PP(ipos2) << std::endl);
}
}
else {
DEBUG_OUT(LVL "Pathfinder:"
" not moving to invalid direction: "
<< PP(direction) << std::endl);
}
}
else {
DEBUG_OUT(LVL "Pathfinder:"
" skipping srcdir: "
<< PP(direction) << std::endl);
}
direction = getDirHeuristic(directions, g_pos);
}
return retval;
}
/******************************************************************************/
void Pathfinder::buildPath(std::vector<v3s16> &path, v3s16 pos, int level)
{
level ++;
if (level > 700) {
ERROR_TARGET
<< LVL "Pathfinder: path is too long aborting" << std::endl;
return;
}
PathGridnode &g_pos = getIndexElement(pos);
if (!g_pos.valid) {
ERROR_TARGET
<< LVL "Pathfinder: invalid next pos detected aborting" << std::endl;
return;
}
g_pos.is_element = true;
//check if source reached
if (g_pos.source) {
path.push_back(pos);
return;
}
buildPath(path, pos + g_pos.sourcedir, level);
path.push_back(pos);
}
/******************************************************************************/
v3f Pathfinder::tov3f(v3s16 pos)
{
return v3f(BS * pos.X, BS * pos.Y, BS * pos.Z);
}
#ifdef PATHFINDER_DEBUG
/******************************************************************************/
void Pathfinder::printCost()
{
printCost(DIR_XP);
printCost(DIR_XM);
printCost(DIR_ZP);
printCost(DIR_ZM);
}
/******************************************************************************/
void Pathfinder::printYdir()
{
printYdir(DIR_XP);
printYdir(DIR_XM);
printYdir(DIR_ZP);
printYdir(DIR_ZM);
}
/******************************************************************************/
void Pathfinder::printCost(PathDirections dir)
{
std::cout << "Cost in direction: " << dirToName(dir) << std::endl;
std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl;
std::cout << std::setfill(' ');
for (int y = 0; y < m_max_index_y; y++) {
std::cout << "Level: " << y << std::endl;
std::cout << std::setw(4) << " " << " ";
for (int x = 0; x < m_max_index_x; x++) {
std::cout << std::setw(4) << x;
}
std::cout << std::endl;
for (int z = 0; z < m_max_index_z; z++) {
std::cout << std::setw(4) << z <<": ";
for (int x = 0; x < m_max_index_x; x++) {
if (getIdxElem(x, y, z).directions[dir].valid)
std::cout << std::setw(4)
<< getIdxElem(x, y, z).directions[dir].value;
else
std::cout << std::setw(4) << "-";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
}
/******************************************************************************/
void Pathfinder::printYdir(PathDirections dir)
{
std::cout << "Height difference in direction: " << dirToName(dir) << std::endl;
std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl;
std::cout << std::setfill(' ');
for (int y = 0; y < m_max_index_y; y++) {
std::cout << "Level: " << y << std::endl;
std::cout << std::setw(4) << " " << " ";
for (int x = 0; x < m_max_index_x; x++) {
std::cout << std::setw(4) << x;
}
std::cout << std::endl;
for (int z = 0; z < m_max_index_z; z++) {
std::cout << std::setw(4) << z <<": ";
for (int x = 0; x < m_max_index_x; x++) {
if (getIdxElem(x, y, z).directions[dir].valid)
std::cout << std::setw(4)
<< getIdxElem(x, y, z).directions[dir].direction;
else
std::cout << std::setw(4) << "-";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
}
/******************************************************************************/
void Pathfinder::printType()
{
std::cout << "Type of node:" << std::endl;
std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl;
std::cout << std::setfill(' ');
for (int y = 0; y < m_max_index_y; y++) {
std::cout << "Level: " << y << std::endl;
std::cout << std::setw(3) << " " << " ";
for (int x = 0; x < m_max_index_x; x++) {
std::cout << std::setw(3) << x;
}
std::cout << std::endl;
for (int z = 0; z < m_max_index_z; z++) {
std::cout << std::setw(3) << z <<": ";
for (int x = 0; x < m_max_index_x; x++) {
char toshow = getIdxElem(x, y, z).type;
std::cout << std::setw(3) << toshow;
}
std::cout << std::endl;
}
std::cout << std::endl;
}
std::cout << std::endl;
}
/******************************************************************************/
void Pathfinder::printPathLen()
{
std::cout << "Pathlen:" << std::endl;
std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl;
std::cout << std::setfill(' ');
for (int y = 0; y < m_max_index_y; y++) {
std::cout << "Level: " << y << std::endl;
std::cout << std::setw(3) << " " << " ";
for (int x = 0; x < m_max_index_x; x++) {
std::cout << std::setw(3) << x;
}
std::cout << std::endl;
for (int z = 0; z < m_max_index_z; z++) {
std::cout << std::setw(3) << z <<": ";
for (int x = 0; x < m_max_index_x; x++) {
std::cout << std::setw(3) << getIdxElem(x, y, z).totalcost;
}
std::cout << std::endl;
}
std::cout << std::endl;
}
std::cout << std::endl;
}
/******************************************************************************/
std::string Pathfinder::dirToName(PathDirections dir)
{
switch (dir) {
case DIR_XP:
return "XP";
break;
case DIR_XM:
return "XM";
break;
case DIR_ZP:
return "ZP";
break;
case DIR_ZM:
return "ZM";
break;
default:
return "UKN";
}
}
/******************************************************************************/
void Pathfinder::printPath(std::vector<v3s16> path)
{
unsigned int current = 0;
for (std::vector<v3s16>::iterator i = path.begin();
i != path.end(); ++i) {
std::cout << std::setw(3) << current << ":" << PP((*i)) << std::endl;
current++;
}
}
#endif
| pgimeno/minetest | src/pathfinder.cpp | C++ | mit | 36,430 |
/*
Minetest
Copyright (C) 2013 sapier, sapier at gmx dot net
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
/******************************************************************************/
/* Includes */
/******************************************************************************/
#include <vector>
#include "irr_v3d.h"
/******************************************************************************/
/* Forward declarations */
/******************************************************************************/
class ServerEnvironment;
/******************************************************************************/
/* Typedefs and macros */
/******************************************************************************/
typedef enum {
DIR_XP,
DIR_XM,
DIR_ZP,
DIR_ZM
} PathDirections;
/** List of supported algorithms */
typedef enum {
PA_DIJKSTRA, /**< Dijkstra shortest path algorithm */
PA_PLAIN, /**< A* algorithm using heuristics to find a path */
PA_PLAIN_NP /**< A* algorithm without prefetching of map data */
} PathAlgorithm;
/******************************************************************************/
/* declarations */
/******************************************************************************/
/** c wrapper function to use from scriptapi */
std::vector<v3s16> get_path(ServerEnvironment *env,
v3s16 source,
v3s16 destination,
unsigned int searchdistance,
unsigned int max_jump,
unsigned int max_drop,
PathAlgorithm algo);
| pgimeno/minetest | src/pathfinder.h | C++ | mit | 2,460 |
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "player.h"
#include "threading/mutex_auto_lock.h"
#include "util/numeric.h"
#include "hud.h"
#include "constants.h"
#include "gamedef.h"
#include "settings.h"
#include "log.h"
#include "porting.h" // strlcpy
Player::Player(const char *name, IItemDefManager *idef):
inventory(idef)
{
strlcpy(m_name, name, PLAYERNAME_SIZE);
inventory.clear();
inventory.addList("main", PLAYER_INVENTORY_SIZE);
InventoryList *craft = inventory.addList("craft", 9);
craft->setWidth(3);
inventory.addList("craftpreview", 1);
inventory.addList("craftresult", 1);
inventory.setModified(false);
// Can be redefined via Lua
inventory_formspec = "size[8,7.5]"
//"image[1,0.6;1,2;player.png]"
"list[current_player;main;0,3.5;8,4;]"
"list[current_player;craft;3,0;3,3;]"
"listring[]"
"list[current_player;craftpreview;7,1;1,1;]";
// Initialize movement settings at default values, so movement can work
// if the server fails to send them
movement_acceleration_default = 3 * BS;
movement_acceleration_air = 2 * BS;
movement_acceleration_fast = 10 * BS;
movement_speed_walk = 4 * BS;
movement_speed_crouch = 1.35 * BS;
movement_speed_fast = 20 * BS;
movement_speed_climb = 2 * BS;
movement_speed_jump = 6.5 * BS;
movement_liquid_fluidity = 1 * BS;
movement_liquid_fluidity_smooth = 0.5 * BS;
movement_liquid_sink = 10 * BS;
movement_gravity = 9.81 * BS;
local_animation_speed = 0.0;
hud_flags =
HUD_FLAG_HOTBAR_VISIBLE | HUD_FLAG_HEALTHBAR_VISIBLE |
HUD_FLAG_CROSSHAIR_VISIBLE | HUD_FLAG_WIELDITEM_VISIBLE |
HUD_FLAG_BREATHBAR_VISIBLE | HUD_FLAG_MINIMAP_VISIBLE |
HUD_FLAG_MINIMAP_RADAR_VISIBLE;
hud_hotbar_itemcount = HUD_HOTBAR_ITEMCOUNT_DEFAULT;
m_player_settings.readGlobalSettings();
// Register player setting callbacks
for (const std::string &name : m_player_settings.setting_names)
g_settings->registerChangedCallback(name,
&Player::settingsChangedCallback, &m_player_settings);
}
Player::~Player()
{
// m_player_settings becomes invalid, remove callbacks
for (const std::string &name : m_player_settings.setting_names)
g_settings->deregisterChangedCallback(name,
&Player::settingsChangedCallback, &m_player_settings);
clearHud();
}
u32 Player::addHud(HudElement *toadd)
{
MutexAutoLock lock(m_mutex);
u32 id = getFreeHudID();
if (id < hud.size())
hud[id] = toadd;
else
hud.push_back(toadd);
return id;
}
HudElement* Player::getHud(u32 id)
{
MutexAutoLock lock(m_mutex);
if (id < hud.size())
return hud[id];
return NULL;
}
HudElement* Player::removeHud(u32 id)
{
MutexAutoLock lock(m_mutex);
HudElement* retval = NULL;
if (id < hud.size()) {
retval = hud[id];
hud[id] = NULL;
}
return retval;
}
void Player::clearHud()
{
MutexAutoLock lock(m_mutex);
while(!hud.empty()) {
delete hud.back();
hud.pop_back();
}
}
void PlayerSettings::readGlobalSettings()
{
free_move = g_settings->getBool("free_move");
pitch_move = g_settings->getBool("pitch_move");
fast_move = g_settings->getBool("fast_move");
continuous_forward = g_settings->getBool("continuous_forward");
always_fly_fast = g_settings->getBool("always_fly_fast");
aux1_descends = g_settings->getBool("aux1_descends");
noclip = g_settings->getBool("noclip");
autojump = g_settings->getBool("autojump");
}
void Player::settingsChangedCallback(const std::string &name, void *data)
{
((PlayerSettings *)data)->readGlobalSettings();
}
| pgimeno/minetest | src/player.cpp | C++ | mit | 4,326 |
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "irrlichttypes_bloated.h"
#include "inventory.h"
#include "constants.h"
#include "network/networkprotocol.h"
#include "util/basic_macros.h"
#include <list>
#include <mutex>
#define PLAYERNAME_SIZE 20
#define PLAYERNAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"
#define PLAYERNAME_ALLOWED_CHARS_USER_EXPL "'a' to 'z', 'A' to 'Z', '0' to '9', '-', '_'"
struct PlayerControl
{
PlayerControl() = default;
PlayerControl(
bool a_up,
bool a_down,
bool a_left,
bool a_right,
bool a_jump,
bool a_aux1,
bool a_sneak,
bool a_zoom,
bool a_LMB,
bool a_RMB,
float a_pitch,
float a_yaw,
float a_sidew_move_joystick_axis,
float a_forw_move_joystick_axis
)
{
up = a_up;
down = a_down;
left = a_left;
right = a_right;
jump = a_jump;
aux1 = a_aux1;
sneak = a_sneak;
zoom = a_zoom;
LMB = a_LMB;
RMB = a_RMB;
pitch = a_pitch;
yaw = a_yaw;
sidew_move_joystick_axis = a_sidew_move_joystick_axis;
forw_move_joystick_axis = a_forw_move_joystick_axis;
}
bool up = false;
bool down = false;
bool left = false;
bool right = false;
bool jump = false;
bool aux1 = false;
bool sneak = false;
bool zoom = false;
bool LMB = false;
bool RMB = false;
float pitch = 0.0f;
float yaw = 0.0f;
float sidew_move_joystick_axis = 0.0f;
float forw_move_joystick_axis = 0.0f;
};
struct PlayerSettings
{
bool free_move = false;
bool pitch_move = false;
bool fast_move = false;
bool continuous_forward = false;
bool always_fly_fast = false;
bool aux1_descends = false;
bool noclip = false;
bool autojump = false;
const std::string setting_names[8] = {
"free_move", "pitch_move", "fast_move", "continuous_forward", "always_fly_fast",
"aux1_descends", "noclip", "autojump"
};
void readGlobalSettings();
};
class Map;
struct CollisionInfo;
struct HudElement;
class Environment;
class Player
{
public:
Player(const char *name, IItemDefManager *idef);
virtual ~Player() = 0;
DISABLE_CLASS_COPY(Player);
virtual void move(f32 dtime, Environment *env, f32 pos_max_d)
{}
virtual void move(f32 dtime, Environment *env, f32 pos_max_d,
std::vector<CollisionInfo> *collision_info)
{}
const v3f &getSpeed() const
{
return m_speed;
}
void setSpeed(const v3f &speed)
{
m_speed = speed;
}
const char *getName() const { return m_name; }
u32 getFreeHudID()
{
size_t size = hud.size();
for (size_t i = 0; i != size; i++) {
if (!hud[i])
return i;
}
return size;
}
v3f eye_offset_first;
v3f eye_offset_third;
Inventory inventory;
f32 movement_acceleration_default;
f32 movement_acceleration_air;
f32 movement_acceleration_fast;
f32 movement_speed_walk;
f32 movement_speed_crouch;
f32 movement_speed_fast;
f32 movement_speed_climb;
f32 movement_speed_jump;
f32 movement_liquid_fluidity;
f32 movement_liquid_fluidity_smooth;
f32 movement_liquid_sink;
f32 movement_gravity;
v2s32 local_animations[4];
float local_animation_speed;
std::string inventory_formspec;
std::string formspec_prepend;
PlayerControl control;
const PlayerControl& getPlayerControl() { return control; }
PlayerSettings &getPlayerSettings() { return m_player_settings; }
static void settingsChangedCallback(const std::string &name, void *data);
u32 keyPressed = 0;
HudElement* getHud(u32 id);
u32 addHud(HudElement* hud);
HudElement* removeHud(u32 id);
void clearHud();
u32 hud_flags;
s32 hud_hotbar_itemcount;
protected:
char m_name[PLAYERNAME_SIZE];
v3f m_speed;
std::vector<HudElement *> hud;
private:
// Protect some critical areas
// hud for example can be modified by EmergeThread
// and ServerThread
std::mutex m_mutex;
PlayerSettings m_player_settings;
};
| pgimeno/minetest | src/player.h | C++ | mit | 4,522 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/*
Random portability stuff
See comments in porting.h
*/
#include "porting.h"
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
#include <sys/types.h>
#include <sys/sysctl.h>
#elif defined(_WIN32)
#include <windows.h>
#include <wincrypt.h>
#include <algorithm>
#include <shlwapi.h>
#endif
#if !defined(_WIN32)
#include <unistd.h>
#include <sys/utsname.h>
#endif
#if defined(__hpux)
#define _PSTAT64
#include <sys/pstat.h>
#endif
#include "config.h"
#include "debug.h"
#include "filesys.h"
#include "log.h"
#include "util/string.h"
#include "settings.h"
#include <list>
#include <cstdarg>
#include <cstdio>
namespace porting
{
/*
Signal handler (grabs Ctrl-C on POSIX systems)
*/
bool g_killed = false;
bool *signal_handler_killstatus()
{
return &g_killed;
}
#if !defined(_WIN32) // POSIX
#include <signal.h>
void signal_handler(int sig)
{
if (!g_killed) {
if (sig == SIGINT) {
dstream << "INFO: signal_handler(): "
<< "Ctrl-C pressed, shutting down." << std::endl;
} else if (sig == SIGTERM) {
dstream << "INFO: signal_handler(): "
<< "got SIGTERM, shutting down." << std::endl;
}
// Comment out for less clutter when testing scripts
/*dstream << "INFO: sigint_handler(): "
<< "Printing debug stacks" << std::endl;
debug_stacks_print();*/
g_killed = true;
} else {
(void)signal(sig, SIG_DFL);
}
}
void signal_handler_init(void)
{
(void)signal(SIGINT, signal_handler);
(void)signal(SIGTERM, signal_handler);
}
#else // _WIN32
#include <signal.h>
BOOL WINAPI event_handler(DWORD sig)
{
switch (sig) {
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
if (!g_killed) {
dstream << "INFO: event_handler(): "
<< "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
" shutting down." << std::endl;
g_killed = true;
} else {
(void)signal(SIGINT, SIG_DFL);
}
break;
case CTRL_BREAK_EVENT:
break;
}
return TRUE;
}
void signal_handler_init(void)
{
SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
}
#endif
/*
Path mangler
*/
// Default to RUN_IN_PLACE style relative paths
std::string path_share = "..";
std::string path_user = "..";
std::string path_locale = path_share + DIR_DELIM + "locale";
std::string path_cache = path_user + DIR_DELIM + "cache";
std::string getDataPath(const char *subpath)
{
return path_share + DIR_DELIM + subpath;
}
void pathRemoveFile(char *path, char delim)
{
// Remove filename and path delimiter
int i;
for(i = strlen(path)-1; i>=0; i--)
{
if(path[i] == delim)
break;
}
path[i] = 0;
}
bool detectMSVCBuildDir(const std::string &path)
{
const char *ends[] = {
"bin\\Release",
"bin\\MinSizeRel",
"bin\\RelWithDebInfo",
"bin\\Debug",
"bin\\Build",
NULL
};
return (!removeStringEnd(path, ends).empty());
}
std::string get_sysinfo()
{
#ifdef _WIN32
std::ostringstream oss;
LPSTR filePath = new char[MAX_PATH];
UINT blockSize;
VS_FIXEDFILEINFO *fixedFileInfo;
GetSystemDirectoryA(filePath, MAX_PATH);
PathAppendA(filePath, "kernel32.dll");
DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
oss << "Windows/"
<< HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
<< LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
<< HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
#ifdef _WIN64
oss << "x86_64";
#else
BOOL is64 = FALSE;
if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
oss << "x86_64"; // 32-bit app on 64-bit OS
else
oss << "x86";
#endif
delete[] lpVersionInfo;
delete[] filePath;
return oss.str();
#else
struct utsname osinfo;
uname(&osinfo);
return std::string(osinfo.sysname) + "/"
+ osinfo.release + " " + osinfo.machine;
#endif
}
bool getCurrentWorkingDir(char *buf, size_t len)
{
#ifdef _WIN32
DWORD ret = GetCurrentDirectory(len, buf);
return (ret != 0) && (ret <= len);
#else
return getcwd(buf, len);
#endif
}
bool getExecPathFromProcfs(char *buf, size_t buflen)
{
#ifndef _WIN32
buflen--;
ssize_t len;
if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
(len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
(len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
return false;
buf[len] = '\0';
return true;
#else
return false;
#endif
}
//// Windows
#if defined(_WIN32)
bool getCurrentExecPath(char *buf, size_t len)
{
DWORD written = GetModuleFileNameA(NULL, buf, len);
if (written == 0 || written == len)
return false;
return true;
}
//// Linux
#elif defined(__linux__)
bool getCurrentExecPath(char *buf, size_t len)
{
if (!getExecPathFromProcfs(buf, len))
return false;
return true;
}
//// Mac OS X, Darwin
#elif defined(__APPLE__)
bool getCurrentExecPath(char *buf, size_t len)
{
uint32_t lenb = (uint32_t)len;
if (_NSGetExecutablePath(buf, &lenb) == -1)
return false;
return true;
}
//// FreeBSD, NetBSD, DragonFlyBSD
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
bool getCurrentExecPath(char *buf, size_t len)
{
// Try getting path from procfs first, since valgrind
// doesn't work with the latter
if (getExecPathFromProcfs(buf, len))
return true;
int mib[4];
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
return false;
return true;
}
//// Solaris
#elif defined(__sun) || defined(sun)
bool getCurrentExecPath(char *buf, size_t len)
{
const char *exec = getexecname();
if (exec == NULL)
return false;
if (strlcpy(buf, exec, len) >= len)
return false;
return true;
}
// HP-UX
#elif defined(__hpux)
bool getCurrentExecPath(char *buf, size_t len)
{
struct pst_status psts;
if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
return false;
if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
return false;
return true;
}
#else
bool getCurrentExecPath(char *buf, size_t len)
{
return false;
}
#endif
//// Non-Windows
#if !defined(_WIN32)
const char *getHomeOrFail()
{
const char *home = getenv("HOME");
// In rare cases the HOME environment variable may be unset
FATAL_ERROR_IF(!home,
"Required environment variable HOME is not set");
return home;
}
#endif
//// Windows
#if defined(_WIN32)
bool setSystemPaths()
{
char buf[BUFSIZ];
// Find path of executable and set path_share relative to it
FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
"Failed to get current executable path");
pathRemoveFile(buf, '\\');
std::string exepath(buf);
// Use ".\bin\.."
path_share = exepath + "\\..";
if (detectMSVCBuildDir(exepath)) {
// The msvc build dir schould normaly not be present if properly installed,
// but its usefull for debugging.
path_share += DIR_DELIM "..";
}
// Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME_C;
return true;
}
//// Linux
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
bool setSystemPaths()
{
char buf[BUFSIZ];
if (!getCurrentExecPath(buf, sizeof(buf))) {
#ifdef __ANDROID__
errorstream << "Unable to read bindir "<< std::endl;
#else
FATAL_ERROR("Unable to read bindir");
#endif
return false;
}
pathRemoveFile(buf, '/');
std::string bindir(buf);
// Find share directory from these.
// It is identified by containing the subdirectory "builtin".
std::list<std::string> trylist;
std::string static_sharedir = STATIC_SHAREDIR;
if (!static_sharedir.empty() && static_sharedir != ".")
trylist.push_back(static_sharedir);
trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
DIR_DELIM + PROJECT_NAME);
trylist.push_back(bindir + DIR_DELIM "..");
#ifdef __ANDROID__
trylist.push_back(path_user);
#endif
for (std::list<std::string>::const_iterator
i = trylist.begin(); i != trylist.end(); ++i) {
const std::string &trypath = *i;
if (!fs::PathExists(trypath) ||
!fs::PathExists(trypath + DIR_DELIM + "builtin")) {
warningstream << "system-wide share not found at \""
<< trypath << "\""<< std::endl;
continue;
}
// Warn if was not the first alternative
if (i != trylist.begin()) {
warningstream << "system-wide share found at \""
<< trypath << "\"" << std::endl;
}
path_share = trypath;
break;
}
#ifndef __ANDROID__
path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
+ PROJECT_NAME;
#endif
return true;
}
//// Mac OS X
#elif defined(__APPLE__)
bool setSystemPaths()
{
CFBundleRef main_bundle = CFBundleGetMainBundle();
CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
char path[PATH_MAX];
if (CFURLGetFileSystemRepresentation(resources_url,
TRUE, (UInt8 *)path, PATH_MAX)) {
path_share = std::string(path);
} else {
warningstream << "Could not determine bundle resource path" << std::endl;
}
CFRelease(resources_url);
path_user = std::string(getHomeOrFail())
+ "/Library/Application Support/"
+ PROJECT_NAME;
return true;
}
#else
bool setSystemPaths()
{
path_share = STATIC_SHAREDIR;
path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
+ lowercase(PROJECT_NAME);
return true;
}
#endif
void migrateCachePath()
{
const std::string local_cache_path = path_user + DIR_DELIM + "cache";
// Delete tmp folder if it exists (it only ever contained
// a temporary ogg file, which is no longer used).
if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
// Bail if migration impossible
if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
|| fs::PathExists(path_cache)) {
return;
}
if (!fs::Rename(local_cache_path, path_cache)) {
errorstream << "Failed to migrate local cache path "
"to system path!" << std::endl;
}
}
void initializePaths()
{
#if RUN_IN_PLACE
char buf[BUFSIZ];
infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
bool success =
getCurrentExecPath(buf, sizeof(buf)) ||
getExecPathFromProcfs(buf, sizeof(buf));
if (success) {
pathRemoveFile(buf, DIR_DELIM_CHAR);
std::string execpath(buf);
path_share = execpath + DIR_DELIM "..";
path_user = execpath + DIR_DELIM "..";
if (detectMSVCBuildDir(execpath)) {
path_share += DIR_DELIM "..";
path_user += DIR_DELIM "..";
}
} else {
errorstream << "Failed to get paths by executable location, "
"trying cwd" << std::endl;
if (!getCurrentWorkingDir(buf, sizeof(buf)))
FATAL_ERROR("Ran out of methods to get paths");
size_t cwdlen = strlen(buf);
if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
cwdlen--;
buf[cwdlen] = '\0';
}
if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
pathRemoveFile(buf, DIR_DELIM_CHAR);
std::string execpath(buf);
path_share = execpath;
path_user = execpath;
}
path_cache = path_user + DIR_DELIM + "cache";
#else
infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
if (!setSystemPaths())
errorstream << "Failed to get one or more system-wide path" << std::endl;
# ifdef _WIN32
path_cache = path_user + DIR_DELIM + "cache";
# else
// Initialize path_cache
// First try $XDG_CACHE_HOME/PROJECT_NAME
const char *cache_dir = getenv("XDG_CACHE_HOME");
const char *home_dir = getenv("HOME");
if (cache_dir) {
path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
} else if (home_dir) {
// Then try $HOME/.cache/PROJECT_NAME
path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
+ DIR_DELIM + PROJECT_NAME;
} else {
// If neither works, use $PATH_USER/cache
path_cache = path_user + DIR_DELIM + "cache";
}
// Migrate cache folder to new location if possible
migrateCachePath();
# endif // _WIN32
#endif // RUN_IN_PLACE
infostream << "Detected share path: " << path_share << std::endl;
infostream << "Detected user path: " << path_user << std::endl;
infostream << "Detected cache path: " << path_cache << std::endl;
#if USE_GETTEXT
bool found_localedir = false;
# ifdef STATIC_LOCALEDIR
if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
found_localedir = true;
path_locale = STATIC_LOCALEDIR;
infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
} else {
path_locale = getDataPath("locale");
if (fs::PathExists(path_locale)) {
found_localedir = true;
infostream << "Using in-place locale directory " << path_locale
<< " even though a static one was provided "
<< "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
}
}
# else
path_locale = getDataPath("locale");
if (fs::PathExists(path_locale)) {
found_localedir = true;
}
# endif
if (!found_localedir) {
warningstream << "Couldn't find a locale directory!" << std::endl;
}
#endif // USE_GETTEXT
}
////
//// OS-specific Secure Random
////
#ifdef WIN32
bool secure_rand_fill_buf(void *buf, size_t len)
{
HCRYPTPROV wctx;
if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
return false;
CryptGenRandom(wctx, len, (BYTE *)buf);
CryptReleaseContext(wctx, 0);
return true;
}
#else
bool secure_rand_fill_buf(void *buf, size_t len)
{
// N.B. This function checks *only* for /dev/urandom, because on most
// common OSes it is non-blocking, whereas /dev/random is blocking, and it
// is exceptionally uncommon for there to be a situation where /dev/random
// exists but /dev/urandom does not. This guesswork is necessary since
// random devices are not covered by any POSIX standard...
FILE *fp = fopen("/dev/urandom", "rb");
if (!fp)
return false;
bool success = fread(buf, len, 1, fp) == 1;
fclose(fp);
return success;
}
#endif
void attachOrCreateConsole()
{
#ifdef _WIN32
static bool consoleAllocated = false;
const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
consoleAllocated = true;
}
#endif
}
int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
{
// https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
// Many of the MSVC / Windows printf-style functions do not support positional
// arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
// platforms, but defer to _vsprintf_p on MSVC / Windows.
// https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
// _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
// above FFmpeg link).
va_list args;
va_start(args, fmt);
#ifndef _MSC_VER
int c = vsnprintf(buf, buf_size, fmt, args);
#else // _MSC_VER
int c = _vsprintf_p(buf, buf_size, fmt, args);
if (c == -1)
c = _vscprintf_p(fmt, args);
#endif // _MSC_VER
va_end(args);
return c;
}
// Load performance counter frequency only once at startup
#ifdef _WIN32
inline double get_perf_freq()
{
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
return freq.QuadPart;
}
double perf_freq = get_perf_freq();
#endif
} //namespace porting
| pgimeno/minetest | src/porting.cpp | C++ | mit | 16,286 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/*
Random portability stuff
*/
#pragma once
#ifdef _WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501 // We need to do this before any other headers
// because those might include sdkddkver.h which defines _WIN32_WINNT if not already set
#endif
#include <string>
#include <vector>
#include "irrlicht.h"
#include "irrlichttypes.h" // u32
#include "irrlichttypes_extrabloated.h"
#include "debug.h"
#include "constants.h"
#include "gettime.h"
#ifdef _MSC_VER
#define SWPRINTF_CHARSTRING L"%S"
#else
#define SWPRINTF_CHARSTRING L"%s"
#endif
//currently not needed
//template<typename T> struct alignment_trick { char c; T member; };
//#define ALIGNOF(type) offsetof (alignment_trick<type>, member)
#ifdef _WIN32
#include <windows.h>
#define sleep_ms(x) Sleep(x)
#else
#include <unistd.h>
#include <cstdint> //for uintptr_t
// Use standard Posix macro for Linux
#if (defined(linux) || defined(__linux)) && !defined(__linux__)
#define __linux__
#endif
#if (defined(__linux__) || defined(__GNU__)) && !defined(_GNU_SOURCE)
#define _GNU_SOURCE
#endif
#define sleep_ms(x) usleep(x*1000)
#endif
#ifdef _MSC_VER
#define ALIGNOF(x) __alignof(x)
#define strtok_r(x, y, z) strtok_s(x, y, z)
#define strtof(x, y) (float)strtod(x, y)
#define strtoll(x, y, z) _strtoi64(x, y, z)
#define strtoull(x, y, z) _strtoui64(x, y, z)
#define strcasecmp(x, y) stricmp(x, y)
#define strncasecmp(x, y, n) strnicmp(x, y, n)
#else
#define ALIGNOF(x) __alignof__(x)
#endif
#ifdef __MINGW32__
#define strtok_r(x, y, z) mystrtok_r(x, y, z)
#endif
// strlcpy is missing from glibc. thanks a lot, drepper.
// strlcpy is also missing from AIX and HP-UX because they aim to be weird.
// We can't simply alias strlcpy to MSVC's strcpy_s, since strcpy_s by
// default raises an assertion error and aborts the program if the buffer is
// too small.
#if defined(__FreeBSD__) || defined(__NetBSD__) || \
defined(__OpenBSD__) || defined(__DragonFly__) || \
defined(__APPLE__) || \
defined(__sun) || defined(sun) || \
defined(__QNX__) || defined(__QNXNTO__)
#define HAVE_STRLCPY
#endif
// So we need to define our own.
#ifndef HAVE_STRLCPY
#define strlcpy(d, s, n) mystrlcpy(d, s, n)
#endif
#define PADDING(x, y) ((ALIGNOF(y) - ((uintptr_t)(x) & (ALIGNOF(y) - 1))) & (ALIGNOF(y) - 1))
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#include <CoreFoundation/CoreFoundation.h>
#endif
#ifndef _WIN32 // Posix
#include <sys/time.h>
#include <ctime>
#if defined(__MACH__) && defined(__APPLE__)
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#endif
namespace porting
{
/*
Signal handler (grabs Ctrl-C on POSIX systems)
*/
void signal_handler_init();
// Returns a pointer to a bool.
// When the bool is true, program should quit.
bool * signal_handler_killstatus();
/*
Path of static data directory.
*/
extern std::string path_share;
/*
Directory for storing user data. Examples:
Windows: "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
Linux: "~/.<PROJECT_NAME>"
Mac: "~/Library/Application Support/<PROJECT_NAME>"
*/
extern std::string path_user;
/*
Path to gettext locale files
*/
extern std::string path_locale;
/*
Path to directory for storing caches.
*/
extern std::string path_cache;
/*
Get full path of stuff in data directory.
Example: "stone.png" -> "../data/stone.png"
*/
std::string getDataPath(const char *subpath);
/*
Move cache folder from path_user to the
system cache location if possible.
*/
void migrateCachePath();
/*
Initialize path_*.
*/
void initializePaths();
/*
Return system information
e.g. "Linux/3.12.7 x86_64"
*/
std::string get_sysinfo();
// Monotonic counter getters.
#ifdef _WIN32 // Windows
extern double perf_freq;
inline u64 os_get_time(double mult)
{
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return static_cast<double>(t.QuadPart) / (perf_freq / mult);
}
// Resolution is <1us.
inline u64 getTimeS() { return os_get_time(1); }
inline u64 getTimeMs() { return os_get_time(1000); }
inline u64 getTimeUs() { return os_get_time(1000*1000); }
inline u64 getTimeNs() { return os_get_time(1000*1000*1000); }
#else // Posix
inline void os_get_clock(struct timespec *ts)
{
#if defined(__MACH__) && defined(__APPLE__)
// From http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x
// OS X does not have clock_gettime, use clock_get_time
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts->tv_sec = mts.tv_sec;
ts->tv_nsec = mts.tv_nsec;
#elif defined(CLOCK_MONOTONIC_RAW)
clock_gettime(CLOCK_MONOTONIC_RAW, ts);
#elif defined(_POSIX_MONOTONIC_CLOCK)
clock_gettime(CLOCK_MONOTONIC, ts);
#else
struct timeval tv;
gettimeofday(&tv, NULL);
TIMEVAL_TO_TIMESPEC(&tv, ts);
#endif
}
inline u64 getTimeS()
{
struct timespec ts;
os_get_clock(&ts);
return ts.tv_sec;
}
inline u64 getTimeMs()
{
struct timespec ts;
os_get_clock(&ts);
return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
inline u64 getTimeUs()
{
struct timespec ts;
os_get_clock(&ts);
return ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
}
inline u64 getTimeNs()
{
struct timespec ts;
os_get_clock(&ts);
return ts.tv_sec * 1000000000 + ts.tv_nsec;
}
#endif
inline u64 getTime(TimePrecision prec)
{
switch (prec) {
case PRECISION_SECONDS: return getTimeS();
case PRECISION_MILLI: return getTimeMs();
case PRECISION_MICRO: return getTimeUs();
case PRECISION_NANO: return getTimeNs();
}
FATAL_ERROR("Called getTime with invalid time precision");
}
/**
* Delta calculation function arguments.
* @param old_time_ms old time for delta calculation
* @param new_time_ms new time for delta calculation
* @return positive delta value
*/
inline u64 getDeltaMs(u64 old_time_ms, u64 new_time_ms)
{
if (new_time_ms >= old_time_ms) {
return (new_time_ms - old_time_ms);
}
return (old_time_ms - new_time_ms);
}
inline const char *getPlatformName()
{
return
#if defined(ANDROID)
"Android"
#elif defined(__linux__)
"Linux"
#elif defined(_WIN32) || defined(_WIN64)
"Windows"
#elif defined(__DragonFly__) || defined(__FreeBSD__) || \
defined(__NetBSD__) || defined(__OpenBSD__)
"BSD"
#elif defined(__APPLE__) && defined(__MACH__)
#if TARGET_OS_MAC
"OSX"
#elif TARGET_OS_IPHONE
"iOS"
#else
"Apple"
#endif
#elif defined(_AIX)
"AIX"
#elif defined(__hpux)
"HP-UX"
#elif defined(__sun) || defined(sun)
#if defined(__SVR4)
"Solaris"
#else
"SunOS"
#endif
#elif defined(__CYGWIN__)
"Cygwin"
#elif defined(__unix__) || defined(__unix)
#if defined(_POSIX_VERSION)
"Posix"
#else
"Unix"
#endif
#else
"?"
#endif
;
}
bool secure_rand_fill_buf(void *buf, size_t len);
// This attaches to the parents process console, or creates a new one if it doesnt exist.
void attachOrCreateConsole();
int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...);
} // namespace porting
#ifdef __ANDROID__
#include "porting_android.h"
#endif
| pgimeno/minetest | src/porting.h | C++ | mit | 7,887 |
/*
Minetest
Copyright (C) 2014 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef __ANDROID__
#error This file may only be compiled for android!
#endif
#include "util/numeric.h"
#include "porting.h"
#include "porting_android.h"
#include "threading/thread.h"
#include "config.h"
#include "filesys.h"
#include "log.h"
#include <sstream>
#include <exception>
#include <cstdlib>
#ifdef GPROF
#include "prof.h"
#endif
extern int main(int argc, char *argv[]);
void android_main(android_app *app)
{
int retval = 0;
porting::app_global = app;
Thread::setName("Main");
try {
app_dummy();
char *argv[] = {strdup(PROJECT_NAME), NULL};
main(ARRLEN(argv) - 1, argv);
free(argv[0]);
} catch (std::exception &e) {
errorstream << "Uncaught exception in main thread: " << e.what() << std::endl;
retval = -1;
} catch (...) {
errorstream << "Uncaught exception in main thread!" << std::endl;
retval = -1;
}
porting::cleanupAndroid();
infostream << "Shutting down." << std::endl;
exit(retval);
}
/* handler for finished message box input */
/* Intentionally NOT in namespace porting */
/* TODO this doesn't work as expected, no idea why but there's a workaround */
/* for it right now */
extern "C" {
JNIEXPORT void JNICALL Java_net_minetest_MtNativeActivity_putMessageBoxResult(
JNIEnv * env, jclass thiz, jstring text)
{
errorstream << "Java_net_minetest_MtNativeActivity_putMessageBoxResult got: "
<< std::string((const char*)env->GetStringChars(text,0))
<< std::endl;
}
}
namespace porting {
std::string path_storage = DIR_DELIM "sdcard" DIR_DELIM;
android_app* app_global;
JNIEnv* jnienv;
jclass nativeActivity;
jclass findClass(std::string classname)
{
if (jnienv == 0) {
return 0;
}
jclass nativeactivity = jnienv->FindClass("android/app/NativeActivity");
jmethodID getClassLoader =
jnienv->GetMethodID(nativeactivity,"getClassLoader",
"()Ljava/lang/ClassLoader;");
jobject cls =
jnienv->CallObjectMethod(app_global->activity->clazz, getClassLoader);
jclass classLoader = jnienv->FindClass("java/lang/ClassLoader");
jmethodID findClass =
jnienv->GetMethodID(classLoader, "loadClass",
"(Ljava/lang/String;)Ljava/lang/Class;");
jstring strClassName =
jnienv->NewStringUTF(classname.c_str());
return (jclass) jnienv->CallObjectMethod(cls, findClass, strClassName);
}
void copyAssets()
{
jmethodID assetcopy = jnienv->GetMethodID(nativeActivity,"copyAssets","()V");
if (assetcopy == 0) {
assert("porting::copyAssets unable to find copy assets method" == 0);
}
jnienv->CallVoidMethod(app_global->activity->clazz, assetcopy);
}
void initAndroid()
{
porting::jnienv = NULL;
JavaVM *jvm = app_global->activity->vm;
JavaVMAttachArgs lJavaVMAttachArgs;
lJavaVMAttachArgs.version = JNI_VERSION_1_6;
lJavaVMAttachArgs.name = PROJECT_NAME_C "NativeThread";
lJavaVMAttachArgs.group = NULL;
#ifdef NDEBUG
// This is a ugly hack as arm v7a non debuggable builds crash without this
// printf ... if someone finds out why please fix it!
infostream << "Attaching native thread. " << std::endl;
#endif
if ( jvm->AttachCurrentThread(&porting::jnienv, &lJavaVMAttachArgs) == JNI_ERR) {
errorstream << "Failed to attach native thread to jvm" << std::endl;
exit(-1);
}
nativeActivity = findClass("net/minetest/minetest/MtNativeActivity");
if (nativeActivity == 0) {
errorstream <<
"porting::initAndroid unable to find java native activity class" <<
std::endl;
}
#ifdef GPROF
/* in the start-up code */
__android_log_print(ANDROID_LOG_ERROR, PROJECT_NAME_C,
"Initializing GPROF profiler");
monstartup("libminetest.so");
#endif
}
void cleanupAndroid()
{
#ifdef GPROF
errorstream << "Shutting down GPROF profiler" << std::endl;
setenv("CPUPROFILE", (path_user + DIR_DELIM + "gmon.out").c_str(), 1);
moncleanup();
#endif
JavaVM *jvm = app_global->activity->vm;
jvm->DetachCurrentThread();
}
static std::string javaStringToUTF8(jstring js)
{
std::string str;
// Get string as a UTF-8 c-string
const char *c_str = jnienv->GetStringUTFChars(js, NULL);
// Save it
str = c_str;
// And free the c-string
jnienv->ReleaseStringUTFChars(js, c_str);
return str;
}
// Calls static method if obj is NULL
static std::string getAndroidPath(jclass cls, jobject obj, jclass cls_File,
jmethodID mt_getAbsPath, const char *getter)
{
// Get getter method
jmethodID mt_getter;
if (obj)
mt_getter = jnienv->GetMethodID(cls, getter,
"()Ljava/io/File;");
else
mt_getter = jnienv->GetStaticMethodID(cls, getter,
"()Ljava/io/File;");
// Call getter
jobject ob_file;
if (obj)
ob_file = jnienv->CallObjectMethod(obj, mt_getter);
else
ob_file = jnienv->CallStaticObjectMethod(cls, mt_getter);
// Call getAbsolutePath
jstring js_path = (jstring) jnienv->CallObjectMethod(ob_file,
mt_getAbsPath);
return javaStringToUTF8(js_path);
}
void initializePathsAndroid()
{
// Get Environment class
jclass cls_Env = jnienv->FindClass("android/os/Environment");
// Get File class
jclass cls_File = jnienv->FindClass("java/io/File");
// Get getAbsolutePath method
jmethodID mt_getAbsPath = jnienv->GetMethodID(cls_File,
"getAbsolutePath", "()Ljava/lang/String;");
path_cache = getAndroidPath(nativeActivity, app_global->activity->clazz,
cls_File, mt_getAbsPath, "getCacheDir");
path_storage = getAndroidPath(cls_Env, NULL, cls_File, mt_getAbsPath,
"getExternalStorageDirectory");
path_user = path_storage + DIR_DELIM + PROJECT_NAME_C;
path_share = path_storage + DIR_DELIM + PROJECT_NAME_C;
migrateCachePath();
}
void showInputDialog(const std::string& acceptButton, const std::string& hint,
const std::string& current, int editType)
{
jmethodID showdialog = jnienv->GetMethodID(nativeActivity,"showDialog",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V");
if (showdialog == 0) {
assert("porting::showInputDialog unable to find java show dialog method" == 0);
}
jstring jacceptButton = jnienv->NewStringUTF(acceptButton.c_str());
jstring jhint = jnienv->NewStringUTF(hint.c_str());
jstring jcurrent = jnienv->NewStringUTF(current.c_str());
jint jeditType = editType;
jnienv->CallVoidMethod(app_global->activity->clazz, showdialog,
jacceptButton, jhint, jcurrent, jeditType);
}
int getInputDialogState()
{
jmethodID dialogstate = jnienv->GetMethodID(nativeActivity,
"getDialogState", "()I");
if (dialogstate == 0) {
assert("porting::getInputDialogState unable to find java dialog state method" == 0);
}
return jnienv->CallIntMethod(app_global->activity->clazz, dialogstate);
}
std::string getInputDialogValue()
{
jmethodID dialogvalue = jnienv->GetMethodID(nativeActivity,
"getDialogValue", "()Ljava/lang/String;");
if (dialogvalue == 0) {
assert("porting::getInputDialogValue unable to find java dialog value method" == 0);
}
jobject result = jnienv->CallObjectMethod(app_global->activity->clazz,
dialogvalue);
const char* javachars = jnienv->GetStringUTFChars((jstring) result,0);
std::string text(javachars);
jnienv->ReleaseStringUTFChars((jstring) result, javachars);
return text;
}
#ifndef SERVER
float getDisplayDensity()
{
static bool firstrun = true;
static float value = 0;
if (firstrun) {
jmethodID getDensity = jnienv->GetMethodID(nativeActivity, "getDensity",
"()F");
if (getDensity == 0) {
assert("porting::getDisplayDensity unable to find java getDensity method" == 0);
}
value = jnienv->CallFloatMethod(app_global->activity->clazz, getDensity);
firstrun = false;
}
return value;
}
v2u32 getDisplaySize()
{
static bool firstrun = true;
static v2u32 retval;
if (firstrun) {
jmethodID getDisplayWidth = jnienv->GetMethodID(nativeActivity,
"getDisplayWidth", "()I");
if (getDisplayWidth == 0) {
assert("porting::getDisplayWidth unable to find java getDisplayWidth method" == 0);
}
retval.X = jnienv->CallIntMethod(app_global->activity->clazz,
getDisplayWidth);
jmethodID getDisplayHeight = jnienv->GetMethodID(nativeActivity,
"getDisplayHeight", "()I");
if (getDisplayHeight == 0) {
assert("porting::getDisplayHeight unable to find java getDisplayHeight method" == 0);
}
retval.Y = jnienv->CallIntMethod(app_global->activity->clazz,
getDisplayHeight);
firstrun = false;
}
return retval;
}
#endif // ndef SERVER
}
| pgimeno/minetest | src/porting_android.cpp | C++ | mit | 9,051 |
/*
Minetest
Copyright (C) 2014 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#ifndef __ANDROID__
#error this include has to be included on android port only!
#endif
#include <jni.h>
#include <android_native_app_glue.h>
#include <android/log.h>
#include <string>
namespace porting {
/** java app **/
extern android_app *app_global;
/** java <-> c++ interaction interface **/
extern JNIEnv *jnienv;
/**
* do initialization required on android only
*/
void initAndroid();
void cleanupAndroid();
/**
* Initializes path_* variables for Android
* @param env Android JNI environment
*/
void initializePathsAndroid();
/**
* use java function to copy media from assets to external storage
*/
void copyAssets();
/**
* show text input dialog in java
* @param acceptButton text to display on accept button
* @param hint hint to show
* @param current initial value to display
* @param editType type of texfield
* (1==multiline text input; 2==single line text input; 3=password field)
*/
void showInputDialog(const std::string& acceptButton,
const std::string& hint, const std::string& current, int editType);
/**
* WORKAROUND for not working callbacks from java -> c++
* get current state of input dialog
*/
int getInputDialogState();
/**
* WORKAROUND for not working callbacks from java -> c++
* get text in current input dialog
*/
std::string getInputDialogValue();
#ifndef SERVER
float getDisplayDensity();
v2u32 getDisplaySize();
#endif
}
| pgimeno/minetest | src/porting_android.h | C++ | mit | 2,187 |
/*
Minetest
Copyright (C) 2015 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "profiler.h"
static Profiler main_profiler;
Profiler *g_profiler = &main_profiler;
ScopeProfiler::ScopeProfiler(
Profiler *profiler, const std::string &name, ScopeProfilerType type) :
m_profiler(profiler),
m_name(name), m_type(type)
{
if (m_profiler)
m_timer = new TimeTaker(m_name);
}
ScopeProfiler::~ScopeProfiler()
{
if (!m_timer)
return;
float duration_ms = m_timer->stop(true);
float duration = duration_ms / 1000.0;
if (m_profiler) {
switch (m_type) {
case SPT_ADD:
m_profiler->add(m_name, duration);
break;
case SPT_AVG:
m_profiler->avg(m_name, duration);
break;
case SPT_GRAPH_ADD:
m_profiler->graphAdd(m_name, duration);
break;
}
}
delete m_timer;
}
| pgimeno/minetest | src/profiler.cpp | C++ | mit | 1,501 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "irrlichttypes.h"
#include <cassert>
#include <string>
#include <map>
#include <ostream>
#include "threading/mutex_auto_lock.h"
#include "util/timetaker.h"
#include "util/numeric.h" // paging()
#define MAX_PROFILER_TEXT_ROWS 20
// Global profiler
class Profiler;
extern Profiler *g_profiler;
/*
Time profiler
*/
class Profiler
{
public:
Profiler() = default;
void add(const std::string &name, float value)
{
MutexAutoLock lock(m_mutex);
{
/* No average shall have been used; mark add used as -2 */
std::map<std::string, int>::iterator n = m_avgcounts.find(name);
if(n == m_avgcounts.end())
m_avgcounts[name] = -2;
else{
if(n->second == -1)
n->second = -2;
assert(n->second == -2);
}
}
{
std::map<std::string, float>::iterator n = m_data.find(name);
if(n == m_data.end())
m_data[name] = value;
else
n->second += value;
}
}
void avg(const std::string &name, float value)
{
MutexAutoLock lock(m_mutex);
int &count = m_avgcounts[name];
assert(count != -2);
count = MYMAX(count, 0) + 1;
m_data[name] += value;
}
void clear()
{
MutexAutoLock lock(m_mutex);
for (auto &it : m_data) {
it.second = 0;
}
m_avgcounts.clear();
}
void print(std::ostream &o)
{
printPage(o, 1, 1);
}
float getValue(const std::string &name) const
{
std::map<std::string, float>::const_iterator numerator = m_data.find(name);
if (numerator == m_data.end())
return 0.f;
std::map<std::string, int>::const_iterator denominator = m_avgcounts.find(name);
if (denominator != m_avgcounts.end()){
if (denominator->second >= 1)
return numerator->second / denominator->second;
}
return numerator->second;
}
void printPage(std::ostream &o, u32 page, u32 pagecount)
{
MutexAutoLock lock(m_mutex);
u32 minindex, maxindex;
paging(m_data.size(), page, pagecount, minindex, maxindex);
for (std::map<std::string, float>::const_iterator i = m_data.begin();
i != m_data.end(); ++i) {
if (maxindex == 0)
break;
maxindex--;
if (minindex != 0) {
minindex--;
continue;
}
int avgcount = 1;
std::map<std::string, int>::const_iterator n = m_avgcounts.find(i->first);
if (n != m_avgcounts.end()) {
if(n->second >= 1)
avgcount = n->second;
}
o << " " << i->first << ": ";
s32 clampsize = 40;
s32 space = clampsize - i->first.size();
for(s32 j = 0; j < space; j++) {
if (j % 2 == 0 && j < space - 1)
o << "-";
else
o << " ";
}
o << (i->second / avgcount);
o << std::endl;
}
}
typedef std::map<std::string, float> GraphValues;
void graphAdd(const std::string &id, float value)
{
MutexAutoLock lock(m_mutex);
std::map<std::string, float>::iterator i =
m_graphvalues.find(id);
if(i == m_graphvalues.end())
m_graphvalues[id] = value;
else
i->second += value;
}
void graphGet(GraphValues &result)
{
MutexAutoLock lock(m_mutex);
result = m_graphvalues;
m_graphvalues.clear();
}
void remove(const std::string& name)
{
MutexAutoLock lock(m_mutex);
m_avgcounts.erase(name);
m_data.erase(name);
}
private:
std::mutex m_mutex;
std::map<std::string, float> m_data;
std::map<std::string, int> m_avgcounts;
std::map<std::string, float> m_graphvalues;
};
enum ScopeProfilerType{
SPT_ADD,
SPT_AVG,
SPT_GRAPH_ADD
};
class ScopeProfiler
{
public:
ScopeProfiler(Profiler *profiler, const std::string &name,
ScopeProfilerType type = SPT_ADD);
~ScopeProfiler();
private:
Profiler *m_profiler = nullptr;
std::string m_name;
TimeTaker *m_timer = nullptr;
enum ScopeProfilerType m_type;
};
| pgimeno/minetest | src/profiler.h | C++ | mit | 4,420 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "quicktune.h"
#include "threading/mutex_auto_lock.h"
#include "util/string.h"
std::string QuicktuneValue::getString()
{
switch(type){
case QVT_NONE:
return "(none)";
case QVT_FLOAT:
return ftos(value_QVT_FLOAT.current);
}
return "<invalid type>";
}
void QuicktuneValue::relativeAdd(float amount)
{
switch(type){
case QVT_NONE:
break;
case QVT_FLOAT:
value_QVT_FLOAT.current += amount * (value_QVT_FLOAT.max - value_QVT_FLOAT.min);
if(value_QVT_FLOAT.current > value_QVT_FLOAT.max)
value_QVT_FLOAT.current = value_QVT_FLOAT.max;
if(value_QVT_FLOAT.current < value_QVT_FLOAT.min)
value_QVT_FLOAT.current = value_QVT_FLOAT.min;
break;
}
}
static std::map<std::string, QuicktuneValue> g_values;
static std::vector<std::string> g_names;
std::mutex *g_mutex = NULL;
static void makeMutex()
{
if(!g_mutex){
g_mutex = new std::mutex();
}
}
std::vector<std::string> getQuicktuneNames()
{
return g_names;
}
QuicktuneValue getQuicktuneValue(const std::string &name)
{
makeMutex();
MutexAutoLock lock(*g_mutex);
std::map<std::string, QuicktuneValue>::iterator i = g_values.find(name);
if(i == g_values.end()){
QuicktuneValue val;
val.type = QVT_NONE;
return val;
}
return i->second;
}
void setQuicktuneValue(const std::string &name, const QuicktuneValue &val)
{
makeMutex();
MutexAutoLock lock(*g_mutex);
g_values[name] = val;
g_values[name].modified = true;
}
void updateQuicktuneValue(const std::string &name, QuicktuneValue &val)
{
makeMutex();
MutexAutoLock lock(*g_mutex);
std::map<std::string, QuicktuneValue>::iterator i = g_values.find(name);
if(i == g_values.end()){
g_values[name] = val;
g_names.push_back(name);
return;
}
QuicktuneValue &ref = i->second;
if(ref.modified)
val = ref;
else{
ref = val;
ref.modified = false;
}
}
| pgimeno/minetest | src/quicktune.cpp | C++ | mit | 2,598 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/*
Used for tuning constants when developing.
Eg. if you have this constant somewhere that you just can't get right
by changing it and recompiling all over again:
v3f wield_position = v3f(55, -35, 65);
Make it look like this:
v3f wield_position = v3f(55, -35, 65);
QUICKTUNE_AUTONAME(QVT_FLOAT, wield_position.X, 0, 100);
QUICKTUNE_AUTONAME(QVT_FLOAT, wield_position.Y, -80, 20);
QUICKTUNE_AUTONAME(QVT_FLOAT, wield_position.Z, 0, 100);
Then you can modify the values at runtime, using the keys
keymap_quicktune_prev
keymap_quicktune_next
keymap_quicktune_dec
keymap_quicktune_inc
Once you have modified the values at runtime and then quit, the game
will print out all the modified values at the end:
Modified quicktune values:
wield_position.X = 60
wield_position.Y = -30
wield_position.Z = 65
The QUICKTUNE macros shouldn't generally be left in committed code.
*/
#pragma once
#include <string>
#include <map>
#include <vector>
enum QuicktuneValueType{
QVT_NONE,
QVT_FLOAT
};
struct QuicktuneValue
{
QuicktuneValueType type = QVT_NONE;
union{
struct{
float current;
float min;
float max;
} value_QVT_FLOAT;
};
bool modified = false;
QuicktuneValue() = default;
std::string getString();
void relativeAdd(float amount);
};
std::vector<std::string> getQuicktuneNames();
QuicktuneValue getQuicktuneValue(const std::string &name);
void setQuicktuneValue(const std::string &name, const QuicktuneValue &val);
void updateQuicktuneValue(const std::string &name, QuicktuneValue &val);
#ifndef NDEBUG
#define QUICKTUNE(type_, var, min_, max_, name){\
QuicktuneValue qv;\
qv.type = type_;\
qv.value_##type_.current = var;\
qv.value_##type_.min = min_;\
qv.value_##type_.max = max_;\
updateQuicktuneValue(name, qv);\
var = qv.value_##type_.current;\
}
#else // NDEBUG
#define QUICKTUNE(type, var, min_, max_, name){}
#endif
#define QUICKTUNE_AUTONAME(type_, var, min_, max_)\
QUICKTUNE(type_, var, min_, max_, #var)
| pgimeno/minetest | src/quicktune.h | C++ | mit | 2,778 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "quicktune.h"
class QuicktuneShortcutter
{
private:
std::vector<std::string> m_names;
u32 m_selected_i;
std::string m_message;
public:
bool hasMessage() const
{
return !m_message.empty();
}
std::string getMessage()
{
std::string s = m_message;
m_message = "";
if (!s.empty())
return std::string("[quicktune] ") + s;
return "";
}
std::string getSelectedName()
{
if(m_selected_i < m_names.size())
return m_names[m_selected_i];
return "(nothing)";
}
void next()
{
m_names = getQuicktuneNames();
if(m_selected_i < m_names.size()-1)
m_selected_i++;
else
m_selected_i = 0;
m_message = std::string("Selected \"")+getSelectedName()+"\"";
}
void prev()
{
m_names = getQuicktuneNames();
if(m_selected_i > 0)
m_selected_i--;
else
m_selected_i = m_names.size()-1;
m_message = std::string("Selected \"")+getSelectedName()+"\"";
}
void inc()
{
QuicktuneValue val = getQuicktuneValue(getSelectedName());
val.relativeAdd(0.05);
m_message = std::string("\"")+getSelectedName()
+"\" = "+val.getString();
setQuicktuneValue(getSelectedName(), val);
}
void dec()
{
QuicktuneValue val = getQuicktuneValue(getSelectedName());
val.relativeAdd(-0.05);
m_message = std::string("\"")+getSelectedName()
+"\" = "+val.getString();
setQuicktuneValue(getSelectedName(), val);
}
};
| pgimeno/minetest | src/quicktune_shortcutter.h | C++ | mit | 2,155 |
/*
Minetest
Copyright (C) 2016 juhdanad, Daniel Juhasz <juhdanad@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "raycast.h"
#include "irr_v3d.h"
#include "irr_aabb3d.h"
#include "constants.h"
bool RaycastSort::operator() (const PointedThing &pt1,
const PointedThing &pt2) const
{
// "nothing" can not be sorted
assert(pt1.type != POINTEDTHING_NOTHING);
assert(pt2.type != POINTEDTHING_NOTHING);
f32 pt1_distSq = pt1.distanceSq;
// Add some bonus when one of them is an object
if (pt1.type != pt2.type) {
if (pt1.type == POINTEDTHING_OBJECT)
pt1_distSq -= BS * BS;
else if (pt2.type == POINTEDTHING_OBJECT)
pt1_distSq += BS * BS;
}
// returns false if pt1 is nearer than pt2
if (pt1_distSq < pt2.distanceSq) {
return false;
}
if (pt1_distSq == pt2.distanceSq) {
// Sort them to allow only one order
if (pt1.type == POINTEDTHING_OBJECT)
return (pt2.type == POINTEDTHING_OBJECT
&& pt1.object_id < pt2.object_id);
return (pt2.type == POINTEDTHING_OBJECT
|| pt1.node_undersurface < pt2.node_undersurface);
}
return true;
}
RaycastState::RaycastState(const core::line3d<f32> &shootline,
bool objects_pointable, bool liquids_pointable) :
m_shootline(shootline),
m_iterator(shootline.start / BS, shootline.getVector() / BS),
m_previous_node(m_iterator.m_current_node_pos),
m_objects_pointable(objects_pointable),
m_liquids_pointable(liquids_pointable)
{
}
bool boxLineCollision(const aabb3f &box, const v3f &start,
const v3f &dir, v3f *collision_point, v3s16 *collision_normal)
{
if (box.isPointInside(start)) {
*collision_point = start;
collision_normal->set(0, 0, 0);
return true;
}
float m = 0;
// Test X collision
if (dir.X != 0) {
if (dir.X > 0)
m = (box.MinEdge.X - start.X) / dir.X;
else
m = (box.MaxEdge.X - start.X) / dir.X;
if (m >= 0 && m <= 1) {
*collision_point = start + dir * m;
if ((collision_point->Y >= box.MinEdge.Y)
&& (collision_point->Y <= box.MaxEdge.Y)
&& (collision_point->Z >= box.MinEdge.Z)
&& (collision_point->Z <= box.MaxEdge.Z)) {
collision_normal->set((dir.X > 0) ? -1 : 1, 0, 0);
return true;
}
}
}
// Test Y collision
if (dir.Y != 0) {
if (dir.Y > 0)
m = (box.MinEdge.Y - start.Y) / dir.Y;
else
m = (box.MaxEdge.Y - start.Y) / dir.Y;
if (m >= 0 && m <= 1) {
*collision_point = start + dir * m;
if ((collision_point->X >= box.MinEdge.X)
&& (collision_point->X <= box.MaxEdge.X)
&& (collision_point->Z >= box.MinEdge.Z)
&& (collision_point->Z <= box.MaxEdge.Z)) {
collision_normal->set(0, (dir.Y > 0) ? -1 : 1, 0);
return true;
}
}
}
// Test Z collision
if (dir.Z != 0) {
if (dir.Z > 0)
m = (box.MinEdge.Z - start.Z) / dir.Z;
else
m = (box.MaxEdge.Z - start.Z) / dir.Z;
if (m >= 0 && m <= 1) {
*collision_point = start + dir * m;
if ((collision_point->X >= box.MinEdge.X)
&& (collision_point->X <= box.MaxEdge.X)
&& (collision_point->Y >= box.MinEdge.Y)
&& (collision_point->Y <= box.MaxEdge.Y)) {
collision_normal->set(0, 0, (dir.Z > 0) ? -1 : 1);
return true;
}
}
}
return false;
}
| pgimeno/minetest | src/raycast.cpp | C++ | mit | 3,811 |
/*
Minetest
Copyright (C) 2016 juhdanad, Daniel Juhasz <juhdanad@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "voxelalgorithms.h"
#include "util/pointedthing.h"
//! Sorts PointedThings based on their distance.
struct RaycastSort
{
bool operator() (const PointedThing &pt1, const PointedThing &pt2) const;
};
//! Describes the state of a raycast.
class RaycastState
{
public:
/*!
* Creates a raycast.
* @param objects_pointable if false, only nodes will be found
* @param liquids pointable if false, liquid nodes won't be found
*/
RaycastState(const core::line3d<f32> &shootline, bool objects_pointable,
bool liquids_pointable);
//! Shootline of the raycast.
core::line3d<f32> m_shootline;
//! Iterator to store the progress of the raycast.
voxalgo::VoxelLineIterator m_iterator;
//! Previous tested node during the raycast.
v3s16 m_previous_node;
/*!
* This priority queue stores the found pointed things
* waiting to be returned.
*/
std::priority_queue<PointedThing, std::vector<PointedThing>, RaycastSort> m_found;
bool m_objects_pointable;
bool m_liquids_pointable;
//! The code needs to search these nodes around the center node.
core::aabbox3d<s16> m_search_range { 0, 0, 0, 0, 0, 0 };
//! If true, the Environment will initialize this state.
bool m_initialization_needed = true;
};
/*!
* Checks if a line and a box intersects.
* @param[in] box box to test collision
* @param[in] start starting point of the line
* @param[in] dir direction and length of the line
* @param[out] collision_point first point of the collision
* @param[out] collision_normal normal vector at the collision, points
* outwards of the surface. If start is in the box, zero vector.
* @returns true if a collision point was found
*/
bool boxLineCollision(const aabb3f &box, const v3f &start, const v3f &dir,
v3f *collision_point, v3s16 *collision_normal);
| pgimeno/minetest | src/raycast.h | C++ | mit | 2,623 |
/*
Minetest
Copyright (C) 2016 MillersMan <millersman@users.noreply.github.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "reflowscan.h"
#include "map.h"
#include "mapblock.h"
#include "nodedef.h"
#include "util/timetaker.h"
ReflowScan::ReflowScan(Map *map, const NodeDefManager *ndef) :
m_map(map),
m_ndef(ndef)
{
}
void ReflowScan::scan(MapBlock *block, UniqueQueue<v3s16> *liquid_queue)
{
m_block_pos = block->getPos();
m_rel_block_pos = block->getPosRelative();
m_liquid_queue = liquid_queue;
// Prepare the lookup which is a 3x3x3 array of the blocks surrounding the
// scanned block. Blocks are only added to the lookup if they are really
// needed. The lookup is indexed manually to use the same index in a
// bit-array (of uint32 type) which stores for unloaded blocks that they
// were already fetched from Map but were actually nullptr.
memset(m_lookup, 0, sizeof(m_lookup));
int block_idx = 1 + (1 * 9) + (1 * 3);
m_lookup[block_idx] = block;
m_lookup_state_bitset = 1 << block_idx;
// Scan the columns in the block
for (s16 z = 0; z < MAP_BLOCKSIZE; z++)
for (s16 x = 0; x < MAP_BLOCKSIZE; x++) {
scanColumn(x, z);
}
// Scan neighbouring columns from the nearby blocks as they might contain
// liquid nodes that weren't allowed to flow to prevent gaps.
for (s16 i = 0; i < MAP_BLOCKSIZE; i++) {
scanColumn(i, -1);
scanColumn(i, MAP_BLOCKSIZE);
scanColumn(-1, i);
scanColumn(MAP_BLOCKSIZE, i);
}
}
inline MapBlock *ReflowScan::lookupBlock(int x, int y, int z)
{
// Gets the block that contains (x,y,z) relativ to the scanned block.
// This uses a lookup as there might be many lookups into the same
// neighbouring block which makes fetches from Map costly.
int bx = (MAP_BLOCKSIZE + x) / MAP_BLOCKSIZE;
int by = (MAP_BLOCKSIZE + y) / MAP_BLOCKSIZE;
int bz = (MAP_BLOCKSIZE + z) / MAP_BLOCKSIZE;
int idx = (bx + (by * 9) + (bz * 3));
MapBlock *result = m_lookup[idx];
if (!result && (m_lookup_state_bitset & (1 << idx)) == 0) {
// The block wasn't requested yet so fetch it from Map and store it
// in the lookup
v3s16 pos = m_block_pos + v3s16(bx - 1, by - 1, bz - 1);
m_lookup[idx] = result = m_map->getBlockNoCreateNoEx(pos);
m_lookup_state_bitset |= (1 << idx);
}
return result;
}
inline bool ReflowScan::isLiquidFlowableTo(int x, int y, int z)
{
// Tests whether (x,y,z) is a node to which liquid might flow.
bool valid_position;
MapBlock *block = lookupBlock(x, y, z);
if (block) {
int dx = (MAP_BLOCKSIZE + x) % MAP_BLOCKSIZE;
int dy = (MAP_BLOCKSIZE + y) % MAP_BLOCKSIZE;
int dz = (MAP_BLOCKSIZE + z) % MAP_BLOCKSIZE;
MapNode node = block->getNodeNoCheck(dx, dy, dz, &valid_position);
if (node.getContent() != CONTENT_IGNORE) {
const ContentFeatures &f = m_ndef->get(node);
// NOTE: No need to check for flowing nodes with lower liquid level
// as they should only occur on top of other columns where they
// will be added to the queue themselves.
return f.floodable;
}
}
return false;
}
inline bool ReflowScan::isLiquidHorizontallyFlowable(int x, int y, int z)
{
// Check if the (x,y,z) might spread to one of the horizontally
// neighbouring nodes
return isLiquidFlowableTo(x - 1, y, z) ||
isLiquidFlowableTo(x + 1, y, z) ||
isLiquidFlowableTo(x, y, z - 1) ||
isLiquidFlowableTo(x, y, z + 1);
}
void ReflowScan::scanColumn(int x, int z)
{
bool valid_position;
// Is the column inside a loaded block?
MapBlock *block = lookupBlock(x, 0, z);
if (!block)
return;
MapBlock *above = lookupBlock(x, MAP_BLOCKSIZE, z);
int dx = (MAP_BLOCKSIZE + x) % MAP_BLOCKSIZE;
int dz = (MAP_BLOCKSIZE + z) % MAP_BLOCKSIZE;
// Get the state from the node above the scanned block
bool was_ignore, was_liquid;
if (above) {
MapNode node = above->getNodeNoCheck(dx, 0, dz, &valid_position);
was_ignore = node.getContent() == CONTENT_IGNORE;
was_liquid = m_ndef->get(node).isLiquid();
} else {
was_ignore = true;
was_liquid = false;
}
bool was_checked = false;
bool was_pushed = false;
// Scan through the whole block
for (s16 y = MAP_BLOCKSIZE - 1; y >= 0; y--) {
MapNode node = block->getNodeNoCheck(dx, y, dz, &valid_position);
const ContentFeatures &f = m_ndef->get(node);
bool is_ignore = node.getContent() == CONTENT_IGNORE;
bool is_liquid = f.isLiquid();
if (is_ignore || was_ignore || is_liquid == was_liquid) {
// Neither topmost node of liquid column nor topmost node below column
was_checked = false;
was_pushed = false;
} else if (is_liquid) {
// This is the topmost node in the column
bool is_pushed = false;
if (f.liquid_type == LIQUID_FLOWING ||
isLiquidHorizontallyFlowable(x, y, z)) {
m_liquid_queue->push_back(m_rel_block_pos + v3s16(x, y, z));
is_pushed = true;
}
// Remember waschecked and waspushed to avoid repeated
// checks/pushes in case the column consists of only this node
was_checked = true;
was_pushed = is_pushed;
} else {
// This is the topmost node below a liquid column
if (!was_pushed && (f.floodable ||
(!was_checked && isLiquidHorizontallyFlowable(x, y + 1, z)))) {
// Activate the lowest node in the column which is one
// node above this one
m_liquid_queue->push_back(m_rel_block_pos + v3s16(x, y + 1, z));
}
}
was_liquid = is_liquid;
was_ignore = is_ignore;
}
// Check the node below the current block
MapBlock *below = lookupBlock(x, -1, z);
if (below) {
MapNode node = below->getNodeNoCheck(dx, MAP_BLOCKSIZE - 1, dz, &valid_position);
const ContentFeatures &f = m_ndef->get(node);
bool is_ignore = node.getContent() == CONTENT_IGNORE;
bool is_liquid = f.isLiquid();
if (is_ignore || was_ignore || is_liquid == was_liquid) {
// Neither topmost node of liquid column nor topmost node below column
} else if (is_liquid) {
// This is the topmost node in the column and might want to flow away
if (f.liquid_type == LIQUID_FLOWING ||
isLiquidHorizontallyFlowable(x, -1, z)) {
m_liquid_queue->push_back(m_rel_block_pos + v3s16(x, -1, z));
}
} else {
// This is the topmost node below a liquid column
if (!was_pushed && (f.floodable ||
(!was_checked && isLiquidHorizontallyFlowable(x, 0, z)))) {
// Activate the lowest node in the column which is one
// node above this one
m_liquid_queue->push_back(m_rel_block_pos + v3s16(x, 0, z));
}
}
}
}
| pgimeno/minetest | src/reflowscan.cpp | C++ | mit | 7,050 |
/*
Minetest
Copyright (C) 2016 MillersMan <millersman@users.noreply.github.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "util/container.h"
#include "irrlichttypes_bloated.h"
class NodeDefManager;
class Map;
class MapBlock;
class ReflowScan {
public:
ReflowScan(Map *map, const NodeDefManager *ndef);
void scan(MapBlock *block, UniqueQueue<v3s16> *liquid_queue);
private:
MapBlock *lookupBlock(int x, int y, int z);
bool isLiquidFlowableTo(int x, int y, int z);
bool isLiquidHorizontallyFlowable(int x, int y, int z);
void scanColumn(int x, int z);
private:
Map *m_map = nullptr;
const NodeDefManager *m_ndef = nullptr;
v3s16 m_block_pos, m_rel_block_pos;
UniqueQueue<v3s16> *m_liquid_queue = nullptr;
MapBlock *m_lookup[3 * 3 * 3];
u32 m_lookup_state_bitset;
};
| pgimeno/minetest | src/reflowscan.h | C++ | mit | 1,469 |
/*
Minetest
Copyright (C) 2010-2016 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2014-2016 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "remoteplayer.h"
#include <json/json.h>
#include "content_sao.h"
#include "filesys.h"
#include "gamedef.h"
#include "porting.h" // strlcpy
#include "server.h"
#include "settings.h"
#include "convert_json.h"
/*
RemotePlayer
*/
// static config cache for remoteplayer
bool RemotePlayer::m_setting_cache_loaded = false;
float RemotePlayer::m_setting_chat_message_limit_per_10sec = 0.0f;
u16 RemotePlayer::m_setting_chat_message_limit_trigger_kick = 0;
RemotePlayer::RemotePlayer(const char *name, IItemDefManager *idef):
Player(name, idef)
{
if (!RemotePlayer::m_setting_cache_loaded) {
RemotePlayer::m_setting_chat_message_limit_per_10sec =
g_settings->getFloat("chat_message_limit_per_10sec");
RemotePlayer::m_setting_chat_message_limit_trigger_kick =
g_settings->getU16("chat_message_limit_trigger_kick");
RemotePlayer::m_setting_cache_loaded = true;
}
movement_acceleration_default = g_settings->getFloat("movement_acceleration_default") * BS;
movement_acceleration_air = g_settings->getFloat("movement_acceleration_air") * BS;
movement_acceleration_fast = g_settings->getFloat("movement_acceleration_fast") * BS;
movement_speed_walk = g_settings->getFloat("movement_speed_walk") * BS;
movement_speed_crouch = g_settings->getFloat("movement_speed_crouch") * BS;
movement_speed_fast = g_settings->getFloat("movement_speed_fast") * BS;
movement_speed_climb = g_settings->getFloat("movement_speed_climb") * BS;
movement_speed_jump = g_settings->getFloat("movement_speed_jump") * BS;
movement_liquid_fluidity = g_settings->getFloat("movement_liquid_fluidity") * BS;
movement_liquid_fluidity_smooth = g_settings->getFloat("movement_liquid_fluidity_smooth") * BS;
movement_liquid_sink = g_settings->getFloat("movement_liquid_sink") * BS;
movement_gravity = g_settings->getFloat("movement_gravity") * BS;
// copy defaults
m_cloud_params.density = 0.4f;
m_cloud_params.color_bright = video::SColor(229, 240, 240, 255);
m_cloud_params.color_ambient = video::SColor(255, 0, 0, 0);
m_cloud_params.height = 120.0f;
m_cloud_params.thickness = 16.0f;
m_cloud_params.speed = v2f(0.0f, -2.0f);
}
void RemotePlayer::serializeExtraAttributes(std::string &output)
{
assert(m_sao);
Json::Value json_root;
const StringMap &attrs = m_sao->getMeta().getStrings();
for (const auto &attr : attrs) {
json_root[attr.first] = attr.second;
}
output = fastWriteJson(json_root);
}
void RemotePlayer::deSerialize(std::istream &is, const std::string &playername,
PlayerSAO *sao)
{
Settings args;
if (!args.parseConfigLines(is, "PlayerArgsEnd")) {
throw SerializationError("PlayerArgsEnd of player " + playername + " not found!");
}
m_dirty = true;
//args.getS32("version"); // Version field value not used
const std::string &name = args.get("name");
strlcpy(m_name, name.c_str(), PLAYERNAME_SIZE);
if (sao) {
try {
sao->setHPRaw(args.getU16("hp"));
} catch(SettingNotFoundException &e) {
sao->setHPRaw(PLAYER_MAX_HP_DEFAULT);
}
try {
sao->setBasePosition(args.getV3F("position"));
} catch (SettingNotFoundException &e) {}
try {
sao->setLookPitch(args.getFloat("pitch"));
} catch (SettingNotFoundException &e) {}
try {
sao->setPlayerYaw(args.getFloat("yaw"));
} catch (SettingNotFoundException &e) {}
try {
sao->setBreath(args.getU16("breath"), false);
} catch (SettingNotFoundException &e) {}
try {
const std::string &extended_attributes = args.get("extended_attributes");
std::istringstream iss(extended_attributes);
Json::CharReaderBuilder builder;
builder.settings_["collectComments"] = false;
std::string errs;
Json::Value attr_root;
Json::parseFromStream(builder, iss, &attr_root, &errs);
const Json::Value::Members attr_list = attr_root.getMemberNames();
for (const auto &it : attr_list) {
Json::Value attr_value = attr_root[it];
sao->getMeta().setString(it, attr_value.asString());
}
sao->getMeta().setModified(false);
} catch (SettingNotFoundException &e) {}
}
try {
inventory.deSerialize(is);
} catch (SerializationError &e) {
errorstream << "Failed to deserialize player inventory. player_name="
<< name << " " << e.what() << std::endl;
}
if (!inventory.getList("craftpreview") && inventory.getList("craftresult")) {
// Convert players without craftpreview
inventory.addList("craftpreview", 1);
bool craftresult_is_preview = true;
if(args.exists("craftresult_is_preview"))
craftresult_is_preview = args.getBool("craftresult_is_preview");
if(craftresult_is_preview)
{
// Clear craftresult
inventory.getList("craftresult")->changeItem(0, ItemStack());
}
}
}
void RemotePlayer::serialize(std::ostream &os)
{
// Utilize a Settings object for storing values
Settings args;
args.setS32("version", 1);
args.set("name", m_name);
// This should not happen
assert(m_sao);
args.setU16("hp", m_sao->getHP());
args.setV3F("position", m_sao->getBasePosition());
args.setFloat("pitch", m_sao->getLookPitch());
args.setFloat("yaw", m_sao->getRotation().Y);
args.setU16("breath", m_sao->getBreath());
std::string extended_attrs;
serializeExtraAttributes(extended_attrs);
args.set("extended_attributes", extended_attrs);
args.writeLines(os);
os<<"PlayerArgsEnd\n";
inventory.serialize(os);
}
const RemotePlayerChatResult RemotePlayer::canSendChatMessage()
{
// Rate limit messages
u32 now = time(NULL);
float time_passed = now - m_last_chat_message_sent;
m_last_chat_message_sent = now;
// If this feature is disabled
if (m_setting_chat_message_limit_per_10sec <= 0.0) {
return RPLAYER_CHATRESULT_OK;
}
m_chat_message_allowance += time_passed * (m_setting_chat_message_limit_per_10sec / 8.0f);
if (m_chat_message_allowance > m_setting_chat_message_limit_per_10sec) {
m_chat_message_allowance = m_setting_chat_message_limit_per_10sec;
}
if (m_chat_message_allowance < 1.0f) {
infostream << "Player " << m_name
<< " chat limited due to excessive message amount." << std::endl;
// Kick player if flooding is too intensive
m_message_rate_overhead++;
if (m_message_rate_overhead > RemotePlayer::m_setting_chat_message_limit_trigger_kick) {
return RPLAYER_CHATRESULT_KICK;
}
return RPLAYER_CHATRESULT_FLOODING;
}
// Reinit message overhead
if (m_message_rate_overhead > 0) {
m_message_rate_overhead = 0;
}
m_chat_message_allowance -= 1.0f;
return RPLAYER_CHATRESULT_OK;
}
void RemotePlayer::onSuccessfulSave()
{
setModified(false);
if (m_sao)
m_sao->getMeta().setModified(false);
}
| pgimeno/minetest | src/remoteplayer.cpp | C++ | mit | 7,590 |
/*
Minetest
Copyright (C) 2010-2016 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2014-2016 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "player.h"
#include "cloudparams.h"
class PlayerSAO;
enum RemotePlayerChatResult
{
RPLAYER_CHATRESULT_OK,
RPLAYER_CHATRESULT_FLOODING,
RPLAYER_CHATRESULT_KICK,
};
/*
Player on the server
*/
class RemotePlayer : public Player
{
friend class PlayerDatabaseFiles;
public:
RemotePlayer(const char *name, IItemDefManager *idef);
virtual ~RemotePlayer() = default;
void deSerialize(std::istream &is, const std::string &playername, PlayerSAO *sao);
PlayerSAO *getPlayerSAO() { return m_sao; }
void setPlayerSAO(PlayerSAO *sao) { m_sao = sao; }
const RemotePlayerChatResult canSendChatMessage();
void setHotbarItemcount(s32 hotbar_itemcount)
{
hud_hotbar_itemcount = hotbar_itemcount;
}
s32 getHotbarItemcount() const { return hud_hotbar_itemcount; }
void overrideDayNightRatio(bool do_override, float ratio)
{
m_day_night_ratio_do_override = do_override;
m_day_night_ratio = ratio;
}
void getDayNightRatio(bool *do_override, float *ratio)
{
*do_override = m_day_night_ratio_do_override;
*ratio = m_day_night_ratio;
}
void setHotbarImage(const std::string &name) { hud_hotbar_image = name; }
const std::string &getHotbarImage() const { return hud_hotbar_image; }
void setHotbarSelectedImage(const std::string &name)
{
hud_hotbar_selected_image = name;
}
const std::string &getHotbarSelectedImage() const
{
return hud_hotbar_selected_image;
}
void setSky(const video::SColor &bgcolor, const std::string &type,
const std::vector<std::string> ¶ms, bool &clouds)
{
m_sky_bgcolor = bgcolor;
m_sky_type = type;
m_sky_params = params;
m_sky_clouds = clouds;
}
void getSky(video::SColor *bgcolor, std::string *type,
std::vector<std::string> *params, bool *clouds)
{
*bgcolor = m_sky_bgcolor;
*type = m_sky_type;
*params = m_sky_params;
*clouds = m_sky_clouds;
}
void setCloudParams(const CloudParams &cloud_params)
{
m_cloud_params = cloud_params;
}
const CloudParams &getCloudParams() const { return m_cloud_params; }
bool checkModified() const { return m_dirty || inventory.checkModified(); }
void setModified(const bool x)
{
m_dirty = x;
if (!x)
inventory.setModified(x);
}
void setLocalAnimations(v2s32 frames[4], float frame_speed)
{
for (int i = 0; i < 4; i++)
local_animations[i] = frames[i];
local_animation_speed = frame_speed;
}
void getLocalAnimations(v2s32 *frames, float *frame_speed)
{
for (int i = 0; i < 4; i++)
frames[i] = local_animations[i];
*frame_speed = local_animation_speed;
}
void setDirty(bool dirty) { m_dirty = true; }
u16 protocol_version = 0;
session_t getPeerId() const { return m_peer_id; }
void setPeerId(session_t peer_id) { m_peer_id = peer_id; }
void onSuccessfulSave();
private:
/*
serialize() writes a bunch of text that can contain
any characters except a '\0', and such an ending that
deSerialize stops reading exactly at the right point.
*/
void serialize(std::ostream &os);
void serializeExtraAttributes(std::string &output);
PlayerSAO *m_sao = nullptr;
bool m_dirty = false;
static bool m_setting_cache_loaded;
static float m_setting_chat_message_limit_per_10sec;
static u16 m_setting_chat_message_limit_trigger_kick;
u32 m_last_chat_message_sent = std::time(0);
float m_chat_message_allowance = 5.0f;
u16 m_message_rate_overhead = 0;
bool m_day_night_ratio_do_override = false;
float m_day_night_ratio;
std::string hud_hotbar_image = "";
std::string hud_hotbar_selected_image = "";
std::string m_sky_type;
video::SColor m_sky_bgcolor;
std::vector<std::string> m_sky_params;
bool m_sky_clouds;
CloudParams m_cloud_params;
session_t m_peer_id = PEER_ID_INEXISTENT;
};
| pgimeno/minetest | src/remoteplayer.h | C++ | mit | 4,562 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "rollback.h"
#include <fstream>
#include <list>
#include <sstream>
#include "log.h"
#include "mapnode.h"
#include "gamedef.h"
#include "nodedef.h"
#include "util/serialize.h"
#include "util/string.h"
#include "util/numeric.h"
#include "inventorymanager.h" // deserializing InventoryLocations
#include "sqlite3.h"
#include "filesys.h"
#define POINTS_PER_NODE (16.0)
#define SQLRES(f, good) \
if ((f) != (good)) {\
throw FileNotGoodException(std::string("RollbackManager: " \
"SQLite3 error (" __FILE__ ":" TOSTRING(__LINE__) \
"): ") + sqlite3_errmsg(db)); \
}
#define SQLOK(f) SQLRES(f, SQLITE_OK)
#define SQLOK_ERRSTREAM(s, m) \
if ((s) != SQLITE_OK) { \
errorstream << "RollbackManager: " << (m) << ": " \
<< sqlite3_errmsg(db) << std::endl; \
}
#define FINALIZE_STATEMENT(statement) \
SQLOK_ERRSTREAM(sqlite3_finalize(statement), "Failed to finalize " #statement)
class ItemStackRow : public ItemStack {
public:
ItemStackRow & operator = (const ItemStack & other)
{
*static_cast<ItemStack *>(this) = other;
return *this;
}
int id;
};
struct ActionRow {
int id;
int actor;
time_t timestamp;
int type;
std::string location, list;
int index, add;
ItemStackRow stack;
int nodeMeta;
int x, y, z;
int oldNode;
int oldParam1, oldParam2;
std::string oldMeta;
int newNode;
int newParam1, newParam2;
std::string newMeta;
int guessed;
};
struct Entity {
int id;
std::string name;
};
RollbackManager::RollbackManager(const std::string & world_path,
IGameDef * gamedef_) :
gamedef(gamedef_)
{
verbosestream << "RollbackManager::RollbackManager(" << world_path
<< ")" << std::endl;
std::string txt_filename = world_path + DIR_DELIM "rollback.txt";
std::string migrating_flag = txt_filename + ".migrating";
database_path = world_path + DIR_DELIM "rollback.sqlite";
bool created = initDatabase();
if (fs::PathExists(txt_filename) && (created ||
fs::PathExists(migrating_flag))) {
std::ofstream of(migrating_flag.c_str());
of.close();
migrate(txt_filename);
fs::DeleteSingleFileOrEmptyDirectory(migrating_flag);
}
}
RollbackManager::~RollbackManager()
{
flush();
FINALIZE_STATEMENT(stmt_insert);
FINALIZE_STATEMENT(stmt_replace);
FINALIZE_STATEMENT(stmt_select);
FINALIZE_STATEMENT(stmt_select_range);
FINALIZE_STATEMENT(stmt_select_withActor);
FINALIZE_STATEMENT(stmt_knownActor_select);
FINALIZE_STATEMENT(stmt_knownActor_insert);
FINALIZE_STATEMENT(stmt_knownNode_select);
FINALIZE_STATEMENT(stmt_knownNode_insert);
SQLOK_ERRSTREAM(sqlite3_close(db), "Could not close db");
}
void RollbackManager::registerNewActor(const int id, const std::string &name)
{
Entity actor = {id, name};
knownActors.push_back(actor);
}
void RollbackManager::registerNewNode(const int id, const std::string &name)
{
Entity node = {id, name};
knownNodes.push_back(node);
}
int RollbackManager::getActorId(const std::string &name)
{
for (std::vector<Entity>::const_iterator iter = knownActors.begin();
iter != knownActors.end(); ++iter) {
if (iter->name == name) {
return iter->id;
}
}
SQLOK(sqlite3_bind_text(stmt_knownActor_insert, 1, name.c_str(), name.size(), NULL));
SQLRES(sqlite3_step(stmt_knownActor_insert), SQLITE_DONE);
SQLOK(sqlite3_reset(stmt_knownActor_insert));
int id = sqlite3_last_insert_rowid(db);
registerNewActor(id, name);
return id;
}
int RollbackManager::getNodeId(const std::string &name)
{
for (std::vector<Entity>::const_iterator iter = knownNodes.begin();
iter != knownNodes.end(); ++iter) {
if (iter->name == name) {
return iter->id;
}
}
SQLOK(sqlite3_bind_text(stmt_knownNode_insert, 1, name.c_str(), name.size(), NULL));
SQLRES(sqlite3_step(stmt_knownNode_insert), SQLITE_DONE);
SQLOK(sqlite3_reset(stmt_knownNode_insert));
int id = sqlite3_last_insert_rowid(db);
registerNewNode(id, name);
return id;
}
const char * RollbackManager::getActorName(const int id)
{
for (std::vector<Entity>::const_iterator iter = knownActors.begin();
iter != knownActors.end(); ++iter) {
if (iter->id == id) {
return iter->name.c_str();
}
}
return "";
}
const char * RollbackManager::getNodeName(const int id)
{
for (std::vector<Entity>::const_iterator iter = knownNodes.begin();
iter != knownNodes.end(); ++iter) {
if (iter->id == id) {
return iter->name.c_str();
}
}
return "";
}
bool RollbackManager::createTables()
{
SQLOK(sqlite3_exec(db,
"CREATE TABLE IF NOT EXISTS `actor` (\n"
" `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n"
" `name` TEXT NOT NULL\n"
");\n"
"CREATE TABLE IF NOT EXISTS `node` (\n"
" `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n"
" `name` TEXT NOT NULL\n"
");\n"
"CREATE TABLE IF NOT EXISTS `action` (\n"
" `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n"
" `actor` INTEGER NOT NULL,\n"
" `timestamp` TIMESTAMP NOT NULL,\n"
" `type` INTEGER NOT NULL,\n"
" `list` TEXT,\n"
" `index` INTEGER,\n"
" `add` INTEGER,\n"
" `stackNode` INTEGER,\n"
" `stackQuantity` INTEGER,\n"
" `nodeMeta` INTEGER,\n"
" `x` INT,\n"
" `y` INT,\n"
" `z` INT,\n"
" `oldNode` INTEGER,\n"
" `oldParam1` INTEGER,\n"
" `oldParam2` INTEGER,\n"
" `oldMeta` TEXT,\n"
" `newNode` INTEGER,\n"
" `newParam1` INTEGER,\n"
" `newParam2` INTEGER,\n"
" `newMeta` TEXT,\n"
" `guessedActor` INTEGER,\n"
" FOREIGN KEY (`actor`) REFERENCES `actor`(`id`),\n"
" FOREIGN KEY (`stackNode`) REFERENCES `node`(`id`),\n"
" FOREIGN KEY (`oldNode`) REFERENCES `node`(`id`),\n"
" FOREIGN KEY (`newNode`) REFERENCES `node`(`id`)\n"
");\n"
"CREATE INDEX IF NOT EXISTS `actionIndex` ON `action`(`x`,`y`,`z`,`timestamp`,`actor`);\n",
NULL, NULL, NULL));
verbosestream << "SQL Rollback: SQLite3 database structure was created" << std::endl;
return true;
}
bool RollbackManager::initDatabase()
{
verbosestream << "RollbackManager: Database connection setup" << std::endl;
bool needs_create = !fs::PathExists(database_path);
SQLOK(sqlite3_open_v2(database_path.c_str(), &db,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL));
if (needs_create) {
createTables();
}
SQLOK(sqlite3_prepare_v2(db,
"INSERT INTO `action` (\n"
" `actor`, `timestamp`, `type`,\n"
" `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,\n"
" `x`, `y`, `z`,\n"
" `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
" `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
" `guessedActor`\n"
") VALUES (\n"
" ?, ?, ?,\n"
" ?, ?, ?, ?, ?, ?,\n"
" ?, ?, ?,\n"
" ?, ?, ?, ?,\n"
" ?, ?, ?, ?,\n"
" ?"
");",
-1, &stmt_insert, NULL));
SQLOK(sqlite3_prepare_v2(db,
"REPLACE INTO `action` (\n"
" `actor`, `timestamp`, `type`,\n"
" `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodeMeta`,\n"
" `x`, `y`, `z`,\n"
" `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
" `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
" `guessedActor`, `id`\n"
") VALUES (\n"
" ?, ?, ?,\n"
" ?, ?, ?, ?, ?, ?,\n"
" ?, ?, ?,\n"
" ?, ?, ?, ?,\n"
" ?, ?, ?, ?,\n"
" ?, ?\n"
");",
-1, &stmt_replace, NULL));
SQLOK(sqlite3_prepare_v2(db,
"SELECT\n"
" `actor`, `timestamp`, `type`,\n"
" `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
" `x`, `y`, `z`,\n"
" `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
" `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
" `guessedActor`\n"
" FROM `action`\n"
" WHERE `timestamp` >= ?\n"
" ORDER BY `timestamp` DESC, `id` DESC",
-1, &stmt_select, NULL));
SQLOK(sqlite3_prepare_v2(db,
"SELECT\n"
" `actor`, `timestamp`, `type`,\n"
" `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
" `x`, `y`, `z`,\n"
" `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
" `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
" `guessedActor`\n"
"FROM `action`\n"
"WHERE `timestamp` >= ?\n"
" AND `x` IS NOT NULL\n"
" AND `y` IS NOT NULL\n"
" AND `z` IS NOT NULL\n"
" AND `x` BETWEEN ? AND ?\n"
" AND `y` BETWEEN ? AND ?\n"
" AND `z` BETWEEN ? AND ?\n"
"ORDER BY `timestamp` DESC, `id` DESC\n"
"LIMIT 0,?",
-1, &stmt_select_range, NULL));
SQLOK(sqlite3_prepare_v2(db,
"SELECT\n"
" `actor`, `timestamp`, `type`,\n"
" `list`, `index`, `add`, `stackNode`, `stackQuantity`, `nodemeta`,\n"
" `x`, `y`, `z`,\n"
" `oldNode`, `oldParam1`, `oldParam2`, `oldMeta`,\n"
" `newNode`, `newParam1`, `newParam2`, `newMeta`,\n"
" `guessedActor`\n"
"FROM `action`\n"
"WHERE `timestamp` >= ?\n"
" AND `actor` = ?\n"
"ORDER BY `timestamp` DESC, `id` DESC\n",
-1, &stmt_select_withActor, NULL));
SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `actor`",
-1, &stmt_knownActor_select, NULL));
SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `actor` (`name`) VALUES (?)",
-1, &stmt_knownActor_insert, NULL));
SQLOK(sqlite3_prepare_v2(db, "SELECT `id`, `name` FROM `node`",
-1, &stmt_knownNode_select, NULL));
SQLOK(sqlite3_prepare_v2(db, "INSERT INTO `node` (`name`) VALUES (?)",
-1, &stmt_knownNode_insert, NULL));
verbosestream << "SQL prepared statements setup correctly" << std::endl;
while (sqlite3_step(stmt_knownActor_select) == SQLITE_ROW) {
registerNewActor(
sqlite3_column_int(stmt_knownActor_select, 0),
reinterpret_cast<const char *>(sqlite3_column_text(stmt_knownActor_select, 1))
);
}
SQLOK(sqlite3_reset(stmt_knownActor_select));
while (sqlite3_step(stmt_knownNode_select) == SQLITE_ROW) {
registerNewNode(
sqlite3_column_int(stmt_knownNode_select, 0),
reinterpret_cast<const char *>(sqlite3_column_text(stmt_knownNode_select, 1))
);
}
SQLOK(sqlite3_reset(stmt_knownNode_select));
return needs_create;
}
bool RollbackManager::registerRow(const ActionRow & row)
{
sqlite3_stmt * stmt_do = (row.id) ? stmt_replace : stmt_insert;
bool nodeMeta = false;
SQLOK(sqlite3_bind_int (stmt_do, 1, row.actor));
SQLOK(sqlite3_bind_int64(stmt_do, 2, row.timestamp));
SQLOK(sqlite3_bind_int (stmt_do, 3, row.type));
if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
const std::string & loc = row.location;
nodeMeta = (loc.substr(0, 9) == "nodemeta:");
SQLOK(sqlite3_bind_text(stmt_do, 4, row.list.c_str(), row.list.size(), NULL));
SQLOK(sqlite3_bind_int (stmt_do, 5, row.index));
SQLOK(sqlite3_bind_int (stmt_do, 6, row.add));
SQLOK(sqlite3_bind_int (stmt_do, 7, row.stack.id));
SQLOK(sqlite3_bind_int (stmt_do, 8, row.stack.count));
SQLOK(sqlite3_bind_int (stmt_do, 9, (int) nodeMeta));
if (nodeMeta) {
std::string::size_type p1, p2;
p1 = loc.find(':') + 1;
p2 = loc.find(',');
std::string x = loc.substr(p1, p2 - p1);
p1 = p2 + 1;
p2 = loc.find(',', p1);
std::string y = loc.substr(p1, p2 - p1);
std::string z = loc.substr(p2 + 1);
SQLOK(sqlite3_bind_int(stmt_do, 10, atoi(x.c_str())));
SQLOK(sqlite3_bind_int(stmt_do, 11, atoi(y.c_str())));
SQLOK(sqlite3_bind_int(stmt_do, 12, atoi(z.c_str())));
}
} else {
SQLOK(sqlite3_bind_null(stmt_do, 4));
SQLOK(sqlite3_bind_null(stmt_do, 5));
SQLOK(sqlite3_bind_null(stmt_do, 6));
SQLOK(sqlite3_bind_null(stmt_do, 7));
SQLOK(sqlite3_bind_null(stmt_do, 8));
SQLOK(sqlite3_bind_null(stmt_do, 9));
}
if (row.type == RollbackAction::TYPE_SET_NODE) {
SQLOK(sqlite3_bind_int (stmt_do, 10, row.x));
SQLOK(sqlite3_bind_int (stmt_do, 11, row.y));
SQLOK(sqlite3_bind_int (stmt_do, 12, row.z));
SQLOK(sqlite3_bind_int (stmt_do, 13, row.oldNode));
SQLOK(sqlite3_bind_int (stmt_do, 14, row.oldParam1));
SQLOK(sqlite3_bind_int (stmt_do, 15, row.oldParam2));
SQLOK(sqlite3_bind_text(stmt_do, 16, row.oldMeta.c_str(), row.oldMeta.size(), NULL));
SQLOK(sqlite3_bind_int (stmt_do, 17, row.newNode));
SQLOK(sqlite3_bind_int (stmt_do, 18, row.newParam1));
SQLOK(sqlite3_bind_int (stmt_do, 19, row.newParam2));
SQLOK(sqlite3_bind_text(stmt_do, 20, row.newMeta.c_str(), row.newMeta.size(), NULL));
SQLOK(sqlite3_bind_int (stmt_do, 21, row.guessed ? 1 : 0));
} else {
if (!nodeMeta) {
SQLOK(sqlite3_bind_null(stmt_do, 10));
SQLOK(sqlite3_bind_null(stmt_do, 11));
SQLOK(sqlite3_bind_null(stmt_do, 12));
}
SQLOK(sqlite3_bind_null(stmt_do, 13));
SQLOK(sqlite3_bind_null(stmt_do, 14));
SQLOK(sqlite3_bind_null(stmt_do, 15));
SQLOK(sqlite3_bind_null(stmt_do, 16));
SQLOK(sqlite3_bind_null(stmt_do, 17));
SQLOK(sqlite3_bind_null(stmt_do, 18));
SQLOK(sqlite3_bind_null(stmt_do, 19));
SQLOK(sqlite3_bind_null(stmt_do, 20));
SQLOK(sqlite3_bind_null(stmt_do, 21));
}
if (row.id) {
SQLOK(sqlite3_bind_int(stmt_do, 22, row.id));
}
int written = sqlite3_step(stmt_do);
SQLOK(sqlite3_reset(stmt_do));
return written == SQLITE_DONE;
}
const std::list<ActionRow> RollbackManager::actionRowsFromSelect(sqlite3_stmt* stmt)
{
std::list<ActionRow> rows;
const unsigned char * text;
size_t size;
while (sqlite3_step(stmt) == SQLITE_ROW) {
ActionRow row;
row.actor = sqlite3_column_int (stmt, 0);
row.timestamp = sqlite3_column_int64(stmt, 1);
row.type = sqlite3_column_int (stmt, 2);
if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
text = sqlite3_column_text (stmt, 3);
size = sqlite3_column_bytes(stmt, 3);
row.list = std::string(reinterpret_cast<const char*>(text), size);
row.index = sqlite3_column_int(stmt, 4);
row.add = sqlite3_column_int(stmt, 5);
row.stack.id = sqlite3_column_int(stmt, 6);
row.stack.count = sqlite3_column_int(stmt, 7);
row.nodeMeta = sqlite3_column_int(stmt, 8);
}
if (row.type == RollbackAction::TYPE_SET_NODE || row.nodeMeta) {
row.x = sqlite3_column_int(stmt, 9);
row.y = sqlite3_column_int(stmt, 10);
row.z = sqlite3_column_int(stmt, 11);
}
if (row.type == RollbackAction::TYPE_SET_NODE) {
row.oldNode = sqlite3_column_int(stmt, 12);
row.oldParam1 = sqlite3_column_int(stmt, 13);
row.oldParam2 = sqlite3_column_int(stmt, 14);
text = sqlite3_column_text (stmt, 15);
size = sqlite3_column_bytes(stmt, 15);
row.oldMeta = std::string(reinterpret_cast<const char*>(text), size);
row.newNode = sqlite3_column_int(stmt, 16);
row.newParam1 = sqlite3_column_int(stmt, 17);
row.newParam2 = sqlite3_column_int(stmt, 18);
text = sqlite3_column_text(stmt, 19);
size = sqlite3_column_bytes(stmt, 19);
row.newMeta = std::string(reinterpret_cast<const char*>(text), size);
row.guessed = sqlite3_column_int(stmt, 20);
}
if (row.nodeMeta) {
row.location = "nodemeta:";
row.location += itos(row.x);
row.location += ',';
row.location += itos(row.y);
row.location += ',';
row.location += itos(row.z);
} else {
row.location = getActorName(row.actor);
}
rows.push_back(row);
}
SQLOK(sqlite3_reset(stmt));
return rows;
}
ActionRow RollbackManager::actionRowFromRollbackAction(const RollbackAction & action)
{
ActionRow row;
row.id = 0;
row.actor = getActorId(action.actor);
row.timestamp = action.unix_time;
row.type = action.type;
if (row.type == RollbackAction::TYPE_MODIFY_INVENTORY_STACK) {
row.location = action.inventory_location;
row.list = action.inventory_list;
row.index = action.inventory_index;
row.add = action.inventory_add;
row.stack = action.inventory_stack;
row.stack.id = getNodeId(row.stack.name);
} else {
row.x = action.p.X;
row.y = action.p.Y;
row.z = action.p.Z;
row.oldNode = getNodeId(action.n_old.name);
row.oldParam1 = action.n_old.param1;
row.oldParam2 = action.n_old.param2;
row.oldMeta = action.n_old.meta;
row.newNode = getNodeId(action.n_new.name);
row.newParam1 = action.n_new.param1;
row.newParam2 = action.n_new.param2;
row.newMeta = action.n_new.meta;
row.guessed = action.actor_is_guess;
}
return row;
}
const std::list<RollbackAction> RollbackManager::rollbackActionsFromActionRows(
const std::list<ActionRow> & rows)
{
std::list<RollbackAction> actions;
for (const ActionRow &row : rows) {
RollbackAction action;
action.actor = (row.actor) ? getActorName(row.actor) : "";
action.unix_time = row.timestamp;
action.type = static_cast<RollbackAction::Type>(row.type);
switch (action.type) {
case RollbackAction::TYPE_MODIFY_INVENTORY_STACK:
action.inventory_location = row.location;
action.inventory_list = row.list;
action.inventory_index = row.index;
action.inventory_add = row.add;
action.inventory_stack = row.stack;
if (action.inventory_stack.name.empty()) {
action.inventory_stack.name = getNodeName(row.stack.id);
}
break;
case RollbackAction::TYPE_SET_NODE:
action.p = v3s16(row.x, row.y, row.z);
action.n_old.name = getNodeName(row.oldNode);
action.n_old.param1 = row.oldParam1;
action.n_old.param2 = row.oldParam2;
action.n_old.meta = row.oldMeta;
action.n_new.name = getNodeName(row.newNode);
action.n_new.param1 = row.newParam1;
action.n_new.param2 = row.newParam2;
action.n_new.meta = row.newMeta;
break;
default:
throw ("W.T.F.");
break;
}
actions.push_back(action);
}
return actions;
}
const std::list<ActionRow> RollbackManager::getRowsSince(time_t firstTime, const std::string & actor)
{
sqlite3_stmt *stmt_stmt = actor.empty() ? stmt_select : stmt_select_withActor;
sqlite3_bind_int64(stmt_stmt, 1, firstTime);
if (!actor.empty()) {
sqlite3_bind_int(stmt_stmt, 2, getActorId(actor));
}
const std::list<ActionRow> & rows = actionRowsFromSelect(stmt_stmt);
sqlite3_reset(stmt_stmt);
return rows;
}
const std::list<ActionRow> RollbackManager::getRowsSince_range(
time_t start_time, v3s16 p, int range, int limit)
{
sqlite3_bind_int64(stmt_select_range, 1, start_time);
sqlite3_bind_int (stmt_select_range, 2, static_cast<int>(p.X - range));
sqlite3_bind_int (stmt_select_range, 3, static_cast<int>(p.X + range));
sqlite3_bind_int (stmt_select_range, 4, static_cast<int>(p.Y - range));
sqlite3_bind_int (stmt_select_range, 5, static_cast<int>(p.Y + range));
sqlite3_bind_int (stmt_select_range, 6, static_cast<int>(p.Z - range));
sqlite3_bind_int (stmt_select_range, 7, static_cast<int>(p.Z + range));
sqlite3_bind_int (stmt_select_range, 8, limit);
const std::list<ActionRow> & rows = actionRowsFromSelect(stmt_select_range);
sqlite3_reset(stmt_select_range);
return rows;
}
const std::list<RollbackAction> RollbackManager::getActionsSince_range(
time_t start_time, v3s16 p, int range, int limit)
{
return rollbackActionsFromActionRows(getRowsSince_range(start_time, p, range, limit));
}
const std::list<RollbackAction> RollbackManager::getActionsSince(
time_t start_time, const std::string & actor)
{
return rollbackActionsFromActionRows(getRowsSince(start_time, actor));
}
void RollbackManager::migrate(const std::string & file_path)
{
std::cout << "Migrating from rollback.txt to rollback.sqlite." << std::endl;
std::ifstream fh(file_path.c_str(), std::ios::in | std::ios::ate);
if (!fh.good()) {
throw FileNotGoodException("Unable to open rollback.txt");
}
std::streampos file_size = fh.tellg();
if (file_size < 10) {
errorstream << "Empty rollback log." << std::endl;
return;
}
fh.seekg(0);
sqlite3_stmt *stmt_begin;
sqlite3_stmt *stmt_commit;
SQLOK(sqlite3_prepare_v2(db, "BEGIN", -1, &stmt_begin, NULL));
SQLOK(sqlite3_prepare_v2(db, "COMMIT", -1, &stmt_commit, NULL));
std::string bit;
int i = 0;
time_t start = time(0);
time_t t = start;
SQLRES(sqlite3_step(stmt_begin), SQLITE_DONE);
sqlite3_reset(stmt_begin);
do {
ActionRow row;
row.id = 0;
// Get the timestamp
std::getline(fh, bit, ' ');
bit = trim(bit);
if (!atoi(bit.c_str())) {
std::getline(fh, bit);
continue;
}
row.timestamp = atoi(bit.c_str());
// Get the actor
row.actor = getActorId(deSerializeJsonString(fh));
// Get the action type
std::getline(fh, bit, '[');
std::getline(fh, bit, ' ');
if (bit == "modify_inventory_stack") {
row.type = RollbackAction::TYPE_MODIFY_INVENTORY_STACK;
row.location = trim(deSerializeJsonString(fh));
std::getline(fh, bit, ' ');
row.list = trim(deSerializeJsonString(fh));
std::getline(fh, bit, ' ');
std::getline(fh, bit, ' ');
row.index = atoi(trim(bit).c_str());
std::getline(fh, bit, ' ');
row.add = (int)(trim(bit) == "add");
row.stack.deSerialize(deSerializeJsonString(fh));
row.stack.id = getNodeId(row.stack.name);
std::getline(fh, bit);
} else if (bit == "set_node") {
row.type = RollbackAction::TYPE_SET_NODE;
std::getline(fh, bit, '(');
std::getline(fh, bit, ',');
row.x = atoi(trim(bit).c_str());
std::getline(fh, bit, ',');
row.y = atoi(trim(bit).c_str());
std::getline(fh, bit, ')');
row.z = atoi(trim(bit).c_str());
std::getline(fh, bit, ' ');
row.oldNode = getNodeId(trim(deSerializeJsonString(fh)));
std::getline(fh, bit, ' ');
std::getline(fh, bit, ' ');
row.oldParam1 = atoi(trim(bit).c_str());
std::getline(fh, bit, ' ');
row.oldParam2 = atoi(trim(bit).c_str());
row.oldMeta = trim(deSerializeJsonString(fh));
std::getline(fh, bit, ' ');
row.newNode = getNodeId(trim(deSerializeJsonString(fh)));
std::getline(fh, bit, ' ');
std::getline(fh, bit, ' ');
row.newParam1 = atoi(trim(bit).c_str());
std::getline(fh, bit, ' ');
row.newParam2 = atoi(trim(bit).c_str());
row.newMeta = trim(deSerializeJsonString(fh));
std::getline(fh, bit, ' ');
std::getline(fh, bit, ' ');
std::getline(fh, bit);
row.guessed = (int)(trim(bit) == "actor_is_guess");
} else {
errorstream << "Unrecognized rollback action type \""
<< bit << "\"!" << std::endl;
continue;
}
registerRow(row);
++i;
if (time(0) - t >= 1) {
SQLRES(sqlite3_step(stmt_commit), SQLITE_DONE);
sqlite3_reset(stmt_commit);
t = time(0);
std::cout
<< " Done: " << static_cast<int>((static_cast<float>(fh.tellg()) / static_cast<float>(file_size)) * 100) << "%"
<< " Speed: " << i / (t - start) << "/second \r" << std::flush;
SQLRES(sqlite3_step(stmt_begin), SQLITE_DONE);
sqlite3_reset(stmt_begin);
}
} while (fh.good());
SQLRES(sqlite3_step(stmt_commit), SQLITE_DONE);
sqlite3_reset(stmt_commit);
SQLOK(sqlite3_finalize(stmt_begin));
SQLOK(sqlite3_finalize(stmt_commit));
std::cout
<< " Done: 100% " << std::endl
<< "Now you can delete the old rollback.txt file." << std::endl;
}
// Get nearness factor for subject's action for this action
// Return value: 0 = impossible, >0 = factor
float RollbackManager::getSuspectNearness(bool is_guess, v3s16 suspect_p,
time_t suspect_t, v3s16 action_p, time_t action_t)
{
// Suspect cannot cause things in the past
if (action_t < suspect_t) {
return 0; // 0 = cannot be
}
// Start from 100
int f = 100;
// Distance (1 node = -x points)
f -= POINTS_PER_NODE * intToFloat(suspect_p, 1).getDistanceFrom(intToFloat(action_p, 1));
// Time (1 second = -x points)
f -= 1 * (action_t - suspect_t);
// If is a guess, halve the points
if (is_guess) {
f *= 0.5;
}
// Limit to 0
if (f < 0) {
f = 0;
}
return f;
}
void RollbackManager::reportAction(const RollbackAction &action_)
{
// Ignore if not important
if (!action_.isImportant(gamedef)) {
return;
}
RollbackAction action = action_;
action.unix_time = time(0);
// Figure out actor
action.actor = current_actor;
action.actor_is_guess = current_actor_is_guess;
if (action.actor.empty()) { // If actor is not known, find out suspect or cancel
v3s16 p;
if (!action.getPosition(&p)) {
return;
}
action.actor = getSuspect(p, 83, 1);
if (action.actor.empty()) {
return;
}
action.actor_is_guess = true;
}
addAction(action);
}
std::string RollbackManager::getActor()
{
return current_actor;
}
bool RollbackManager::isActorGuess()
{
return current_actor_is_guess;
}
void RollbackManager::setActor(const std::string & actor, bool is_guess)
{
current_actor = actor;
current_actor_is_guess = is_guess;
}
std::string RollbackManager::getSuspect(v3s16 p, float nearness_shortcut,
float min_nearness)
{
if (!current_actor.empty()) {
return current_actor;
}
int cur_time = time(0);
time_t first_time = cur_time - (100 - min_nearness);
RollbackAction likely_suspect;
float likely_suspect_nearness = 0;
for (std::list<RollbackAction>::const_reverse_iterator
i = action_latest_buffer.rbegin();
i != action_latest_buffer.rend(); ++i) {
if (i->unix_time < first_time) {
break;
}
if (i->actor.empty()) {
continue;
}
// Find position of suspect or continue
v3s16 suspect_p;
if (!i->getPosition(&suspect_p)) {
continue;
}
float f = getSuspectNearness(i->actor_is_guess, suspect_p,
i->unix_time, p, cur_time);
if (f >= min_nearness && f > likely_suspect_nearness) {
likely_suspect_nearness = f;
likely_suspect = *i;
if (likely_suspect_nearness >= nearness_shortcut) {
break;
}
}
}
// No likely suspect was found
if (likely_suspect_nearness == 0) {
return "";
}
// Likely suspect was found
return likely_suspect.actor;
}
void RollbackManager::flush()
{
sqlite3_exec(db, "BEGIN", NULL, NULL, NULL);
std::list<RollbackAction>::const_iterator iter;
for (iter = action_todisk_buffer.begin();
iter != action_todisk_buffer.end();
++iter) {
if (iter->actor.empty()) {
continue;
}
registerRow(actionRowFromRollbackAction(*iter));
}
sqlite3_exec(db, "COMMIT", NULL, NULL, NULL);
action_todisk_buffer.clear();
}
void RollbackManager::addAction(const RollbackAction & action)
{
action_todisk_buffer.push_back(action);
action_latest_buffer.push_back(action);
// Flush to disk sometimes
if (action_todisk_buffer.size() >= 500) {
flush();
}
}
std::list<RollbackAction> RollbackManager::getEntriesSince(time_t first_time)
{
flush();
return getActionsSince(first_time);
}
std::list<RollbackAction> RollbackManager::getNodeActors(v3s16 pos, int range,
time_t seconds, int limit)
{
flush();
time_t cur_time = time(0);
time_t first_time = cur_time - seconds;
return getActionsSince_range(first_time, pos, range, limit);
}
std::list<RollbackAction> RollbackManager::getRevertActions(
const std::string &actor_filter,
time_t seconds)
{
time_t cur_time = time(0);
time_t first_time = cur_time - seconds;
flush();
return getActionsSince(first_time, actor_filter);
}
| pgimeno/minetest | src/rollback.cpp | C++ | mit | 27,394 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include <string>
#include "irr_v3d.h"
#include "rollback_interface.h"
#include <list>
#include <vector>
#include "sqlite3.h"
class IGameDef;
struct ActionRow;
struct Entity;
class RollbackManager: public IRollbackManager
{
public:
RollbackManager(const std::string & world_path, IGameDef * gamedef);
~RollbackManager();
void reportAction(const RollbackAction & action_);
std::string getActor();
bool isActorGuess();
void setActor(const std::string & actor, bool is_guess);
std::string getSuspect(v3s16 p, float nearness_shortcut,
float min_nearness);
void flush();
void addAction(const RollbackAction & action);
std::list<RollbackAction> getEntriesSince(time_t first_time);
std::list<RollbackAction> getNodeActors(v3s16 pos, int range,
time_t seconds, int limit);
std::list<RollbackAction> getRevertActions(
const std::string & actor_filter, time_t seconds);
private:
void registerNewActor(const int id, const std::string & name);
void registerNewNode(const int id, const std::string & name);
int getActorId(const std::string & name);
int getNodeId(const std::string & name);
const char * getActorName(const int id);
const char * getNodeName(const int id);
bool createTables();
bool initDatabase();
bool registerRow(const ActionRow & row);
const std::list<ActionRow> actionRowsFromSelect(sqlite3_stmt * stmt);
ActionRow actionRowFromRollbackAction(const RollbackAction & action);
const std::list<RollbackAction> rollbackActionsFromActionRows(
const std::list<ActionRow> & rows);
const std::list<ActionRow> getRowsSince(time_t firstTime,
const std::string & actor);
const std::list<ActionRow> getRowsSince_range(time_t firstTime, v3s16 p,
int range, int limit);
const std::list<RollbackAction> getActionsSince_range(time_t firstTime, v3s16 p,
int range, int limit);
const std::list<RollbackAction> getActionsSince(time_t firstTime,
const std::string & actor = "");
void migrate(const std::string & filepath);
static float getSuspectNearness(bool is_guess, v3s16 suspect_p,
time_t suspect_t, v3s16 action_p, time_t action_t);
IGameDef *gamedef = nullptr;
std::string current_actor;
bool current_actor_is_guess = false;
std::list<RollbackAction> action_todisk_buffer;
std::list<RollbackAction> action_latest_buffer;
std::string database_path;
sqlite3 * db;
sqlite3_stmt * stmt_insert;
sqlite3_stmt * stmt_replace;
sqlite3_stmt * stmt_select;
sqlite3_stmt * stmt_select_range;
sqlite3_stmt * stmt_select_withActor;
sqlite3_stmt * stmt_knownActor_select;
sqlite3_stmt * stmt_knownActor_insert;
sqlite3_stmt * stmt_knownNode_select;
sqlite3_stmt * stmt_knownNode_insert;
std::vector<Entity> knownActors;
std::vector<Entity> knownNodes;
};
| pgimeno/minetest | src/rollback.h | C++ | mit | 3,519 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "rollback_interface.h"
#include <sstream>
#include "util/serialize.h"
#include "util/string.h"
#include "util/numeric.h"
#include "util/basic_macros.h"
#include "map.h"
#include "gamedef.h"
#include "nodedef.h"
#include "nodemetadata.h"
#include "exceptions.h"
#include "log.h"
#include "inventorymanager.h"
#include "inventory.h"
#include "mapblock.h"
RollbackNode::RollbackNode(Map *map, v3s16 p, IGameDef *gamedef)
{
const NodeDefManager *ndef = gamedef->ndef();
MapNode n = map->getNodeNoEx(p);
name = ndef->get(n).name;
param1 = n.param1;
param2 = n.param2;
NodeMetadata *metap = map->getNodeMetadata(p);
if (metap) {
std::ostringstream os(std::ios::binary);
metap->serialize(os, 1); // FIXME: version bump??
meta = os.str();
}
}
std::string RollbackAction::toString() const
{
std::ostringstream os(std::ios::binary);
switch (type) {
case TYPE_SET_NODE:
os << "set_node " << PP(p);
os << ": (" << serializeJsonString(n_old.name);
os << ", " << itos(n_old.param1);
os << ", " << itos(n_old.param2);
os << ", " << serializeJsonString(n_old.meta);
os << ") -> (" << serializeJsonString(n_new.name);
os << ", " << itos(n_new.param1);
os << ", " << itos(n_new.param2);
os << ", " << serializeJsonString(n_new.meta);
os << ')';
case TYPE_MODIFY_INVENTORY_STACK:
os << "modify_inventory_stack (";
os << serializeJsonString(inventory_location);
os << ", " << serializeJsonString(inventory_list);
os << ", " << inventory_index;
os << ", " << (inventory_add ? "add" : "remove");
os << ", " << serializeJsonString(inventory_stack.getItemString());
os << ')';
default:
return "<unknown action>";
}
return os.str();
}
bool RollbackAction::isImportant(IGameDef *gamedef) const
{
if (type != TYPE_SET_NODE)
return true;
// If names differ, action is always important
if(n_old.name != n_new.name)
return true;
// If metadata differs, action is always important
if(n_old.meta != n_new.meta)
return true;
const NodeDefManager *ndef = gamedef->ndef();
// Both are of the same name, so a single definition is needed
const ContentFeatures &def = ndef->get(n_old.name);
// If the type is flowing liquid, action is not important
if (def.liquid_type == LIQUID_FLOWING)
return false;
// Otherwise action is important
return true;
}
bool RollbackAction::getPosition(v3s16 *dst) const
{
switch (type) {
case TYPE_SET_NODE:
if (dst) *dst = p;
return true;
case TYPE_MODIFY_INVENTORY_STACK: {
InventoryLocation loc;
loc.deSerialize(inventory_location);
if (loc.type != InventoryLocation::NODEMETA) {
return false;
}
if (dst) *dst = loc.p;
return true; }
default:
return false;
}
}
bool RollbackAction::applyRevert(Map *map, InventoryManager *imgr, IGameDef *gamedef) const
{
try {
switch (type) {
case TYPE_NOTHING:
return true;
case TYPE_SET_NODE: {
const NodeDefManager *ndef = gamedef->ndef();
// Make sure position is loaded from disk
map->emergeBlock(getContainerPos(p, MAP_BLOCKSIZE), false);
// Check current node
MapNode current_node = map->getNodeNoEx(p);
std::string current_name = ndef->get(current_node).name;
// If current node not the new node, it's bad
if (current_name != n_new.name) {
return false;
}
// Create rollback node
content_t id = CONTENT_IGNORE;
if (!ndef->getId(n_old.name, id)) {
// The old node is not registered
return false;
}
MapNode n(id, n_old.param1, n_old.param2);
// Set rollback node
try {
if (!map->addNodeWithEvent(p, n)) {
infostream << "RollbackAction::applyRevert(): "
<< "AddNodeWithEvent failed at "
<< PP(p) << " for " << n_old.name
<< std::endl;
return false;
}
if (n_old.meta.empty()) {
map->removeNodeMetadata(p);
} else {
NodeMetadata *meta = map->getNodeMetadata(p);
if (!meta) {
meta = new NodeMetadata(gamedef->idef());
if (!map->setNodeMetadata(p, meta)) {
delete meta;
infostream << "RollbackAction::applyRevert(): "
<< "setNodeMetadata failed at "
<< PP(p) << " for " << n_old.name
<< std::endl;
return false;
}
}
std::istringstream is(n_old.meta, std::ios::binary);
meta->deSerialize(is, 1); // FIXME: version bump??
}
// Inform other things that the meta data has changed
MapEditEvent event;
event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
event.p = p;
map->dispatchEvent(&event);
} catch (InvalidPositionException &e) {
infostream << "RollbackAction::applyRevert(): "
<< "InvalidPositionException: " << e.what()
<< std::endl;
return false;
}
// Success
return true; }
case TYPE_MODIFY_INVENTORY_STACK: {
InventoryLocation loc;
loc.deSerialize(inventory_location);
Inventory *inv = imgr->getInventory(loc);
if (!inv) {
infostream << "RollbackAction::applyRevert(): Could not get "
"inventory at " << inventory_location << std::endl;
return false;
}
InventoryList *list = inv->getList(inventory_list);
if (!list) {
infostream << "RollbackAction::applyRevert(): Could not get "
"inventory list \"" << inventory_list << "\" in "
<< inventory_location << std::endl;
return false;
}
if (list->getSize() <= inventory_index) {
infostream << "RollbackAction::applyRevert(): List index "
<< inventory_index << " too large in "
<< "inventory list \"" << inventory_list << "\" in "
<< inventory_location << std::endl;
return false;
}
// If item was added, take away item, otherwise add removed item
if (inventory_add) {
// Silently ignore different current item
if (list->getItem(inventory_index).name !=
gamedef->idef()->getAlias(inventory_stack.name))
return false;
list->takeItem(inventory_index, inventory_stack.count);
} else {
list->addItem(inventory_index, inventory_stack);
}
// Inventory was modified; send to clients
imgr->setInventoryModified(loc);
return true; }
default:
errorstream << "RollbackAction::applyRevert(): type not handled"
<< std::endl;
return false;
}
} catch(SerializationError &e) {
errorstream << "RollbackAction::applyRevert(): n_old.name=" << n_old.name
<< ", SerializationError: " << e.what() << std::endl;
}
return false;
}
| pgimeno/minetest | src/rollback_interface.cpp | C++ | mit | 7,108 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "irr_v3d.h"
#include <string>
#include <iostream>
#include <list>
#include "exceptions.h"
#include "inventory.h"
class Map;
class IGameDef;
struct MapNode;
class InventoryManager;
struct RollbackNode
{
std::string name;
int param1 = 0;
int param2 = 0;
std::string meta;
bool operator == (const RollbackNode &other)
{
return (name == other.name && param1 == other.param1 &&
param2 == other.param2 && meta == other.meta);
}
bool operator != (const RollbackNode &other) { return !(*this == other); }
RollbackNode() = default;
RollbackNode(Map *map, v3s16 p, IGameDef *gamedef);
};
struct RollbackAction
{
enum Type{
TYPE_NOTHING,
TYPE_SET_NODE,
TYPE_MODIFY_INVENTORY_STACK,
} type = TYPE_NOTHING;
time_t unix_time = 0;
std::string actor;
bool actor_is_guess = false;
v3s16 p;
RollbackNode n_old;
RollbackNode n_new;
std::string inventory_location;
std::string inventory_list;
u32 inventory_index;
bool inventory_add;
ItemStack inventory_stack;
RollbackAction() = default;
void setSetNode(v3s16 p_, const RollbackNode &n_old_,
const RollbackNode &n_new_)
{
type = TYPE_SET_NODE;
p = p_;
n_old = n_old_;
n_new = n_new_;
}
void setModifyInventoryStack(const std::string &inventory_location_,
const std::string &inventory_list_, u32 index_,
bool add_, const ItemStack &inventory_stack_)
{
type = TYPE_MODIFY_INVENTORY_STACK;
inventory_location = inventory_location_;
inventory_list = inventory_list_;
inventory_index = index_;
inventory_add = add_;
inventory_stack = inventory_stack_;
}
// String should not contain newlines or nulls
std::string toString() const;
// Eg. flowing water level changes are not important
bool isImportant(IGameDef *gamedef) const;
bool getPosition(v3s16 *dst) const;
bool applyRevert(Map *map, InventoryManager *imgr, IGameDef *gamedef) const;
};
class IRollbackManager
{
public:
virtual void reportAction(const RollbackAction &action) = 0;
virtual std::string getActor() = 0;
virtual bool isActorGuess() = 0;
virtual void setActor(const std::string &actor, bool is_guess) = 0;
virtual std::string getSuspect(v3s16 p, float nearness_shortcut,
float min_nearness) = 0;
virtual ~IRollbackManager() = default;;
virtual void flush() = 0;
// Get all actors that did something to position p, but not further than
// <seconds> in history
virtual std::list<RollbackAction> getNodeActors(v3s16 pos, int range,
time_t seconds, int limit) = 0;
// Get actions to revert <seconds> of history made by <actor>
virtual std::list<RollbackAction> getRevertActions(const std::string &actor,
time_t seconds) = 0;
};
class RollbackScopeActor
{
public:
RollbackScopeActor(IRollbackManager * rollback_,
const std::string & actor, bool is_guess = false) :
rollback(rollback_)
{
if (rollback) {
old_actor = rollback->getActor();
old_actor_guess = rollback->isActorGuess();
rollback->setActor(actor, is_guess);
}
}
~RollbackScopeActor()
{
if (rollback) {
rollback->setActor(old_actor, old_actor_guess);
}
}
private:
IRollbackManager * rollback;
std::string old_actor;
bool old_actor_guess;
};
| pgimeno/minetest | src/rollback_interface.h | C++ | mit | 4,009 |
add_subdirectory(common)
add_subdirectory(cpp_api)
add_subdirectory(lua_api)
# Used by server and client
set(common_SCRIPT_SRCS
${CMAKE_CURRENT_SOURCE_DIR}/scripting_server.cpp
${common_SCRIPT_COMMON_SRCS}
${common_SCRIPT_CPP_API_SRCS}
${common_SCRIPT_LUA_API_SRCS}
PARENT_SCOPE)
# Used by client only
set(client_SCRIPT_SRCS
${CMAKE_CURRENT_SOURCE_DIR}/scripting_mainmenu.cpp
${CMAKE_CURRENT_SOURCE_DIR}/scripting_client.cpp
${client_SCRIPT_COMMON_SRCS}
${client_SCRIPT_CPP_API_SRCS}
${client_SCRIPT_LUA_API_SRCS}
PARENT_SCOPE)
| pgimeno/minetest | src/script/CMakeLists.txt | Text | mit | 542 |
set(common_SCRIPT_COMMON_SRCS
${CMAKE_CURRENT_SOURCE_DIR}/c_content.cpp
${CMAKE_CURRENT_SOURCE_DIR}/c_converter.cpp
${CMAKE_CURRENT_SOURCE_DIR}/c_types.cpp
${CMAKE_CURRENT_SOURCE_DIR}/c_internal.cpp
${CMAKE_CURRENT_SOURCE_DIR}/helper.cpp
PARENT_SCOPE)
set(client_SCRIPT_COMMON_SRCS
PARENT_SCOPE)
| pgimeno/minetest | src/script/common/CMakeLists.txt | Text | mit | 305 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "common/c_content.h"
#include "common/c_converter.h"
#include "common/c_types.h"
#include "nodedef.h"
#include "object_properties.h"
#include "cpp_api/s_node.h"
#include "lua_api/l_object.h"
#include "lua_api/l_item.h"
#include "common/c_internal.h"
#include "server.h"
#include "log.h"
#include "tool.h"
#include "serverobject.h"
#include "porting.h"
#include "mapgen/mg_schematic.h"
#include "noise.h"
#include "util/pointedthing.h"
#include "debug.h" // For FATAL_ERROR
#include <json/json.h>
struct EnumString es_TileAnimationType[] =
{
{TAT_NONE, "none"},
{TAT_VERTICAL_FRAMES, "vertical_frames"},
{TAT_SHEET_2D, "sheet_2d"},
{0, NULL},
};
/******************************************************************************/
void read_item_definition(lua_State* L, int index,
const ItemDefinition &default_def, ItemDefinition &def)
{
if (index < 0)
index = lua_gettop(L) + 1 + index;
def.type = (ItemType)getenumfield(L, index, "type",
es_ItemType, ITEM_NONE);
getstringfield(L, index, "name", def.name);
getstringfield(L, index, "description", def.description);
getstringfield(L, index, "inventory_image", def.inventory_image);
getstringfield(L, index, "inventory_overlay", def.inventory_overlay);
getstringfield(L, index, "wield_image", def.wield_image);
getstringfield(L, index, "wield_overlay", def.wield_overlay);
getstringfield(L, index, "palette", def.palette_image);
// Read item color.
lua_getfield(L, index, "color");
read_color(L, -1, &def.color);
lua_pop(L, 1);
lua_getfield(L, index, "wield_scale");
if(lua_istable(L, -1)){
def.wield_scale = check_v3f(L, -1);
}
lua_pop(L, 1);
int stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
def.stack_max = rangelim(stack_max, 1, U16_MAX);
lua_getfield(L, index, "on_use");
def.usable = lua_isfunction(L, -1);
lua_pop(L, 1);
getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
warn_if_field_exists(L, index, "tool_digging_properties",
"Deprecated; use tool_capabilities");
lua_getfield(L, index, "tool_capabilities");
if(lua_istable(L, -1)){
def.tool_capabilities = new ToolCapabilities(
read_tool_capabilities(L, -1));
}
// If name is "" (hand), ensure there are ToolCapabilities
// because it will be looked up there whenever any other item has
// no ToolCapabilities
if (def.name.empty() && def.tool_capabilities == NULL){
def.tool_capabilities = new ToolCapabilities();
}
lua_getfield(L, index, "groups");
read_groups(L, -1, def.groups);
lua_pop(L, 1);
lua_getfield(L, index, "sounds");
if(lua_istable(L, -1)){
lua_getfield(L, -1, "place");
read_soundspec(L, -1, def.sound_place);
lua_pop(L, 1);
lua_getfield(L, -1, "place_failed");
read_soundspec(L, -1, def.sound_place_failed);
lua_pop(L, 1);
}
lua_pop(L, 1);
def.range = getfloatfield_default(L, index, "range", def.range);
// Client shall immediately place this node when player places the item.
// Server will update the precise end result a moment later.
// "" = no prediction
getstringfield(L, index, "node_placement_prediction",
def.node_placement_prediction);
}
/******************************************************************************/
void push_item_definition(lua_State *L, const ItemDefinition &i)
{
lua_newtable(L);
lua_pushstring(L, i.name.c_str());
lua_setfield(L, -2, "name");
lua_pushstring(L, i.description.c_str());
lua_setfield(L, -2, "description");
}
void push_item_definition_full(lua_State *L, const ItemDefinition &i)
{
std::string type(es_ItemType[(int)i.type].str);
lua_newtable(L);
lua_pushstring(L, i.name.c_str());
lua_setfield(L, -2, "name");
lua_pushstring(L, i.description.c_str());
lua_setfield(L, -2, "description");
lua_pushstring(L, type.c_str());
lua_setfield(L, -2, "type");
lua_pushstring(L, i.inventory_image.c_str());
lua_setfield(L, -2, "inventory_image");
lua_pushstring(L, i.inventory_overlay.c_str());
lua_setfield(L, -2, "inventory_overlay");
lua_pushstring(L, i.wield_image.c_str());
lua_setfield(L, -2, "wield_image");
lua_pushstring(L, i.wield_overlay.c_str());
lua_setfield(L, -2, "wield_overlay");
lua_pushstring(L, i.palette_image.c_str());
lua_setfield(L, -2, "palette_image");
push_ARGB8(L, i.color);
lua_setfield(L, -2, "color");
push_v3f(L, i.wield_scale);
lua_setfield(L, -2, "wield_scale");
lua_pushinteger(L, i.stack_max);
lua_setfield(L, -2, "stack_max");
lua_pushboolean(L, i.usable);
lua_setfield(L, -2, "usable");
lua_pushboolean(L, i.liquids_pointable);
lua_setfield(L, -2, "liquids_pointable");
if (i.type == ITEM_TOOL) {
push_tool_capabilities(L, ToolCapabilities(
i.tool_capabilities->full_punch_interval,
i.tool_capabilities->max_drop_level,
i.tool_capabilities->groupcaps,
i.tool_capabilities->damageGroups));
lua_setfield(L, -2, "tool_capabilities");
}
push_groups(L, i.groups);
lua_setfield(L, -2, "groups");
push_soundspec(L, i.sound_place);
lua_setfield(L, -2, "sound_place");
push_soundspec(L, i.sound_place_failed);
lua_setfield(L, -2, "sound_place_failed");
lua_pushstring(L, i.node_placement_prediction.c_str());
lua_setfield(L, -2, "node_placement_prediction");
}
/******************************************************************************/
void read_object_properties(lua_State *L, int index,
ObjectProperties *prop, IItemDefManager *idef)
{
if(index < 0)
index = lua_gettop(L) + 1 + index;
if(!lua_istable(L, index))
return;
int hp_max = 0;
if (getintfield(L, -1, "hp_max", hp_max))
prop->hp_max = (u16)rangelim(hp_max, 0, U16_MAX);
getintfield(L, -1, "breath_max", prop->breath_max);
getboolfield(L, -1, "physical", prop->physical);
getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects);
getfloatfield(L, -1, "weight", prop->weight);
lua_getfield(L, -1, "collisionbox");
bool collisionbox_defined = lua_istable(L, -1);
if (collisionbox_defined)
prop->collisionbox = read_aabb3f(L, -1, 1.0);
lua_pop(L, 1);
lua_getfield(L, -1, "selectionbox");
if (lua_istable(L, -1))
prop->selectionbox = read_aabb3f(L, -1, 1.0);
else if (collisionbox_defined)
prop->selectionbox = prop->collisionbox;
lua_pop(L, 1);
getboolfield(L, -1, "pointable", prop->pointable);
getstringfield(L, -1, "visual", prop->visual);
getstringfield(L, -1, "mesh", prop->mesh);
lua_getfield(L, -1, "visual_size");
if (lua_istable(L, -1)) {
// Backwards compatibility: Also accept { x = ?, y = ? }
v2f scale_xy = read_v2f(L, -1);
f32 scale_z = scale_xy.X;
lua_getfield(L, -1, "z");
if (lua_isnumber(L, -1))
scale_z = lua_tonumber(L, -1);
lua_pop(L, 1);
prop->visual_size = v3f(scale_xy.X, scale_xy.Y, scale_z);
}
lua_pop(L, 1);
lua_getfield(L, -1, "textures");
if(lua_istable(L, -1)){
prop->textures.clear();
int table = lua_gettop(L);
lua_pushnil(L);
while(lua_next(L, table) != 0){
// key at index -2 and value at index -1
if(lua_isstring(L, -1))
prop->textures.emplace_back(lua_tostring(L, -1));
else
prop->textures.emplace_back("");
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
}
lua_pop(L, 1);
lua_getfield(L, -1, "colors");
if (lua_istable(L, -1)) {
int table = lua_gettop(L);
prop->colors.clear();
for (lua_pushnil(L); lua_next(L, table); lua_pop(L, 1)) {
video::SColor color(255, 255, 255, 255);
read_color(L, -1, &color);
prop->colors.push_back(color);
}
}
lua_pop(L, 1);
lua_getfield(L, -1, "spritediv");
if(lua_istable(L, -1))
prop->spritediv = read_v2s16(L, -1);
lua_pop(L, 1);
lua_getfield(L, -1, "initial_sprite_basepos");
if(lua_istable(L, -1))
prop->initial_sprite_basepos = read_v2s16(L, -1);
lua_pop(L, 1);
getboolfield(L, -1, "is_visible", prop->is_visible);
getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
if (getfloatfield(L, -1, "stepheight", prop->stepheight))
prop->stepheight *= BS;
getfloatfield(L, -1, "eye_height", prop->eye_height);
getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
lua_getfield(L, -1, "automatic_face_movement_dir");
if (lua_isnumber(L, -1)) {
prop->automatic_face_movement_dir = true;
prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1);
} else if (lua_isboolean(L, -1)) {
prop->automatic_face_movement_dir = lua_toboolean(L, -1);
prop->automatic_face_movement_dir_offset = 0.0;
}
lua_pop(L, 1);
getboolfield(L, -1, "backface_culling", prop->backface_culling);
getintfield(L, -1, "glow", prop->glow);
getstringfield(L, -1, "nametag", prop->nametag);
lua_getfield(L, -1, "nametag_color");
if (!lua_isnil(L, -1)) {
video::SColor color = prop->nametag_color;
if (read_color(L, -1, &color))
prop->nametag_color = color;
}
lua_pop(L, 1);
lua_getfield(L, -1, "automatic_face_movement_max_rotation_per_sec");
if (lua_isnumber(L, -1)) {
prop->automatic_face_movement_max_rotation_per_sec = luaL_checknumber(L, -1);
}
lua_pop(L, 1);
getstringfield(L, -1, "infotext", prop->infotext);
getboolfield(L, -1, "static_save", prop->static_save);
lua_getfield(L, -1, "wield_item");
if (!lua_isnil(L, -1))
prop->wield_item = read_item(L, -1, idef).getItemString();
lua_pop(L, 1);
getfloatfield(L, -1, "zoom_fov", prop->zoom_fov);
getboolfield(L, -1, "use_texture_alpha", prop->use_texture_alpha);
}
/******************************************************************************/
void push_object_properties(lua_State *L, ObjectProperties *prop)
{
lua_newtable(L);
lua_pushnumber(L, prop->hp_max);
lua_setfield(L, -2, "hp_max");
lua_pushnumber(L, prop->breath_max);
lua_setfield(L, -2, "breath_max");
lua_pushboolean(L, prop->physical);
lua_setfield(L, -2, "physical");
lua_pushboolean(L, prop->collideWithObjects);
lua_setfield(L, -2, "collide_with_objects");
lua_pushnumber(L, prop->weight);
lua_setfield(L, -2, "weight");
push_aabb3f(L, prop->collisionbox);
lua_setfield(L, -2, "collisionbox");
push_aabb3f(L, prop->selectionbox);
lua_setfield(L, -2, "selectionbox");
lua_pushboolean(L, prop->pointable);
lua_setfield(L, -2, "pointable");
lua_pushlstring(L, prop->visual.c_str(), prop->visual.size());
lua_setfield(L, -2, "visual");
lua_pushlstring(L, prop->mesh.c_str(), prop->mesh.size());
lua_setfield(L, -2, "mesh");
push_v3f(L, prop->visual_size);
lua_setfield(L, -2, "visual_size");
lua_newtable(L);
u16 i = 1;
for (const std::string &texture : prop->textures) {
lua_pushlstring(L, texture.c_str(), texture.size());
lua_rawseti(L, -2, i++);
}
lua_setfield(L, -2, "textures");
lua_newtable(L);
i = 1;
for (const video::SColor &color : prop->colors) {
push_ARGB8(L, color);
lua_rawseti(L, -2, i++);
}
lua_setfield(L, -2, "colors");
push_v2s16(L, prop->spritediv);
lua_setfield(L, -2, "spritediv");
push_v2s16(L, prop->initial_sprite_basepos);
lua_setfield(L, -2, "initial_sprite_basepos");
lua_pushboolean(L, prop->is_visible);
lua_setfield(L, -2, "is_visible");
lua_pushboolean(L, prop->makes_footstep_sound);
lua_setfield(L, -2, "makes_footstep_sound");
lua_pushnumber(L, prop->stepheight / BS);
lua_setfield(L, -2, "stepheight");
lua_pushnumber(L, prop->eye_height);
lua_setfield(L, -2, "eye_height");
lua_pushnumber(L, prop->automatic_rotate);
lua_setfield(L, -2, "automatic_rotate");
if (prop->automatic_face_movement_dir)
lua_pushnumber(L, prop->automatic_face_movement_dir_offset);
else
lua_pushboolean(L, false);
lua_setfield(L, -2, "automatic_face_movement_dir");
lua_pushboolean(L, prop->backface_culling);
lua_setfield(L, -2, "backface_culling");
lua_pushnumber(L, prop->glow);
lua_setfield(L, -2, "glow");
lua_pushlstring(L, prop->nametag.c_str(), prop->nametag.size());
lua_setfield(L, -2, "nametag");
push_ARGB8(L, prop->nametag_color);
lua_setfield(L, -2, "nametag_color");
lua_pushnumber(L, prop->automatic_face_movement_max_rotation_per_sec);
lua_setfield(L, -2, "automatic_face_movement_max_rotation_per_sec");
lua_pushlstring(L, prop->infotext.c_str(), prop->infotext.size());
lua_setfield(L, -2, "infotext");
lua_pushboolean(L, prop->static_save);
lua_setfield(L, -2, "static_save");
lua_pushlstring(L, prop->wield_item.c_str(), prop->wield_item.size());
lua_setfield(L, -2, "wield_item");
lua_pushnumber(L, prop->zoom_fov);
lua_setfield(L, -2, "zoom_fov");
lua_pushboolean(L, prop->use_texture_alpha);
lua_setfield(L, -2, "use_texture_alpha");
}
/******************************************************************************/
TileDef read_tiledef(lua_State *L, int index, u8 drawtype)
{
if(index < 0)
index = lua_gettop(L) + 1 + index;
TileDef tiledef;
bool default_tiling = true;
bool default_culling = true;
switch (drawtype) {
case NDT_PLANTLIKE:
case NDT_PLANTLIKE_ROOTED:
case NDT_FIRELIKE:
default_tiling = false;
// "break" is omitted here intentionaly, as PLANTLIKE
// FIRELIKE drawtype both should default to having
// backface_culling to false.
case NDT_MESH:
case NDT_LIQUID:
default_culling = false;
break;
default:
break;
}
// key at index -2 and value at index
if(lua_isstring(L, index)){
// "default_lava.png"
tiledef.name = lua_tostring(L, index);
tiledef.tileable_vertical = default_tiling;
tiledef.tileable_horizontal = default_tiling;
tiledef.backface_culling = default_culling;
}
else if(lua_istable(L, index))
{
// name="default_lava.png"
tiledef.name = "";
getstringfield(L, index, "name", tiledef.name);
getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
tiledef.backface_culling = getboolfield_default(
L, index, "backface_culling", default_culling);
tiledef.tileable_horizontal = getboolfield_default(
L, index, "tileable_horizontal", default_tiling);
tiledef.tileable_vertical = getboolfield_default(
L, index, "tileable_vertical", default_tiling);
std::string align_style;
if (getstringfield(L, index, "align_style", align_style)) {
if (align_style == "user")
tiledef.align_style = ALIGN_STYLE_USER_DEFINED;
else if (align_style == "world")
tiledef.align_style = ALIGN_STYLE_WORLD;
else
tiledef.align_style = ALIGN_STYLE_NODE;
}
tiledef.scale = getintfield_default(L, index, "scale", 0);
// color = ...
lua_getfield(L, index, "color");
tiledef.has_color = read_color(L, -1, &tiledef.color);
lua_pop(L, 1);
// animation = {}
lua_getfield(L, index, "animation");
tiledef.animation = read_animation_definition(L, -1);
lua_pop(L, 1);
}
return tiledef;
}
/******************************************************************************/
ContentFeatures read_content_features(lua_State *L, int index)
{
if(index < 0)
index = lua_gettop(L) + 1 + index;
ContentFeatures f;
/* Cache existence of some callbacks */
lua_getfield(L, index, "on_construct");
if(!lua_isnil(L, -1)) f.has_on_construct = true;
lua_pop(L, 1);
lua_getfield(L, index, "on_destruct");
if(!lua_isnil(L, -1)) f.has_on_destruct = true;
lua_pop(L, 1);
lua_getfield(L, index, "after_destruct");
if(!lua_isnil(L, -1)) f.has_after_destruct = true;
lua_pop(L, 1);
lua_getfield(L, index, "on_rightclick");
f.rightclickable = lua_isfunction(L, -1);
lua_pop(L, 1);
/* Name */
getstringfield(L, index, "name", f.name);
/* Groups */
lua_getfield(L, index, "groups");
read_groups(L, -1, f.groups);
lua_pop(L, 1);
/* Visual definition */
f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype",
ScriptApiNode::es_DrawType,NDT_NORMAL);
getfloatfield(L, index, "visual_scale", f.visual_scale);
/* Meshnode model filename */
getstringfield(L, index, "mesh", f.mesh);
// tiles = {}
lua_getfield(L, index, "tiles");
// If nil, try the deprecated name "tile_images" instead
if(lua_isnil(L, -1)){
lua_pop(L, 1);
warn_if_field_exists(L, index, "tile_images",
"Deprecated; new name is \"tiles\".");
lua_getfield(L, index, "tile_images");
}
if(lua_istable(L, -1)){
int table = lua_gettop(L);
lua_pushnil(L);
int i = 0;
while(lua_next(L, table) != 0){
// Read tiledef from value
f.tiledef[i] = read_tiledef(L, -1, f.drawtype);
// removes value, keeps key for next iteration
lua_pop(L, 1);
i++;
if(i==6){
lua_pop(L, 1);
break;
}
}
// Copy last value to all remaining textures
if(i >= 1){
TileDef lasttile = f.tiledef[i-1];
while(i < 6){
f.tiledef[i] = lasttile;
i++;
}
}
}
lua_pop(L, 1);
// overlay_tiles = {}
lua_getfield(L, index, "overlay_tiles");
if (lua_istable(L, -1)) {
int table = lua_gettop(L);
lua_pushnil(L);
int i = 0;
while (lua_next(L, table) != 0) {
// Read tiledef from value
f.tiledef_overlay[i] = read_tiledef(L, -1, f.drawtype);
// removes value, keeps key for next iteration
lua_pop(L, 1);
i++;
if (i == 6) {
lua_pop(L, 1);
break;
}
}
// Copy last value to all remaining textures
if (i >= 1) {
TileDef lasttile = f.tiledef_overlay[i - 1];
while (i < 6) {
f.tiledef_overlay[i] = lasttile;
i++;
}
}
}
lua_pop(L, 1);
// special_tiles = {}
lua_getfield(L, index, "special_tiles");
// If nil, try the deprecated name "special_materials" instead
if(lua_isnil(L, -1)){
lua_pop(L, 1);
warn_if_field_exists(L, index, "special_materials",
"Deprecated; new name is \"special_tiles\".");
lua_getfield(L, index, "special_materials");
}
if(lua_istable(L, -1)){
int table = lua_gettop(L);
lua_pushnil(L);
int i = 0;
while(lua_next(L, table) != 0){
// Read tiledef from value
f.tiledef_special[i] = read_tiledef(L, -1, f.drawtype);
// removes value, keeps key for next iteration
lua_pop(L, 1);
i++;
if(i==CF_SPECIAL_COUNT){
lua_pop(L, 1);
break;
}
}
}
lua_pop(L, 1);
f.alpha = getintfield_default(L, index, "alpha", 255);
bool usealpha = getboolfield_default(L, index,
"use_texture_alpha", false);
if (usealpha)
f.alpha = 0;
// Read node color.
lua_getfield(L, index, "color");
read_color(L, -1, &f.color);
lua_pop(L, 1);
getstringfield(L, index, "palette", f.palette_name);
/* Other stuff */
lua_getfield(L, index, "post_effect_color");
read_color(L, -1, &f.post_effect_color);
lua_pop(L, 1);
f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
ScriptApiNode::es_ContentParamType, CPT_NONE);
f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
ScriptApiNode::es_ContentParamType2, CPT2_NONE);
if (!f.palette_name.empty() &&
!(f.param_type_2 == CPT2_COLOR ||
f.param_type_2 == CPT2_COLORED_FACEDIR ||
f.param_type_2 == CPT2_COLORED_WALLMOUNTED))
warningstream << "Node " << f.name.c_str()
<< " has a palette, but not a suitable paramtype2." << std::endl;
// Warn about some deprecated fields
warn_if_field_exists(L, index, "wall_mounted",
"Deprecated; use paramtype2 = 'wallmounted'");
warn_if_field_exists(L, index, "light_propagates",
"Deprecated; determined from paramtype");
warn_if_field_exists(L, index, "dug_item",
"Deprecated; use 'drop' field");
warn_if_field_exists(L, index, "extra_dug_item",
"Deprecated; use 'drop' field");
warn_if_field_exists(L, index, "extra_dug_item_rarity",
"Deprecated; use 'drop' field");
warn_if_field_exists(L, index, "metadata_name",
"Deprecated; use on_add and metadata callbacks");
// True for all ground-like things like stone and mud, false for eg. trees
getboolfield(L, index, "is_ground_content", f.is_ground_content);
f.light_propagates = (f.param_type == CPT_LIGHT);
getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
// This is used for collision detection.
// Also for general solidness queries.
getboolfield(L, index, "walkable", f.walkable);
// Player can point to these
getboolfield(L, index, "pointable", f.pointable);
// Player can dig these
getboolfield(L, index, "diggable", f.diggable);
// Player can climb these
getboolfield(L, index, "climbable", f.climbable);
// Player can build on these
getboolfield(L, index, "buildable_to", f.buildable_to);
// Liquids flow into and replace node
getboolfield(L, index, "floodable", f.floodable);
// Whether the node is non-liquid, source liquid or flowing liquid
f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
ScriptApiNode::es_LiquidType, LIQUID_NONE);
// If the content is liquid, this is the flowing version of the liquid.
getstringfield(L, index, "liquid_alternative_flowing",
f.liquid_alternative_flowing);
// If the content is liquid, this is the source version of the liquid.
getstringfield(L, index, "liquid_alternative_source",
f.liquid_alternative_source);
// Viscosity for fluid flow, ranging from 1 to 7, with
// 1 giving almost instantaneous propagation and 7 being
// the slowest possible
f.liquid_viscosity = getintfield_default(L, index,
"liquid_viscosity", f.liquid_viscosity);
f.liquid_range = getintfield_default(L, index,
"liquid_range", f.liquid_range);
f.leveled = getintfield_default(L, index, "leveled", f.leveled);
getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
f.drowning = getintfield_default(L, index,
"drowning", f.drowning);
// Amount of light the node emits
f.light_source = getintfield_default(L, index,
"light_source", f.light_source);
if (f.light_source > LIGHT_MAX) {
warningstream << "Node " << f.name.c_str()
<< " had greater light_source than " << LIGHT_MAX
<< ", it was reduced." << std::endl;
f.light_source = LIGHT_MAX;
}
f.damage_per_second = getintfield_default(L, index,
"damage_per_second", f.damage_per_second);
lua_getfield(L, index, "node_box");
if(lua_istable(L, -1))
f.node_box = read_nodebox(L, -1);
lua_pop(L, 1);
lua_getfield(L, index, "connects_to");
if (lua_istable(L, -1)) {
int table = lua_gettop(L);
lua_pushnil(L);
while (lua_next(L, table) != 0) {
// Value at -1
f.connects_to.emplace_back(lua_tostring(L, -1));
lua_pop(L, 1);
}
}
lua_pop(L, 1);
lua_getfield(L, index, "connect_sides");
if (lua_istable(L, -1)) {
int table = lua_gettop(L);
lua_pushnil(L);
while (lua_next(L, table) != 0) {
// Value at -1
std::string side(lua_tostring(L, -1));
// Note faces are flipped to make checking easier
if (side == "top")
f.connect_sides |= 2;
else if (side == "bottom")
f.connect_sides |= 1;
else if (side == "front")
f.connect_sides |= 16;
else if (side == "left")
f.connect_sides |= 32;
else if (side == "back")
f.connect_sides |= 4;
else if (side == "right")
f.connect_sides |= 8;
else
warningstream << "Unknown value for \"connect_sides\": "
<< side << std::endl;
lua_pop(L, 1);
}
}
lua_pop(L, 1);
lua_getfield(L, index, "selection_box");
if(lua_istable(L, -1))
f.selection_box = read_nodebox(L, -1);
lua_pop(L, 1);
lua_getfield(L, index, "collision_box");
if(lua_istable(L, -1))
f.collision_box = read_nodebox(L, -1);
lua_pop(L, 1);
f.waving = getintfield_default(L, index,
"waving", f.waving);
// Set to true if paramtype used to be 'facedir_simple'
getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
// Set to true if wall_mounted used to be set to true
getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
// Sound table
lua_getfield(L, index, "sounds");
if(lua_istable(L, -1)){
lua_getfield(L, -1, "footstep");
read_soundspec(L, -1, f.sound_footstep);
lua_pop(L, 1);
lua_getfield(L, -1, "dig");
read_soundspec(L, -1, f.sound_dig);
lua_pop(L, 1);
lua_getfield(L, -1, "dug");
read_soundspec(L, -1, f.sound_dug);
lua_pop(L, 1);
}
lua_pop(L, 1);
// Node immediately placed by client when node is dug
getstringfield(L, index, "node_dig_prediction",
f.node_dig_prediction);
return f;
}
void push_content_features(lua_State *L, const ContentFeatures &c)
{
std::string paramtype(ScriptApiNode::es_ContentParamType[(int)c.param_type].str);
std::string paramtype2(ScriptApiNode::es_ContentParamType2[(int)c.param_type_2].str);
std::string drawtype(ScriptApiNode::es_DrawType[(int)c.drawtype].str);
std::string liquid_type(ScriptApiNode::es_LiquidType[(int)c.liquid_type].str);
/* Missing "tiles" because I don't see a usecase (at least not yet). */
lua_newtable(L);
lua_pushboolean(L, c.has_on_construct);
lua_setfield(L, -2, "has_on_construct");
lua_pushboolean(L, c.has_on_destruct);
lua_setfield(L, -2, "has_on_destruct");
lua_pushboolean(L, c.has_after_destruct);
lua_setfield(L, -2, "has_after_destruct");
lua_pushstring(L, c.name.c_str());
lua_setfield(L, -2, "name");
push_groups(L, c.groups);
lua_setfield(L, -2, "groups");
lua_pushstring(L, paramtype.c_str());
lua_setfield(L, -2, "paramtype");
lua_pushstring(L, paramtype2.c_str());
lua_setfield(L, -2, "paramtype2");
lua_pushstring(L, drawtype.c_str());
lua_setfield(L, -2, "drawtype");
if (!c.mesh.empty()) {
lua_pushstring(L, c.mesh.c_str());
lua_setfield(L, -2, "mesh");
}
#ifndef SERVER
push_ARGB8(L, c.minimap_color); // I know this is not set-able w/ register_node,
lua_setfield(L, -2, "minimap_color"); // but the people need to know!
#endif
lua_pushnumber(L, c.visual_scale);
lua_setfield(L, -2, "visual_scale");
lua_pushnumber(L, c.alpha);
lua_setfield(L, -2, "alpha");
if (!c.palette_name.empty()) {
push_ARGB8(L, c.color);
lua_setfield(L, -2, "color");
lua_pushstring(L, c.palette_name.c_str());
lua_setfield(L, -2, "palette_name");
push_palette(L, c.palette);
lua_setfield(L, -2, "palette");
}
lua_pushnumber(L, c.waving);
lua_setfield(L, -2, "waving");
lua_pushnumber(L, c.connect_sides);
lua_setfield(L, -2, "connect_sides");
lua_newtable(L);
u16 i = 1;
for (const std::string &it : c.connects_to) {
lua_pushlstring(L, it.c_str(), it.size());
lua_rawseti(L, -2, i++);
}
lua_setfield(L, -2, "connects_to");
push_ARGB8(L, c.post_effect_color);
lua_setfield(L, -2, "post_effect_color");
lua_pushnumber(L, c.leveled);
lua_setfield(L, -2, "leveled");
lua_pushboolean(L, c.sunlight_propagates);
lua_setfield(L, -2, "sunlight_propagates");
lua_pushnumber(L, c.light_source);
lua_setfield(L, -2, "light_source");
lua_pushboolean(L, c.is_ground_content);
lua_setfield(L, -2, "is_ground_content");
lua_pushboolean(L, c.walkable);
lua_setfield(L, -2, "walkable");
lua_pushboolean(L, c.pointable);
lua_setfield(L, -2, "pointable");
lua_pushboolean(L, c.diggable);
lua_setfield(L, -2, "diggable");
lua_pushboolean(L, c.climbable);
lua_setfield(L, -2, "climbable");
lua_pushboolean(L, c.buildable_to);
lua_setfield(L, -2, "buildable_to");
lua_pushboolean(L, c.rightclickable);
lua_setfield(L, -2, "rightclickable");
lua_pushnumber(L, c.damage_per_second);
lua_setfield(L, -2, "damage_per_second");
if (c.isLiquid()) {
lua_pushstring(L, liquid_type.c_str());
lua_setfield(L, -2, "liquid_type");
lua_pushstring(L, c.liquid_alternative_flowing.c_str());
lua_setfield(L, -2, "liquid_alternative_flowing");
lua_pushstring(L, c.liquid_alternative_source.c_str());
lua_setfield(L, -2, "liquid_alternative_source");
lua_pushnumber(L, c.liquid_viscosity);
lua_setfield(L, -2, "liquid_viscosity");
lua_pushboolean(L, c.liquid_renewable);
lua_setfield(L, -2, "liquid_renewable");
lua_pushnumber(L, c.liquid_range);
lua_setfield(L, -2, "liquid_range");
}
lua_pushnumber(L, c.drowning);
lua_setfield(L, -2, "drowning");
lua_pushboolean(L, c.floodable);
lua_setfield(L, -2, "floodable");
push_nodebox(L, c.node_box);
lua_setfield(L, -2, "node_box");
push_nodebox(L, c.selection_box);
lua_setfield(L, -2, "selection_box");
push_nodebox(L, c.collision_box);
lua_setfield(L, -2, "collision_box");
lua_newtable(L);
push_soundspec(L, c.sound_footstep);
lua_setfield(L, -2, "sound_footstep");
push_soundspec(L, c.sound_dig);
lua_setfield(L, -2, "sound_dig");
push_soundspec(L, c.sound_dug);
lua_setfield(L, -2, "sound_dug");
lua_setfield(L, -2, "sounds");
lua_pushboolean(L, c.legacy_facedir_simple);
lua_setfield(L, -2, "legacy_facedir_simple");
lua_pushboolean(L, c.legacy_wallmounted);
lua_setfield(L, -2, "legacy_wallmounted");
lua_pushstring(L, c.node_dig_prediction.c_str());
lua_setfield(L, -2, "node_dig_prediction");
}
/******************************************************************************/
void push_nodebox(lua_State *L, const NodeBox &box)
{
lua_newtable(L);
switch (box.type)
{
case NODEBOX_REGULAR:
lua_pushstring(L, "regular");
lua_setfield(L, -2, "type");
break;
case NODEBOX_LEVELED:
case NODEBOX_FIXED:
lua_pushstring(L, "fixed");
lua_setfield(L, -2, "type");
push_box(L, box.fixed);
lua_setfield(L, -2, "fixed");
break;
case NODEBOX_WALLMOUNTED:
lua_pushstring(L, "wallmounted");
lua_setfield(L, -2, "type");
push_aabb3f(L, box.wall_top);
lua_setfield(L, -2, "wall_top");
push_aabb3f(L, box.wall_bottom);
lua_setfield(L, -2, "wall_bottom");
push_aabb3f(L, box.wall_side);
lua_setfield(L, -2, "wall_side");
break;
case NODEBOX_CONNECTED:
lua_pushstring(L, "connected");
lua_setfield(L, -2, "type");
push_box(L, box.connect_top);
lua_setfield(L, -2, "connect_top");
push_box(L, box.connect_bottom);
lua_setfield(L, -2, "connect_bottom");
push_box(L, box.connect_front);
lua_setfield(L, -2, "connect_front");
push_box(L, box.connect_back);
lua_setfield(L, -2, "connect_back");
push_box(L, box.connect_left);
lua_setfield(L, -2, "connect_left");
push_box(L, box.connect_right);
lua_setfield(L, -2, "connect_right");
break;
default:
FATAL_ERROR("Invalid box.type");
break;
}
}
void push_box(lua_State *L, const std::vector<aabb3f> &box)
{
lua_newtable(L);
u8 i = 1;
for (const aabb3f &it : box) {
push_aabb3f(L, it);
lua_rawseti(L, -2, i++);
}
}
/******************************************************************************/
void push_palette(lua_State *L, const std::vector<video::SColor> *palette)
{
lua_createtable(L, palette->size(), 0);
int newTable = lua_gettop(L);
int index = 1;
std::vector<video::SColor>::const_iterator iter;
for (iter = palette->begin(); iter != palette->end(); ++iter) {
push_ARGB8(L, (*iter));
lua_rawseti(L, newTable, index);
index++;
}
}
/******************************************************************************/
void read_server_sound_params(lua_State *L, int index,
ServerSoundParams ¶ms)
{
if(index < 0)
index = lua_gettop(L) + 1 + index;
// Clear
params = ServerSoundParams();
if(lua_istable(L, index)){
getfloatfield(L, index, "gain", params.gain);
getstringfield(L, index, "to_player", params.to_player);
getfloatfield(L, index, "fade", params.fade);
getfloatfield(L, index, "pitch", params.pitch);
lua_getfield(L, index, "pos");
if(!lua_isnil(L, -1)){
v3f p = read_v3f(L, -1)*BS;
params.pos = p;
params.type = ServerSoundParams::SSP_POSITIONAL;
}
lua_pop(L, 1);
lua_getfield(L, index, "object");
if(!lua_isnil(L, -1)){
ObjectRef *ref = ObjectRef::checkobject(L, -1);
ServerActiveObject *sao = ObjectRef::getobject(ref);
if(sao){
params.object = sao->getId();
params.type = ServerSoundParams::SSP_OBJECT;
}
}
lua_pop(L, 1);
params.max_hear_distance = BS*getfloatfield_default(L, index,
"max_hear_distance", params.max_hear_distance/BS);
getboolfield(L, index, "loop", params.loop);
}
}
/******************************************************************************/
void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
{
if(index < 0)
index = lua_gettop(L) + 1 + index;
if(lua_isnil(L, index)){
} else if(lua_istable(L, index)){
getstringfield(L, index, "name", spec.name);
getfloatfield(L, index, "gain", spec.gain);
getfloatfield(L, index, "fade", spec.fade);
getfloatfield(L, index, "pitch", spec.pitch);
} else if(lua_isstring(L, index)){
spec.name = lua_tostring(L, index);
}
}
void push_soundspec(lua_State *L, const SimpleSoundSpec &spec)
{
lua_newtable(L);
lua_pushstring(L, spec.name.c_str());
lua_setfield(L, -2, "name");
lua_pushnumber(L, spec.gain);
lua_setfield(L, -2, "gain");
lua_pushnumber(L, spec.fade);
lua_setfield(L, -2, "fade");
lua_pushnumber(L, spec.pitch);
lua_setfield(L, -2, "pitch");
}
/******************************************************************************/
NodeBox read_nodebox(lua_State *L, int index)
{
NodeBox nodebox;
if(lua_istable(L, -1)){
nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR);
#define NODEBOXREAD(n, s){ \
lua_getfield(L, index, (s)); \
if (lua_istable(L, -1)) \
(n) = read_aabb3f(L, -1, BS); \
lua_pop(L, 1); \
}
#define NODEBOXREADVEC(n, s) \
lua_getfield(L, index, (s)); \
if (lua_istable(L, -1)) \
(n) = read_aabb3f_vector(L, -1, BS); \
lua_pop(L, 1);
NODEBOXREADVEC(nodebox.fixed, "fixed");
NODEBOXREAD(nodebox.wall_top, "wall_top");
NODEBOXREAD(nodebox.wall_bottom, "wall_bottom");
NODEBOXREAD(nodebox.wall_side, "wall_side");
NODEBOXREADVEC(nodebox.connect_top, "connect_top");
NODEBOXREADVEC(nodebox.connect_bottom, "connect_bottom");
NODEBOXREADVEC(nodebox.connect_front, "connect_front");
NODEBOXREADVEC(nodebox.connect_left, "connect_left");
NODEBOXREADVEC(nodebox.connect_back, "connect_back");
NODEBOXREADVEC(nodebox.connect_right, "connect_right");
NODEBOXREADVEC(nodebox.disconnected_top, "disconnected_top");
NODEBOXREADVEC(nodebox.disconnected_bottom, "disconnected_bottom");
NODEBOXREADVEC(nodebox.disconnected_front, "disconnected_front");
NODEBOXREADVEC(nodebox.disconnected_left, "disconnected_left");
NODEBOXREADVEC(nodebox.disconnected_back, "disconnected_back");
NODEBOXREADVEC(nodebox.disconnected_right, "disconnected_right");
NODEBOXREADVEC(nodebox.disconnected, "disconnected");
NODEBOXREADVEC(nodebox.disconnected_sides, "disconnected_sides");
}
return nodebox;
}
/******************************************************************************/
MapNode readnode(lua_State *L, int index, const NodeDefManager *ndef)
{
lua_getfield(L, index, "name");
if (!lua_isstring(L, -1))
throw LuaError("Node name is not set or is not a string!");
std::string name = lua_tostring(L, -1);
lua_pop(L, 1);
u8 param1 = 0;
lua_getfield(L, index, "param1");
if (!lua_isnil(L, -1))
param1 = lua_tonumber(L, -1);
lua_pop(L, 1);
u8 param2 = 0;
lua_getfield(L, index, "param2");
if (!lua_isnil(L, -1))
param2 = lua_tonumber(L, -1);
lua_pop(L, 1);
content_t id = CONTENT_IGNORE;
if (!ndef->getId(name, id))
throw LuaError("\"" + name + "\" is not a registered node!");
return {id, param1, param2};
}
/******************************************************************************/
void pushnode(lua_State *L, const MapNode &n, const NodeDefManager *ndef)
{
lua_newtable(L);
lua_pushstring(L, ndef->get(n).name.c_str());
lua_setfield(L, -2, "name");
lua_pushnumber(L, n.getParam1());
lua_setfield(L, -2, "param1");
lua_pushnumber(L, n.getParam2());
lua_setfield(L, -2, "param2");
}
/******************************************************************************/
void warn_if_field_exists(lua_State *L, int table,
const char *name, const std::string &message)
{
lua_getfield(L, table, name);
if (!lua_isnil(L, -1)) {
warningstream << "Field \"" << name << "\": "
<< message << std::endl;
infostream << script_get_backtrace(L) << std::endl;
}
lua_pop(L, 1);
}
/******************************************************************************/
int getenumfield(lua_State *L, int table,
const char *fieldname, const EnumString *spec, int default_)
{
int result = default_;
string_to_enum(spec, result,
getstringfield_default(L, table, fieldname, ""));
return result;
}
/******************************************************************************/
bool string_to_enum(const EnumString *spec, int &result,
const std::string &str)
{
const EnumString *esp = spec;
while(esp->str){
if(str == std::string(esp->str)){
result = esp->num;
return true;
}
esp++;
}
return false;
}
/******************************************************************************/
ItemStack read_item(lua_State* L, int index, IItemDefManager *idef)
{
if(index < 0)
index = lua_gettop(L) + 1 + index;
if (lua_isnil(L, index)) {
return ItemStack();
}
if (lua_isuserdata(L, index)) {
// Convert from LuaItemStack
LuaItemStack *o = LuaItemStack::checkobject(L, index);
return o->getItem();
}
if (lua_isstring(L, index)) {
// Convert from itemstring
std::string itemstring = lua_tostring(L, index);
try
{
ItemStack item;
item.deSerialize(itemstring, idef);
return item;
}
catch(SerializationError &e)
{
warningstream<<"unable to create item from itemstring"
<<": "<<itemstring<<std::endl;
return ItemStack();
}
}
else if(lua_istable(L, index))
{
// Convert from table
std::string name = getstringfield_default(L, index, "name", "");
int count = getintfield_default(L, index, "count", 1);
int wear = getintfield_default(L, index, "wear", 0);
ItemStack istack(name, count, wear, idef);
// BACKWARDS COMPATIBLITY
std::string value = getstringfield_default(L, index, "metadata", "");
istack.metadata.setString("", value);
// Get meta
lua_getfield(L, index, "meta");
int fieldstable = lua_gettop(L);
if (lua_istable(L, fieldstable)) {
lua_pushnil(L);
while (lua_next(L, fieldstable) != 0) {
// key at index -2 and value at index -1
std::string key = lua_tostring(L, -2);
size_t value_len;
const char *value_cs = lua_tolstring(L, -1, &value_len);
std::string value(value_cs, value_len);
istack.metadata.setString(key, value);
lua_pop(L, 1); // removes value, keeps key for next iteration
}
}
return istack;
} else {
throw LuaError("Expecting itemstack, itemstring, table or nil");
}
}
/******************************************************************************/
void push_tool_capabilities(lua_State *L,
const ToolCapabilities &toolcap)
{
lua_newtable(L);
setfloatfield(L, -1, "full_punch_interval", toolcap.full_punch_interval);
setintfield(L, -1, "max_drop_level", toolcap.max_drop_level);
// Create groupcaps table
lua_newtable(L);
// For each groupcap
for (const auto &gc_it : toolcap.groupcaps) {
// Create groupcap table
lua_newtable(L);
const std::string &name = gc_it.first;
const ToolGroupCap &groupcap = gc_it.second;
// Create subtable "times"
lua_newtable(L);
for (auto time : groupcap.times) {
lua_pushinteger(L, time.first);
lua_pushnumber(L, time.second);
lua_settable(L, -3);
}
// Set subtable "times"
lua_setfield(L, -2, "times");
// Set simple parameters
setintfield(L, -1, "maxlevel", groupcap.maxlevel);
setintfield(L, -1, "uses", groupcap.uses);
// Insert groupcap table into groupcaps table
lua_setfield(L, -2, name.c_str());
}
// Set groupcaps table
lua_setfield(L, -2, "groupcaps");
//Create damage_groups table
lua_newtable(L);
// For each damage group
for (const auto &damageGroup : toolcap.damageGroups) {
// Create damage group table
lua_pushinteger(L, damageGroup.second);
lua_setfield(L, -2, damageGroup.first.c_str());
}
lua_setfield(L, -2, "damage_groups");
}
/******************************************************************************/
void push_inventory_list(lua_State *L, Inventory *inv, const char *name)
{
InventoryList *invlist = inv->getList(name);
if(invlist == NULL){
lua_pushnil(L);
return;
}
std::vector<ItemStack> items;
for(u32 i=0; i<invlist->getSize(); i++)
items.push_back(invlist->getItem(i));
push_items(L, items);
}
/******************************************************************************/
void read_inventory_list(lua_State *L, int tableindex,
Inventory *inv, const char *name, Server* srv, int forcesize)
{
if(tableindex < 0)
tableindex = lua_gettop(L) + 1 + tableindex;
// If nil, delete list
if(lua_isnil(L, tableindex)){
inv->deleteList(name);
return;
}
// Otherwise set list
std::vector<ItemStack> items = read_items(L, tableindex,srv);
int listsize = (forcesize != -1) ? forcesize : items.size();
InventoryList *invlist = inv->addList(name, listsize);
int index = 0;
for(std::vector<ItemStack>::const_iterator
i = items.begin(); i != items.end(); ++i){
if(forcesize != -1 && index == forcesize)
break;
invlist->changeItem(index, *i);
index++;
}
while(forcesize != -1 && index < forcesize){
invlist->deleteItem(index);
index++;
}
}
/******************************************************************************/
struct TileAnimationParams read_animation_definition(lua_State *L, int index)
{
if(index < 0)
index = lua_gettop(L) + 1 + index;
struct TileAnimationParams anim;
anim.type = TAT_NONE;
if (!lua_istable(L, index))
return anim;
anim.type = (TileAnimationType)
getenumfield(L, index, "type", es_TileAnimationType,
TAT_NONE);
if (anim.type == TAT_VERTICAL_FRAMES) {
// {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
anim.vertical_frames.aspect_w =
getintfield_default(L, index, "aspect_w", 16);
anim.vertical_frames.aspect_h =
getintfield_default(L, index, "aspect_h", 16);
anim.vertical_frames.length =
getfloatfield_default(L, index, "length", 1.0);
} else if (anim.type == TAT_SHEET_2D) {
// {type="sheet_2d", frames_w=5, frames_h=3, frame_length=0.5}
getintfield(L, index, "frames_w",
anim.sheet_2d.frames_w);
getintfield(L, index, "frames_h",
anim.sheet_2d.frames_h);
getfloatfield(L, index, "frame_length",
anim.sheet_2d.frame_length);
}
return anim;
}
/******************************************************************************/
ToolCapabilities read_tool_capabilities(
lua_State *L, int table)
{
ToolCapabilities toolcap;
getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
lua_getfield(L, table, "groupcaps");
if(lua_istable(L, -1)){
int table_groupcaps = lua_gettop(L);
lua_pushnil(L);
while(lua_next(L, table_groupcaps) != 0){
// key at index -2 and value at index -1
std::string groupname = luaL_checkstring(L, -2);
if(lua_istable(L, -1)){
int table_groupcap = lua_gettop(L);
// This will be created
ToolGroupCap groupcap;
// Read simple parameters
getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
getintfield(L, table_groupcap, "uses", groupcap.uses);
// DEPRECATED: maxwear
float maxwear = 0;
if (getfloatfield(L, table_groupcap, "maxwear", maxwear)){
if (maxwear != 0)
groupcap.uses = 1.0/maxwear;
else
groupcap.uses = 0;
warningstream << "Field \"maxwear\" is deprecated; "
<< "replace with uses=1/maxwear" << std::endl;
infostream << script_get_backtrace(L) << std::endl;
}
// Read "times" table
lua_getfield(L, table_groupcap, "times");
if(lua_istable(L, -1)){
int table_times = lua_gettop(L);
lua_pushnil(L);
while(lua_next(L, table_times) != 0){
// key at index -2 and value at index -1
int rating = luaL_checkinteger(L, -2);
float time = luaL_checknumber(L, -1);
groupcap.times[rating] = time;
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
}
lua_pop(L, 1);
// Insert groupcap into toolcap
toolcap.groupcaps[groupname] = groupcap;
}
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
}
lua_pop(L, 1);
lua_getfield(L, table, "damage_groups");
if(lua_istable(L, -1)){
int table_damage_groups = lua_gettop(L);
lua_pushnil(L);
while(lua_next(L, table_damage_groups) != 0){
// key at index -2 and value at index -1
std::string groupname = luaL_checkstring(L, -2);
u16 value = luaL_checkinteger(L, -1);
toolcap.damageGroups[groupname] = value;
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
}
lua_pop(L, 1);
return toolcap;
}
/******************************************************************************/
void push_dig_params(lua_State *L,const DigParams ¶ms)
{
lua_newtable(L);
setboolfield(L, -1, "diggable", params.diggable);
setfloatfield(L, -1, "time", params.time);
setintfield(L, -1, "wear", params.wear);
}
/******************************************************************************/
void push_hit_params(lua_State *L,const HitParams ¶ms)
{
lua_newtable(L);
setintfield(L, -1, "hp", params.hp);
setintfield(L, -1, "wear", params.wear);
}
/******************************************************************************/
bool getflagsfield(lua_State *L, int table, const char *fieldname,
FlagDesc *flagdesc, u32 *flags, u32 *flagmask)
{
lua_getfield(L, table, fieldname);
bool success = read_flags(L, -1, flagdesc, flags, flagmask);
lua_pop(L, 1);
return success;
}
bool read_flags(lua_State *L, int index, FlagDesc *flagdesc,
u32 *flags, u32 *flagmask)
{
if (lua_isstring(L, index)) {
std::string flagstr = lua_tostring(L, index);
*flags = readFlagString(flagstr, flagdesc, flagmask);
} else if (lua_istable(L, index)) {
*flags = read_flags_table(L, index, flagdesc, flagmask);
} else {
return false;
}
return true;
}
u32 read_flags_table(lua_State *L, int table, FlagDesc *flagdesc, u32 *flagmask)
{
u32 flags = 0, mask = 0;
char fnamebuf[64] = "no";
for (int i = 0; flagdesc[i].name; i++) {
bool result;
if (getboolfield(L, table, flagdesc[i].name, result)) {
mask |= flagdesc[i].flag;
if (result)
flags |= flagdesc[i].flag;
}
strlcpy(fnamebuf + 2, flagdesc[i].name, sizeof(fnamebuf) - 2);
if (getboolfield(L, table, fnamebuf, result))
mask |= flagdesc[i].flag;
}
if (flagmask)
*flagmask = mask;
return flags;
}
void push_flags_string(lua_State *L, FlagDesc *flagdesc, u32 flags, u32 flagmask)
{
std::string flagstring = writeFlagString(flags, flagdesc, flagmask);
lua_pushlstring(L, flagstring.c_str(), flagstring.size());
}
/******************************************************************************/
/* Lua Stored data! */
/******************************************************************************/
/******************************************************************************/
void read_groups(lua_State *L, int index, ItemGroupList &result)
{
if (!lua_istable(L,index))
return;
result.clear();
lua_pushnil(L);
if(index < 0)
index -= 1;
while(lua_next(L, index) != 0){
// key at index -2 and value at index -1
std::string name = luaL_checkstring(L, -2);
int rating = luaL_checkinteger(L, -1);
result[name] = rating;
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
}
/******************************************************************************/
void push_groups(lua_State *L, const ItemGroupList &groups)
{
lua_newtable(L);
for (const auto &group : groups) {
lua_pushnumber(L, group.second);
lua_setfield(L, -2, group.first.c_str());
}
}
/******************************************************************************/
void push_items(lua_State *L, const std::vector<ItemStack> &items)
{
lua_createtable(L, items.size(), 0);
for (u32 i = 0; i != items.size(); i++) {
LuaItemStack::create(L, items[i]);
lua_rawseti(L, -2, i + 1);
}
}
/******************************************************************************/
std::vector<ItemStack> read_items(lua_State *L, int index, Server *srv)
{
if(index < 0)
index = lua_gettop(L) + 1 + index;
std::vector<ItemStack> items;
luaL_checktype(L, index, LUA_TTABLE);
lua_pushnil(L);
while (lua_next(L, index)) {
s32 key = luaL_checkinteger(L, -2);
if (key < 1) {
throw LuaError("Invalid inventory list index");
}
if (items.size() < (u32) key) {
items.resize(key);
}
items[key - 1] = read_item(L, -1, srv->idef());
lua_pop(L, 1);
}
return items;
}
/******************************************************************************/
void luaentity_get(lua_State *L, u16 id)
{
// Get luaentities[i]
lua_getglobal(L, "core");
lua_getfield(L, -1, "luaentities");
luaL_checktype(L, -1, LUA_TTABLE);
lua_pushnumber(L, id);
lua_gettable(L, -2);
lua_remove(L, -2); // Remove luaentities
lua_remove(L, -2); // Remove core
}
/******************************************************************************/
bool read_noiseparams(lua_State *L, int index, NoiseParams *np)
{
if (index < 0)
index = lua_gettop(L) + 1 + index;
if (!lua_istable(L, index))
return false;
getfloatfield(L, index, "offset", np->offset);
getfloatfield(L, index, "scale", np->scale);
getfloatfield(L, index, "persist", np->persist);
getfloatfield(L, index, "persistence", np->persist);
getfloatfield(L, index, "lacunarity", np->lacunarity);
getintfield(L, index, "seed", np->seed);
getintfield(L, index, "octaves", np->octaves);
u32 flags = 0;
u32 flagmask = 0;
np->flags = getflagsfield(L, index, "flags", flagdesc_noiseparams,
&flags, &flagmask) ? flags : NOISE_FLAG_DEFAULTS;
lua_getfield(L, index, "spread");
np->spread = read_v3f(L, -1);
lua_pop(L, 1);
return true;
}
void push_noiseparams(lua_State *L, NoiseParams *np)
{
lua_newtable(L);
push_float_string(L, np->offset);
lua_setfield(L, -2, "offset");
push_float_string(L, np->scale);
lua_setfield(L, -2, "scale");
push_float_string(L, np->persist);
lua_setfield(L, -2, "persistence");
push_float_string(L, np->lacunarity);
lua_setfield(L, -2, "lacunarity");
lua_pushnumber(L, np->seed);
lua_setfield(L, -2, "seed");
lua_pushnumber(L, np->octaves);
lua_setfield(L, -2, "octaves");
push_flags_string(L, flagdesc_noiseparams, np->flags,
np->flags);
lua_setfield(L, -2, "flags");
push_v3_float_string(L, np->spread);
lua_setfield(L, -2, "spread");
}
/******************************************************************************/
// Returns depth of json value tree
static int push_json_value_getdepth(const Json::Value &value)
{
if (!value.isArray() && !value.isObject())
return 1;
int maxdepth = 0;
for (const auto &it : value) {
int elemdepth = push_json_value_getdepth(it);
if (elemdepth > maxdepth)
maxdepth = elemdepth;
}
return maxdepth + 1;
}
// Recursive function to convert JSON --> Lua table
static bool push_json_value_helper(lua_State *L, const Json::Value &value,
int nullindex)
{
switch(value.type()) {
case Json::nullValue:
default:
lua_pushvalue(L, nullindex);
break;
case Json::intValue:
lua_pushinteger(L, value.asInt());
break;
case Json::uintValue:
lua_pushinteger(L, value.asUInt());
break;
case Json::realValue:
lua_pushnumber(L, value.asDouble());
break;
case Json::stringValue:
{
const char *str = value.asCString();
lua_pushstring(L, str ? str : "");
}
break;
case Json::booleanValue:
lua_pushboolean(L, value.asInt());
break;
case Json::arrayValue:
lua_newtable(L);
for (Json::Value::const_iterator it = value.begin();
it != value.end(); ++it) {
push_json_value_helper(L, *it, nullindex);
lua_rawseti(L, -2, it.index() + 1);
}
break;
case Json::objectValue:
lua_newtable(L);
for (Json::Value::const_iterator it = value.begin();
it != value.end(); ++it) {
#ifndef JSONCPP_STRING
const char *str = it.memberName();
lua_pushstring(L, str ? str : "");
#else
std::string str = it.name();
lua_pushstring(L, str.c_str());
#endif
push_json_value_helper(L, *it, nullindex);
lua_rawset(L, -3);
}
break;
}
return true;
}
// converts JSON --> Lua table; returns false if lua stack limit exceeded
// nullindex: Lua stack index of value to use in place of JSON null
bool push_json_value(lua_State *L, const Json::Value &value, int nullindex)
{
if(nullindex < 0)
nullindex = lua_gettop(L) + 1 + nullindex;
int depth = push_json_value_getdepth(value);
// The maximum number of Lua stack slots used at each recursion level
// of push_json_value_helper is 2, so make sure there a depth * 2 slots
if (lua_checkstack(L, depth * 2))
return push_json_value_helper(L, value, nullindex);
return false;
}
// Converts Lua table --> JSON
void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion)
{
if (recursion > 16) {
throw SerializationError("Maximum recursion depth exceeded");
}
int type = lua_type(L, index);
if (type == LUA_TBOOLEAN) {
root = (bool) lua_toboolean(L, index);
} else if (type == LUA_TNUMBER) {
root = lua_tonumber(L, index);
} else if (type == LUA_TSTRING) {
size_t len;
const char *str = lua_tolstring(L, index, &len);
root = std::string(str, len);
} else if (type == LUA_TTABLE) {
lua_pushnil(L);
while (lua_next(L, index)) {
// Key is at -2 and value is at -1
Json::Value value;
read_json_value(L, value, lua_gettop(L), recursion + 1);
Json::ValueType roottype = root.type();
int keytype = lua_type(L, -1);
if (keytype == LUA_TNUMBER) {
lua_Number key = lua_tonumber(L, -1);
if (roottype != Json::nullValue && roottype != Json::arrayValue) {
throw SerializationError("Can't mix array and object values in JSON");
} else if (key < 1) {
throw SerializationError("Can't use zero-based or negative indexes in JSON");
} else if (floor(key) != key) {
throw SerializationError("Can't use indexes with a fractional part in JSON");
}
root[(Json::ArrayIndex) key - 1] = value;
} else if (keytype == LUA_TSTRING) {
if (roottype != Json::nullValue && roottype != Json::objectValue) {
throw SerializationError("Can't mix array and object values in JSON");
}
root[lua_tostring(L, -1)] = value;
} else {
throw SerializationError("Lua key to convert to JSON is not a string or number");
}
}
} else if (type == LUA_TNIL) {
root = Json::nullValue;
} else {
throw SerializationError("Can only store booleans, numbers, strings, objects, arrays, and null in JSON");
}
lua_pop(L, 1); // Pop value
}
void push_pointed_thing(lua_State *L, const PointedThing &pointed, bool csm,
bool hitpoint)
{
lua_newtable(L);
if (pointed.type == POINTEDTHING_NODE) {
lua_pushstring(L, "node");
lua_setfield(L, -2, "type");
push_v3s16(L, pointed.node_undersurface);
lua_setfield(L, -2, "under");
push_v3s16(L, pointed.node_abovesurface);
lua_setfield(L, -2, "above");
} else if (pointed.type == POINTEDTHING_OBJECT) {
lua_pushstring(L, "object");
lua_setfield(L, -2, "type");
if (csm) {
lua_pushinteger(L, pointed.object_id);
lua_setfield(L, -2, "id");
} else {
push_objectRef(L, pointed.object_id);
lua_setfield(L, -2, "ref");
}
} else {
lua_pushstring(L, "nothing");
lua_setfield(L, -2, "type");
}
if (hitpoint && (pointed.type != POINTEDTHING_NOTHING)) {
push_v3f(L, pointed.intersection_point / BS); // convert to node coords
lua_setfield(L, -2, "intersection_point");
push_v3s16(L, pointed.intersection_normal);
lua_setfield(L, -2, "intersection_normal");
lua_pushinteger(L, pointed.box_id + 1); // change to Lua array index
lua_setfield(L, -2, "box_id");
}
}
void push_objectRef(lua_State *L, const u16 id)
{
// Get core.object_refs[i]
lua_getglobal(L, "core");
lua_getfield(L, -1, "object_refs");
luaL_checktype(L, -1, LUA_TTABLE);
lua_pushnumber(L, id);
lua_gettable(L, -2);
lua_remove(L, -2); // object_refs
lua_remove(L, -2); // core
}
void read_hud_element(lua_State *L, HudElement *elem)
{
elem->type = (HudElementType)getenumfield(L, 2, "hud_elem_type",
es_HudElementType, HUD_ELEM_TEXT);
lua_getfield(L, 2, "position");
elem->pos = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
lua_pop(L, 1);
lua_getfield(L, 2, "scale");
elem->scale = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
lua_pop(L, 1);
lua_getfield(L, 2, "size");
elem->size = lua_istable(L, -1) ? read_v2s32(L, -1) : v2s32();
lua_pop(L, 1);
elem->name = getstringfield_default(L, 2, "name", "");
elem->text = getstringfield_default(L, 2, "text", "");
elem->number = getintfield_default(L, 2, "number", 0);
elem->item = getintfield_default(L, 2, "item", 0);
elem->dir = getintfield_default(L, 2, "direction", 0);
// Deprecated, only for compatibility's sake
if (elem->dir == 0)
elem->dir = getintfield_default(L, 2, "dir", 0);
lua_getfield(L, 2, "alignment");
elem->align = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
lua_pop(L, 1);
lua_getfield(L, 2, "offset");
elem->offset = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
lua_pop(L, 1);
lua_getfield(L, 2, "world_pos");
elem->world_pos = lua_istable(L, -1) ? read_v3f(L, -1) : v3f();
lua_pop(L, 1);
/* check for known deprecated element usage */
if ((elem->type == HUD_ELEM_STATBAR) && (elem->size == v2s32()))
log_deprecated(L,"Deprecated usage of statbar without size!");
}
void push_hud_element(lua_State *L, HudElement *elem)
{
lua_newtable(L);
lua_pushstring(L, es_HudElementType[(u8)elem->type].str);
lua_setfield(L, -2, "type");
push_v2f(L, elem->pos);
lua_setfield(L, -2, "position");
lua_pushstring(L, elem->name.c_str());
lua_setfield(L, -2, "name");
push_v2f(L, elem->scale);
lua_setfield(L, -2, "scale");
lua_pushstring(L, elem->text.c_str());
lua_setfield(L, -2, "text");
lua_pushnumber(L, elem->number);
lua_setfield(L, -2, "number");
lua_pushnumber(L, elem->item);
lua_setfield(L, -2, "item");
lua_pushnumber(L, elem->dir);
lua_setfield(L, -2, "direction");
push_v2f(L, elem->offset);
lua_setfield(L, -2, "offset");
push_v2f(L, elem->align);
lua_setfield(L, -2, "alignment");
push_v2s32(L, elem->size);
lua_setfield(L, -2, "size");
// Deprecated, only for compatibility's sake
lua_pushnumber(L, elem->dir);
lua_setfield(L, -2, "dir");
push_v3f(L, elem->world_pos);
lua_setfield(L, -2, "world_pos");
}
HudElementStat read_hud_change(lua_State *L, HudElement *elem, void **value)
{
HudElementStat stat = HUD_STAT_NUMBER;
if (lua_isstring(L, 3)) {
int statint;
std::string statstr = lua_tostring(L, 3);
stat = string_to_enum(es_HudElementStat, statint, statstr) ?
(HudElementStat)statint : stat;
}
switch (stat) {
case HUD_STAT_POS:
elem->pos = read_v2f(L, 4);
*value = &elem->pos;
break;
case HUD_STAT_NAME:
elem->name = luaL_checkstring(L, 4);
*value = &elem->name;
break;
case HUD_STAT_SCALE:
elem->scale = read_v2f(L, 4);
*value = &elem->scale;
break;
case HUD_STAT_TEXT:
elem->text = luaL_checkstring(L, 4);
*value = &elem->text;
break;
case HUD_STAT_NUMBER:
elem->number = luaL_checknumber(L, 4);
*value = &elem->number;
break;
case HUD_STAT_ITEM:
elem->item = luaL_checknumber(L, 4);
*value = &elem->item;
break;
case HUD_STAT_DIR:
elem->dir = luaL_checknumber(L, 4);
*value = &elem->dir;
break;
case HUD_STAT_ALIGN:
elem->align = read_v2f(L, 4);
*value = &elem->align;
break;
case HUD_STAT_OFFSET:
elem->offset = read_v2f(L, 4);
*value = &elem->offset;
break;
case HUD_STAT_WORLD_POS:
elem->world_pos = read_v3f(L, 4);
*value = &elem->world_pos;
break;
case HUD_STAT_SIZE:
elem->size = read_v2s32(L, 4);
*value = &elem->size;
break;
}
return stat;
}
| pgimeno/minetest | src/script/common/c_content.cpp | C++ | mit | 59,825 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/******************************************************************************/
/******************************************************************************/
/* WARNING!!!! do NOT add this header in any include file or any code file */
/* not being a script/modapi file!!!!!!!! */
/******************************************************************************/
/******************************************************************************/
#pragma once
extern "C" {
#include <lua.h>
}
#include <iostream>
#include <vector>
#include "irrlichttypes_bloated.h"
#include "util/string.h"
#include "itemgroup.h"
#include "itemdef.h"
#include "c_types.h"
#include "hud.h"
namespace Json { class Value; }
struct MapNode;
class NodeDefManager;
struct PointedThing;
struct ItemStack;
struct ItemDefinition;
struct ToolCapabilities;
struct ObjectProperties;
struct SimpleSoundSpec;
struct ServerSoundParams;
class Inventory;
struct NodeBox;
struct ContentFeatures;
struct TileDef;
class Server;
struct DigParams;
struct HitParams;
struct EnumString;
struct NoiseParams;
class Schematic;
ContentFeatures read_content_features (lua_State *L, int index);
void push_content_features (lua_State *L,
const ContentFeatures &c);
void push_nodebox (lua_State *L,
const NodeBox &box);
void push_box (lua_State *L,
const std::vector<aabb3f> &box);
void push_palette (lua_State *L,
const std::vector<video::SColor> *palette);
TileDef read_tiledef (lua_State *L, int index,
u8 drawtype);
void read_soundspec (lua_State *L, int index,
SimpleSoundSpec &spec);
NodeBox read_nodebox (lua_State *L, int index);
void read_server_sound_params (lua_State *L, int index,
ServerSoundParams ¶ms);
void push_dig_params (lua_State *L,
const DigParams ¶ms);
void push_hit_params (lua_State *L,
const HitParams ¶ms);
ItemStack read_item (lua_State *L, int index, IItemDefManager *idef);
struct TileAnimationParams read_animation_definition(lua_State *L, int index);
ToolCapabilities read_tool_capabilities (lua_State *L, int table);
void push_tool_capabilities (lua_State *L,
const ToolCapabilities &prop);
void read_item_definition (lua_State *L, int index, const ItemDefinition &default_def,
ItemDefinition &def);
void push_item_definition (lua_State *L,
const ItemDefinition &i);
void push_item_definition_full (lua_State *L,
const ItemDefinition &i);
void read_object_properties (lua_State *L, int index,
ObjectProperties *prop,
IItemDefManager *idef);
void push_object_properties (lua_State *L,
ObjectProperties *prop);
void push_inventory_list (lua_State *L,
Inventory *inv,
const char *name);
void read_inventory_list (lua_State *L, int tableindex,
Inventory *inv, const char *name,
Server *srv, int forcesize=-1);
MapNode readnode (lua_State *L, int index,
const NodeDefManager *ndef);
void pushnode (lua_State *L, const MapNode &n,
const NodeDefManager *ndef);
void read_groups (lua_State *L, int index,
ItemGroupList &result);
void push_groups (lua_State *L,
const ItemGroupList &groups);
//TODO rename to "read_enum_field"
int getenumfield (lua_State *L, int table,
const char *fieldname,
const EnumString *spec,
int default_);
bool getflagsfield (lua_State *L, int table,
const char *fieldname,
FlagDesc *flagdesc,
u32 *flags, u32 *flagmask);
bool read_flags (lua_State *L, int index,
FlagDesc *flagdesc,
u32 *flags, u32 *flagmask);
void push_flags_string (lua_State *L, FlagDesc *flagdesc,
u32 flags, u32 flagmask);
u32 read_flags_table (lua_State *L, int table,
FlagDesc *flagdesc, u32 *flagmask);
void push_items (lua_State *L,
const std::vector<ItemStack> &items);
std::vector<ItemStack> read_items (lua_State *L,
int index,
Server* srv);
void push_soundspec (lua_State *L,
const SimpleSoundSpec &spec);
bool string_to_enum (const EnumString *spec,
int &result,
const std::string &str);
bool read_noiseparams (lua_State *L, int index,
NoiseParams *np);
void push_noiseparams (lua_State *L, NoiseParams *np);
void luaentity_get (lua_State *L,u16 id);
bool push_json_value (lua_State *L,
const Json::Value &value,
int nullindex);
void read_json_value (lua_State *L, Json::Value &root,
int index, u8 recursion = 0);
/*!
* Pushes a Lua `pointed_thing` to the given Lua stack.
* \param csm If true, a client side pointed thing is pushed
* \param hitpoint If true, the exact pointing location is also pushed
*/
void push_pointed_thing(lua_State *L, const PointedThing &pointed, bool csm =
false, bool hitpoint = false);
void push_objectRef (lua_State *L, const u16 id);
void read_hud_element (lua_State *L, HudElement *elem);
void push_hud_element (lua_State *L, HudElement *elem);
HudElementStat read_hud_change (lua_State *L, HudElement *elem, void **value);
extern struct EnumString es_TileAnimationType[];
| pgimeno/minetest | src/script/common/c_content.h | C++ | mit | 8,491 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
extern "C" {
#include "lua.h"
#include "lauxlib.h"
}
#include "util/numeric.h"
#include "util/serialize.h"
#include "util/string.h"
#include "common/c_converter.h"
#include "common/c_internal.h"
#include "constants.h"
#define CHECK_TYPE(index, name, type) { \
int t = lua_type(L, (index)); \
if (t != (type)) { \
std::string traceback = script_get_backtrace(L); \
throw LuaError(std::string("Invalid ") + (name) + \
" (expected " + lua_typename(L, (type)) + \
" got " + lua_typename(L, t) + ").\n" + traceback); \
} \
}
#define CHECK_POS_COORD(name) CHECK_TYPE(-1, "position coordinate '" name "'", LUA_TNUMBER)
#define CHECK_FLOAT_RANGE(value, name) \
if (value < F1000_MIN || value > F1000_MAX) { \
std::ostringstream error_text; \
error_text << "Invalid float vector dimension range '" name "' " << \
"(expected " << F1000_MIN << " < " name " < " << F1000_MAX << \
" got " << value << ")." << std::endl; \
throw LuaError(error_text.str()); \
}
#define CHECK_POS_TAB(index) CHECK_TYPE(index, "position", LUA_TTABLE)
void push_float_string(lua_State *L, float value)
{
std::stringstream ss;
std::string str;
ss << value;
str = ss.str();
lua_pushstring(L, str.c_str());
}
void push_v3f(lua_State *L, v3f p)
{
lua_newtable(L);
lua_pushnumber(L, p.X);
lua_setfield(L, -2, "x");
lua_pushnumber(L, p.Y);
lua_setfield(L, -2, "y");
lua_pushnumber(L, p.Z);
lua_setfield(L, -2, "z");
}
void push_v2f(lua_State *L, v2f p)
{
lua_newtable(L);
lua_pushnumber(L, p.X);
lua_setfield(L, -2, "x");
lua_pushnumber(L, p.Y);
lua_setfield(L, -2, "y");
}
void push_v3_float_string(lua_State *L, v3f p)
{
lua_newtable(L);
push_float_string(L, p.X);
lua_setfield(L, -2, "x");
push_float_string(L, p.Y);
lua_setfield(L, -2, "y");
push_float_string(L, p.Z);
lua_setfield(L, -2, "z");
}
void push_v2_float_string(lua_State *L, v2f p)
{
lua_newtable(L);
push_float_string(L, p.X);
lua_setfield(L, -2, "x");
push_float_string(L, p.Y);
lua_setfield(L, -2, "y");
}
v2s16 read_v2s16(lua_State *L, int index)
{
v2s16 p;
CHECK_POS_TAB(index);
lua_getfield(L, index, "x");
p.X = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_getfield(L, index, "y");
p.Y = lua_tonumber(L, -1);
lua_pop(L, 1);
return p;
}
void push_v2s16(lua_State *L, v2s16 p)
{
lua_newtable(L);
lua_pushnumber(L, p.X);
lua_setfield(L, -2, "x");
lua_pushnumber(L, p.Y);
lua_setfield(L, -2, "y");
}
void push_v2s32(lua_State *L, v2s32 p)
{
lua_newtable(L);
lua_pushnumber(L, p.X);
lua_setfield(L, -2, "x");
lua_pushnumber(L, p.Y);
lua_setfield(L, -2, "y");
}
v2s32 read_v2s32(lua_State *L, int index)
{
v2s32 p;
CHECK_POS_TAB(index);
lua_getfield(L, index, "x");
p.X = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_getfield(L, index, "y");
p.Y = lua_tonumber(L, -1);
lua_pop(L, 1);
return p;
}
v2f read_v2f(lua_State *L, int index)
{
v2f p;
CHECK_POS_TAB(index);
lua_getfield(L, index, "x");
p.X = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_getfield(L, index, "y");
p.Y = lua_tonumber(L, -1);
lua_pop(L, 1);
return p;
}
v2f check_v2f(lua_State *L, int index)
{
v2f p;
CHECK_POS_TAB(index);
lua_getfield(L, index, "x");
CHECK_POS_COORD("x");
p.X = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_getfield(L, index, "y");
CHECK_POS_COORD("y");
p.Y = lua_tonumber(L, -1);
lua_pop(L, 1);
return p;
}
v3f read_v3f(lua_State *L, int index)
{
v3f pos;
CHECK_POS_TAB(index);
lua_getfield(L, index, "x");
pos.X = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_getfield(L, index, "y");
pos.Y = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_getfield(L, index, "z");
pos.Z = lua_tonumber(L, -1);
lua_pop(L, 1);
return pos;
}
v3f check_v3f(lua_State *L, int index)
{
v3f pos;
CHECK_POS_TAB(index);
lua_getfield(L, index, "x");
CHECK_POS_COORD("x");
pos.X = lua_tonumber(L, -1);
CHECK_FLOAT_RANGE(pos.X, "x")
lua_pop(L, 1);
lua_getfield(L, index, "y");
CHECK_POS_COORD("y");
pos.Y = lua_tonumber(L, -1);
CHECK_FLOAT_RANGE(pos.Y, "y")
lua_pop(L, 1);
lua_getfield(L, index, "z");
CHECK_POS_COORD("z");
pos.Z = lua_tonumber(L, -1);
CHECK_FLOAT_RANGE(pos.Z, "z")
lua_pop(L, 1);
return pos;
}
v3d read_v3d(lua_State *L, int index)
{
v3d pos;
CHECK_POS_TAB(index);
lua_getfield(L, index, "x");
pos.X = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_getfield(L, index, "y");
pos.Y = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_getfield(L, index, "z");
pos.Z = lua_tonumber(L, -1);
lua_pop(L, 1);
return pos;
}
v3d check_v3d(lua_State *L, int index)
{
v3d pos;
CHECK_POS_TAB(index);
lua_getfield(L, index, "x");
CHECK_POS_COORD("x");
pos.X = lua_tonumber(L, -1);
CHECK_FLOAT_RANGE(pos.X, "x")
lua_pop(L, 1);
lua_getfield(L, index, "y");
CHECK_POS_COORD("y");
pos.Y = lua_tonumber(L, -1);
CHECK_FLOAT_RANGE(pos.Y, "y")
lua_pop(L, 1);
lua_getfield(L, index, "z");
CHECK_POS_COORD("z");
pos.Z = lua_tonumber(L, -1);
CHECK_FLOAT_RANGE(pos.Z, "z")
lua_pop(L, 1);
return pos;
}
void push_ARGB8(lua_State *L, video::SColor color)
{
lua_newtable(L);
lua_pushnumber(L, color.getAlpha());
lua_setfield(L, -2, "a");
lua_pushnumber(L, color.getRed());
lua_setfield(L, -2, "r");
lua_pushnumber(L, color.getGreen());
lua_setfield(L, -2, "g");
lua_pushnumber(L, color.getBlue());
lua_setfield(L, -2, "b");
}
void pushFloatPos(lua_State *L, v3f p)
{
p /= BS;
push_v3f(L, p);
}
v3f checkFloatPos(lua_State *L, int index)
{
return check_v3f(L, index) * BS;
}
void push_v3s16(lua_State *L, v3s16 p)
{
lua_newtable(L);
lua_pushnumber(L, p.X);
lua_setfield(L, -2, "x");
lua_pushnumber(L, p.Y);
lua_setfield(L, -2, "y");
lua_pushnumber(L, p.Z);
lua_setfield(L, -2, "z");
}
v3s16 read_v3s16(lua_State *L, int index)
{
// Correct rounding at <0
v3d pf = read_v3d(L, index);
return doubleToInt(pf, 1.0);
}
v3s16 check_v3s16(lua_State *L, int index)
{
// Correct rounding at <0
v3d pf = check_v3d(L, index);
return doubleToInt(pf, 1.0);
}
bool read_color(lua_State *L, int index, video::SColor *color)
{
if (lua_istable(L, index)) {
*color = read_ARGB8(L, index);
} else if (lua_isnumber(L, index)) {
color->set(lua_tonumber(L, index));
} else if (lua_isstring(L, index)) {
video::SColor parsed_color;
if (!parseColorString(lua_tostring(L, index), parsed_color, true))
return false;
*color = parsed_color;
} else {
return false;
}
return true;
}
video::SColor read_ARGB8(lua_State *L, int index)
{
video::SColor color(0);
CHECK_TYPE(index, "ARGB color", LUA_TTABLE);
lua_getfield(L, index, "a");
color.setAlpha(lua_isnumber(L, -1) ? lua_tonumber(L, -1) : 0xFF);
lua_pop(L, 1);
lua_getfield(L, index, "r");
color.setRed(lua_tonumber(L, -1));
lua_pop(L, 1);
lua_getfield(L, index, "g");
color.setGreen(lua_tonumber(L, -1));
lua_pop(L, 1);
lua_getfield(L, index, "b");
color.setBlue(lua_tonumber(L, -1));
lua_pop(L, 1);
return color;
}
aabb3f read_aabb3f(lua_State *L, int index, f32 scale)
{
aabb3f box;
if(lua_istable(L, index)){
lua_rawgeti(L, index, 1);
box.MinEdge.X = lua_tonumber(L, -1) * scale;
lua_pop(L, 1);
lua_rawgeti(L, index, 2);
box.MinEdge.Y = lua_tonumber(L, -1) * scale;
lua_pop(L, 1);
lua_rawgeti(L, index, 3);
box.MinEdge.Z = lua_tonumber(L, -1) * scale;
lua_pop(L, 1);
lua_rawgeti(L, index, 4);
box.MaxEdge.X = lua_tonumber(L, -1) * scale;
lua_pop(L, 1);
lua_rawgeti(L, index, 5);
box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
lua_pop(L, 1);
lua_rawgeti(L, index, 6);
box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
lua_pop(L, 1);
}
box.repair();
return box;
}
void push_aabb3f(lua_State *L, aabb3f box)
{
lua_newtable(L);
lua_pushnumber(L, box.MinEdge.X);
lua_rawseti(L, -2, 1);
lua_pushnumber(L, box.MinEdge.Y);
lua_rawseti(L, -2, 2);
lua_pushnumber(L, box.MinEdge.Z);
lua_rawseti(L, -2, 3);
lua_pushnumber(L, box.MaxEdge.X);
lua_rawseti(L, -2, 4);
lua_pushnumber(L, box.MaxEdge.Y);
lua_rawseti(L, -2, 5);
lua_pushnumber(L, box.MaxEdge.Z);
lua_rawseti(L, -2, 6);
}
std::vector<aabb3f> read_aabb3f_vector(lua_State *L, int index, f32 scale)
{
std::vector<aabb3f> boxes;
if(lua_istable(L, index)){
int n = lua_objlen(L, index);
// Check if it's a single box or a list of boxes
bool possibly_single_box = (n == 6);
for(int i = 1; i <= n && possibly_single_box; i++){
lua_rawgeti(L, index, i);
if(!lua_isnumber(L, -1))
possibly_single_box = false;
lua_pop(L, 1);
}
if(possibly_single_box){
// Read a single box
boxes.push_back(read_aabb3f(L, index, scale));
} else {
// Read a list of boxes
for(int i = 1; i <= n; i++){
lua_rawgeti(L, index, i);
boxes.push_back(read_aabb3f(L, -1, scale));
lua_pop(L, 1);
}
}
}
return boxes;
}
size_t read_stringlist(lua_State *L, int index, std::vector<std::string> *result)
{
if (index < 0)
index = lua_gettop(L) + 1 + index;
size_t num_strings = 0;
if (lua_istable(L, index)) {
lua_pushnil(L);
while (lua_next(L, index)) {
if (lua_isstring(L, -1)) {
result->push_back(lua_tostring(L, -1));
num_strings++;
}
lua_pop(L, 1);
}
} else if (lua_isstring(L, index)) {
result->push_back(lua_tostring(L, index));
num_strings++;
}
return num_strings;
}
/*
Table field getters
*/
bool getstringfield(lua_State *L, int table,
const char *fieldname, std::string &result)
{
lua_getfield(L, table, fieldname);
bool got = false;
if(lua_isstring(L, -1)){
size_t len = 0;
const char *ptr = lua_tolstring(L, -1, &len);
if (ptr) {
result.assign(ptr, len);
got = true;
}
}
lua_pop(L, 1);
return got;
}
bool getfloatfield(lua_State *L, int table,
const char *fieldname, float &result)
{
lua_getfield(L, table, fieldname);
bool got = false;
if(lua_isnumber(L, -1)){
result = lua_tonumber(L, -1);
got = true;
}
lua_pop(L, 1);
return got;
}
bool getboolfield(lua_State *L, int table,
const char *fieldname, bool &result)
{
lua_getfield(L, table, fieldname);
bool got = false;
if(lua_isboolean(L, -1)){
result = lua_toboolean(L, -1);
got = true;
}
lua_pop(L, 1);
return got;
}
size_t getstringlistfield(lua_State *L, int table, const char *fieldname,
std::vector<std::string> *result)
{
lua_getfield(L, table, fieldname);
size_t num_strings_read = read_stringlist(L, -1, result);
lua_pop(L, 1);
return num_strings_read;
}
std::string checkstringfield(lua_State *L, int table,
const char *fieldname)
{
lua_getfield(L, table, fieldname);
CHECK_TYPE(-1, std::string("field \"") + fieldname + '"', LUA_TSTRING);
size_t len;
const char *s = lua_tolstring(L, -1, &len);
lua_pop(L, 1);
return std::string(s, len);
}
std::string getstringfield_default(lua_State *L, int table,
const char *fieldname, const std::string &default_)
{
std::string result = default_;
getstringfield(L, table, fieldname, result);
return result;
}
int getintfield_default(lua_State *L, int table,
const char *fieldname, int default_)
{
int result = default_;
getintfield(L, table, fieldname, result);
return result;
}
float getfloatfield_default(lua_State *L, int table,
const char *fieldname, float default_)
{
float result = default_;
getfloatfield(L, table, fieldname, result);
return result;
}
bool getboolfield_default(lua_State *L, int table,
const char *fieldname, bool default_)
{
bool result = default_;
getboolfield(L, table, fieldname, result);
return result;
}
v3s16 getv3s16field_default(lua_State *L, int table,
const char *fieldname, v3s16 default_)
{
getv3intfield(L, table, fieldname, default_);
return default_;
}
void setstringfield(lua_State *L, int table,
const char *fieldname, const char *value)
{
lua_pushstring(L, value);
if(table < 0)
table -= 1;
lua_setfield(L, table, fieldname);
}
void setintfield(lua_State *L, int table,
const char *fieldname, int value)
{
lua_pushinteger(L, value);
if(table < 0)
table -= 1;
lua_setfield(L, table, fieldname);
}
void setfloatfield(lua_State *L, int table,
const char *fieldname, float value)
{
lua_pushnumber(L, value);
if(table < 0)
table -= 1;
lua_setfield(L, table, fieldname);
}
void setboolfield(lua_State *L, int table,
const char *fieldname, bool value)
{
lua_pushboolean(L, value);
if(table < 0)
table -= 1;
lua_setfield(L, table, fieldname);
}
////
//// Array table slices
////
size_t write_array_slice_float(
lua_State *L,
int table_index,
float *data,
v3u16 data_size,
v3u16 slice_offset,
v3u16 slice_size)
{
v3u16 pmin, pmax(data_size);
if (slice_offset.X > 0) {
slice_offset.X--;
pmin.X = slice_offset.X;
pmax.X = MYMIN(slice_offset.X + slice_size.X, data_size.X);
}
if (slice_offset.Y > 0) {
slice_offset.Y--;
pmin.Y = slice_offset.Y;
pmax.Y = MYMIN(slice_offset.Y + slice_size.Y, data_size.Y);
}
if (slice_offset.Z > 0) {
slice_offset.Z--;
pmin.Z = slice_offset.Z;
pmax.Z = MYMIN(slice_offset.Z + slice_size.Z, data_size.Z);
}
const u32 ystride = data_size.X;
const u32 zstride = data_size.X * data_size.Y;
u32 elem_index = 1;
for (u32 z = pmin.Z; z != pmax.Z; z++)
for (u32 y = pmin.Y; y != pmax.Y; y++)
for (u32 x = pmin.X; x != pmax.X; x++) {
u32 i = z * zstride + y * ystride + x;
lua_pushnumber(L, data[i]);
lua_rawseti(L, table_index, elem_index);
elem_index++;
}
return elem_index - 1;
}
size_t write_array_slice_u16(
lua_State *L,
int table_index,
u16 *data,
v3u16 data_size,
v3u16 slice_offset,
v3u16 slice_size)
{
v3u16 pmin, pmax(data_size);
if (slice_offset.X > 0) {
slice_offset.X--;
pmin.X = slice_offset.X;
pmax.X = MYMIN(slice_offset.X + slice_size.X, data_size.X);
}
if (slice_offset.Y > 0) {
slice_offset.Y--;
pmin.Y = slice_offset.Y;
pmax.Y = MYMIN(slice_offset.Y + slice_size.Y, data_size.Y);
}
if (slice_offset.Z > 0) {
slice_offset.Z--;
pmin.Z = slice_offset.Z;
pmax.Z = MYMIN(slice_offset.Z + slice_size.Z, data_size.Z);
}
const u32 ystride = data_size.X;
const u32 zstride = data_size.X * data_size.Y;
u32 elem_index = 1;
for (u32 z = pmin.Z; z != pmax.Z; z++)
for (u32 y = pmin.Y; y != pmax.Y; y++)
for (u32 x = pmin.X; x != pmax.X; x++) {
u32 i = z * zstride + y * ystride + x;
lua_pushinteger(L, data[i]);
lua_rawseti(L, table_index, elem_index);
elem_index++;
}
return elem_index - 1;
}
| pgimeno/minetest | src/script/common/c_converter.cpp | C++ | mit | 14,957 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/******************************************************************************/
/******************************************************************************/
/* WARNING!!!! do NOT add this header in any include file or any code file */
/* not being a script/modapi file!!!!!!!! */
/******************************************************************************/
/******************************************************************************/
#pragma once
#include <vector>
#include <unordered_map>
#include "irrlichttypes_bloated.h"
#include "common/c_types.h"
extern "C" {
#include <lua.h>
}
std::string getstringfield_default(lua_State *L, int table,
const char *fieldname, const std::string &default_);
bool getboolfield_default(lua_State *L, int table,
const char *fieldname, bool default_);
float getfloatfield_default(lua_State *L, int table,
const char *fieldname, float default_);
int getintfield_default(lua_State *L, int table,
const char *fieldname, int default_);
template<typename T>
bool getintfield(lua_State *L, int table,
const char *fieldname, T &result)
{
lua_getfield(L, table, fieldname);
bool got = false;
if (lua_isnumber(L, -1)){
result = lua_tointeger(L, -1);
got = true;
}
lua_pop(L, 1);
return got;
}
template<class T>
bool getv3intfield(lua_State *L, int index,
const char *fieldname, T &result)
{
lua_getfield(L, index, fieldname);
bool got = false;
if (lua_istable(L, -1)) {
got |= getintfield(L, -1, "x", result.X);
got |= getintfield(L, -1, "y", result.Y);
got |= getintfield(L, -1, "z", result.Z);
}
lua_pop(L, 1);
return got;
}
v3s16 getv3s16field_default(lua_State *L, int table,
const char *fieldname, v3s16 default_);
bool getstringfield(lua_State *L, int table,
const char *fieldname, std::string &result);
size_t getstringlistfield(lua_State *L, int table,
const char *fieldname,
std::vector<std::string> *result);
void read_groups(lua_State *L, int index,
std::unordered_map<std::string, int> &result);
bool getboolfield(lua_State *L, int table,
const char *fieldname, bool &result);
bool getfloatfield(lua_State *L, int table,
const char *fieldname, float &result);
std::string checkstringfield(lua_State *L, int table,
const char *fieldname);
void setstringfield(lua_State *L, int table,
const char *fieldname, const char *value);
void setintfield(lua_State *L, int table,
const char *fieldname, int value);
void setfloatfield(lua_State *L, int table,
const char *fieldname, float value);
void setboolfield(lua_State *L, int table,
const char *fieldname, bool value);
v3f checkFloatPos (lua_State *L, int index);
v3f check_v3f (lua_State *L, int index);
v3s16 check_v3s16 (lua_State *L, int index);
v3f read_v3f (lua_State *L, int index);
v2f read_v2f (lua_State *L, int index);
v2s16 read_v2s16 (lua_State *L, int index);
v2s32 read_v2s32 (lua_State *L, int index);
video::SColor read_ARGB8 (lua_State *L, int index);
bool read_color (lua_State *L, int index,
video::SColor *color);
aabb3f read_aabb3f (lua_State *L, int index, f32 scale);
v3s16 read_v3s16 (lua_State *L, int index);
std::vector<aabb3f> read_aabb3f_vector (lua_State *L, int index, f32 scale);
size_t read_stringlist (lua_State *L, int index,
std::vector<std::string> *result);
void push_float_string (lua_State *L, float value);
void push_v3_float_string(lua_State *L, v3f p);
void push_v2_float_string(lua_State *L, v2f p);
void push_v2s16 (lua_State *L, v2s16 p);
void push_v2s32 (lua_State *L, v2s32 p);
void push_v3s16 (lua_State *L, v3s16 p);
void push_aabb3f (lua_State *L, aabb3f box);
void push_ARGB8 (lua_State *L, video::SColor color);
void pushFloatPos (lua_State *L, v3f p);
void push_v3f (lua_State *L, v3f p);
void push_v2f (lua_State *L, v2f p);
void warn_if_field_exists(lua_State *L, int table,
const char *fieldname,
const std::string &message);
size_t write_array_slice_float(lua_State *L, int table_index, float *data,
v3u16 data_size, v3u16 slice_offset, v3u16 slice_size);
size_t write_array_slice_u16(lua_State *L, int table_index, u16 *data,
v3u16 data_size, v3u16 slice_offset, v3u16 slice_size);
| pgimeno/minetest | src/script/common/c_converter.h | C++ | mit | 6,252 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "common/c_internal.h"
#include "debug.h"
#include "log.h"
#include "porting.h"
#include "settings.h"
std::string script_get_backtrace(lua_State *L)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
lua_call(L, 0, 1);
std::string result = luaL_checkstring(L, -1);
lua_pop(L, 1);
return result;
}
int script_exception_wrapper(lua_State *L, lua_CFunction f)
{
try {
return f(L); // Call wrapped function and return result.
} catch (const char *s) { // Catch and convert exceptions.
lua_pushstring(L, s);
} catch (std::exception &e) {
lua_pushstring(L, e.what());
}
return lua_error(L); // Rethrow as a Lua error.
}
/*
* Note that we can't get tracebacks for LUA_ERRMEM or LUA_ERRERR (without
* hacking Lua internals). For LUA_ERRMEM, this is because memory errors will
* not execute the the error handler, and by the time lua_pcall returns the
* execution stack will have already been unwound. For LUA_ERRERR, there was
* another error while trying to generate a backtrace from a LUA_ERRRUN. It is
* presumed there is an error with the internal Lua state and thus not possible
* to gather a coherent backtrace. Realistically, the best we can do here is
* print which C function performed the failing pcall.
*/
void script_error(lua_State *L, int pcall_result, const char *mod, const char *fxn)
{
if (pcall_result == 0)
return;
const char *err_type;
switch (pcall_result) {
case LUA_ERRRUN:
err_type = "Runtime";
break;
case LUA_ERRMEM:
err_type = "OOM";
break;
case LUA_ERRERR:
err_type = "Double fault";
break;
default:
err_type = "Unknown";
}
if (!mod)
mod = "??";
if (!fxn)
fxn = "??";
const char *err_descr = lua_tostring(L, -1);
if (!err_descr)
err_descr = "<no description>";
char buf[256];
porting::mt_snprintf(buf, sizeof(buf), "%s error from mod '%s' in callback %s(): ",
err_type, mod, fxn);
std::string err_msg(buf);
err_msg += err_descr;
if (pcall_result == LUA_ERRMEM) {
err_msg += "\nCurrent Lua memory usage: "
+ itos(lua_gc(L, LUA_GCCOUNT, 0) >> 10) + " MB";
}
throw LuaError(err_msg);
}
// Push the list of callbacks (a lua table).
// Then push nargs arguments.
// Then call this function, which
// - runs the callbacks
// - replaces the table and arguments with the return value,
// computed depending on mode
void script_run_callbacks_f(lua_State *L, int nargs,
RunCallbacksMode mode, const char *fxn)
{
FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
// Insert error handler
PUSH_ERROR_HANDLER(L);
int error_handler = lua_gettop(L) - nargs - 1;
lua_insert(L, error_handler);
// Insert run_callbacks between error handler and table
lua_getglobal(L, "core");
lua_getfield(L, -1, "run_callbacks");
lua_remove(L, -2);
lua_insert(L, error_handler + 1);
// Insert mode after table
lua_pushnumber(L, (int) mode);
lua_insert(L, error_handler + 3);
// Stack now looks like this:
// ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
int result = lua_pcall(L, nargs + 2, 1, error_handler);
if (result != 0)
script_error(L, result, NULL, fxn);
lua_remove(L, error_handler);
}
void log_deprecated(lua_State *L, const std::string &message)
{
static bool configured = false;
static bool do_log = false;
static bool do_error = false;
// Only read settings on first call
if (!configured) {
std::string value = g_settings->get("deprecated_lua_api_handling");
if (value == "log") {
do_log = true;
} else if (value == "error") {
do_log = true;
do_error = true;
}
}
if (do_log) {
warningstream << message;
if (L) { // L can be NULL if we get called from scripting_game.cpp
lua_Debug ar;
if (!lua_getstack(L, 2, &ar))
FATAL_ERROR_IF(!lua_getstack(L, 1, &ar), "lua_getstack() failed");
FATAL_ERROR_IF(!lua_getinfo(L, "Sl", &ar), "lua_getinfo() failed");
warningstream << " (at " << ar.short_src << ":" << ar.currentline << ")";
}
warningstream << std::endl;
if (L) {
if (do_error)
script_error(L, LUA_ERRRUN, NULL, NULL);
else
infostream << script_get_backtrace(L) << std::endl;
}
}
}
| pgimeno/minetest | src/script/common/c_internal.cpp | C++ | mit | 4,935 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/******************************************************************************/
/******************************************************************************/
/* WARNING!!!! do NOT add this header in any include file or any code file */
/* not being a modapi file!!!!!!!! */
/******************************************************************************/
/******************************************************************************/
#pragma once
extern "C" {
#include <lua.h>
#include <lauxlib.h>
}
#include "common/c_types.h"
/*
Define our custom indices into the Lua registry table.
Lua 5.2 and above define the LUA_RIDX_LAST macro. Only numbers above that
may be used for custom indices, anything else is reserved.
Lua 5.1 / LuaJIT do not use any numeric indices (only string indices),
so we can use numeric indices freely.
*/
#ifdef LUA_RIDX_LAST
#define CUSTOM_RIDX_BASE ((LUA_RIDX_LAST)+1)
#else
#define CUSTOM_RIDX_BASE 1
#endif
#define CUSTOM_RIDX_SCRIPTAPI (CUSTOM_RIDX_BASE)
#define CUSTOM_RIDX_GLOBALS_BACKUP (CUSTOM_RIDX_BASE + 1)
#define CUSTOM_RIDX_CURRENT_MOD_NAME (CUSTOM_RIDX_BASE + 2)
#define CUSTOM_RIDX_BACKTRACE (CUSTOM_RIDX_BASE + 3)
// Pushes the error handler onto the stack and returns its index
#define PUSH_ERROR_HANDLER(L) \
(lua_rawgeti((L), LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE), lua_gettop((L)))
#define PCALL_RESL(L, RES) { \
int result_ = (RES); \
if (result_ != 0) { \
script_error((L), result_, NULL, __FUNCTION__); \
} \
}
#define script_run_callbacks(L, nargs, mode) \
script_run_callbacks_f((L), (nargs), (mode), __FUNCTION__)
// What script_run_callbacks does with the return values of callbacks.
// Regardless of the mode, if only one callback is defined,
// its return value is the total return value.
// Modes only affect the case where 0 or >= 2 callbacks are defined.
enum RunCallbacksMode
{
// Returns the return value of the first callback
// Returns nil if list of callbacks is empty
RUN_CALLBACKS_MODE_FIRST,
// Returns the return value of the last callback
// Returns nil if list of callbacks is empty
RUN_CALLBACKS_MODE_LAST,
// If any callback returns a false value, the first such is returned
// Otherwise, the first callback's return value (trueish) is returned
// Returns true if list of callbacks is empty
RUN_CALLBACKS_MODE_AND,
// Like above, but stops calling callbacks (short circuit)
// after seeing the first false value
RUN_CALLBACKS_MODE_AND_SC,
// If any callback returns a true value, the first such is returned
// Otherwise, the first callback's return value (falseish) is returned
// Returns false if list of callbacks is empty
RUN_CALLBACKS_MODE_OR,
// Like above, but stops calling callbacks (short circuit)
// after seeing the first true value
RUN_CALLBACKS_MODE_OR_SC,
// Note: "a true value" and "a false value" refer to values that
// are converted by readParam<bool> to true or false, respectively.
};
std::string script_get_backtrace(lua_State *L);
int script_exception_wrapper(lua_State *L, lua_CFunction f);
void script_error(lua_State *L, int pcall_result, const char *mod, const char *fxn);
void script_run_callbacks_f(lua_State *L, int nargs,
RunCallbacksMode mode, const char *fxn);
void log_deprecated(lua_State *L, const std::string &message);
| pgimeno/minetest | src/script/common/c_internal.h | C++ | mit | 4,285 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <iostream>
#include "common/c_types.h"
#include "common/c_internal.h"
#include "itemdef.h"
struct EnumString es_ItemType[] =
{
{ITEM_NONE, "none"},
{ITEM_NODE, "node"},
{ITEM_CRAFT, "craft"},
{ITEM_TOOL, "tool"},
{0, NULL},
};
| pgimeno/minetest | src/script/common/c_types.cpp | C++ | mit | 1,036 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
extern "C" {
#include "lua.h"
}
#include <iostream>
#include "exceptions.h"
struct EnumString
{
int num;
const char *str;
};
class StackUnroller
{
private:
lua_State *m_lua;
int m_original_top;
public:
StackUnroller(lua_State *L):
m_lua(L),
m_original_top(-1)
{
m_original_top = lua_gettop(m_lua); // store stack height
}
~StackUnroller()
{
lua_settop(m_lua, m_original_top); // restore stack height
}
};
class LuaError : public ModError
{
public:
LuaError(const std::string &s) : ModError(s) {}
};
extern EnumString es_ItemType[];
| pgimeno/minetest | src/script/common/c_types.h | C++ | mit | 1,357 |
/*
Minetest
Copyright (C) 2018 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "helper.h"
#include <cmath>
#include <sstream>
#include <irr_v2d.h>
#include "c_types.h"
#include "c_internal.h"
// imported from c_converter.cpp with pure C++ style
static inline void check_lua_type(lua_State *L, int index, const char *name, int type)
{
int t = lua_type(L, index);
if (t != type) {
std::string traceback = script_get_backtrace(L);
throw LuaError(std::string("Invalid ") + (name) + " (expected " +
lua_typename(L, (type)) + " got " + lua_typename(L, t) +
").\n" + traceback);
}
}
// imported from c_converter.cpp
#define CHECK_POS_COORD(name) \
check_lua_type(L, -1, "position coordinate '" name "'", LUA_TNUMBER)
#define CHECK_POS_TAB(index) check_lua_type(L, index, "position", LUA_TTABLE)
bool LuaHelper::isNaN(lua_State *L, int idx)
{
return lua_type(L, idx) == LUA_TNUMBER && std::isnan(lua_tonumber(L, idx));
}
/*
* Read template functions
*/
template <> bool LuaHelper::readParam(lua_State *L, int index)
{
return lua_toboolean(L, index) != 0;
}
template <> bool LuaHelper::readParam(lua_State *L, int index, const bool &default_value)
{
if (lua_isnil(L, index))
return default_value;
return lua_toboolean(L, index) != 0;
}
template <> s16 LuaHelper::readParam(lua_State *L, int index)
{
return lua_tonumber(L, index);
}
template <> float LuaHelper::readParam(lua_State *L, int index)
{
if (isNaN(L, index))
throw LuaError("NaN value is not allowed.");
return (float)luaL_checknumber(L, index);
}
template <> v2s16 LuaHelper::readParam(lua_State *L, int index)
{
v2s16 p;
CHECK_POS_TAB(index);
lua_getfield(L, index, "x");
CHECK_POS_COORD("x");
p.X = readParam<s16>(L, -1);
lua_pop(L, 1);
lua_getfield(L, index, "y");
CHECK_POS_COORD("y");
p.Y = readParam<s16>(L, -1);
lua_pop(L, 1);
return p;
}
template <> v2f LuaHelper::readParam(lua_State *L, int index)
{
v2f p;
CHECK_POS_TAB(index);
lua_getfield(L, index, "x");
CHECK_POS_COORD("x");
p.X = readParam<float>(L, -1);
lua_pop(L, 1);
lua_getfield(L, index, "y");
CHECK_POS_COORD("y");
p.Y = readParam<float>(L, -1);
lua_pop(L, 1);
return p;
}
template <> std::string LuaHelper::readParam(lua_State *L, int index)
{
std::string result;
const char *str = luaL_checkstring(L, index);
result.append(str);
return result;
}
template <>
std::string LuaHelper::readParam(
lua_State *L, int index, const std::string &default_value)
{
std::string result;
const char *str = lua_tostring(L, index);
if (str)
result.append(str);
else
result = default_value;
return result;
}
| pgimeno/minetest | src/script/common/helper.cpp | C++ | mit | 3,374 |
/*
Minetest
Copyright (C) 2018 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
extern "C" {
#include <lua.h>
#include <lauxlib.h>
}
class LuaHelper
{
protected:
static bool isNaN(lua_State *L, int idx);
/**
* Read a value using a template type T from Lua State L and index
*
*
* @tparam T type to read from Lua
* @param L Lua state
* @param index Lua Index to read
* @return read value from Lua
*/
template <typename T> static T readParam(lua_State *L, int index);
/**
* Read a value using a template type T from Lua State L and index
*
* @tparam T type to read from Lua
* @param L Lua state
* @param index Lua Index to read
* @param default_value default value to apply if nil
* @return read value from Lua or default value if nil
*/
template <typename T>
static T readParam(lua_State *L, int index, const T &default_value);
};
| pgimeno/minetest | src/script/common/helper.h | C++ | mit | 1,594 |
set(common_SCRIPT_CPP_API_SRCS
${CMAKE_CURRENT_SOURCE_DIR}/s_async.cpp
${CMAKE_CURRENT_SOURCE_DIR}/s_base.cpp
${CMAKE_CURRENT_SOURCE_DIR}/s_entity.cpp
${CMAKE_CURRENT_SOURCE_DIR}/s_env.cpp
${CMAKE_CURRENT_SOURCE_DIR}/s_inventory.cpp
${CMAKE_CURRENT_SOURCE_DIR}/s_item.cpp
${CMAKE_CURRENT_SOURCE_DIR}/s_modchannels.cpp
${CMAKE_CURRENT_SOURCE_DIR}/s_node.cpp
${CMAKE_CURRENT_SOURCE_DIR}/s_nodemeta.cpp
${CMAKE_CURRENT_SOURCE_DIR}/s_player.cpp
${CMAKE_CURRENT_SOURCE_DIR}/s_security.cpp
${CMAKE_CURRENT_SOURCE_DIR}/s_server.cpp
PARENT_SCOPE)
set(client_SCRIPT_CPP_API_SRCS
${CMAKE_CURRENT_SOURCE_DIR}/s_client.cpp
${CMAKE_CURRENT_SOURCE_DIR}/s_mainmenu.cpp
PARENT_SCOPE)
| pgimeno/minetest | src/script/cpp_api/CMakeLists.txt | Text | mit | 686 |
/*
Minetest
Copyright (C) 2013 sapier, <sapier AT gmx DOT net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <cstdio>
#include <cstdlib>
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#include "server.h"
#include "s_async.h"
#include "log.h"
#include "filesys.h"
#include "porting.h"
#include "common/c_internal.h"
/******************************************************************************/
AsyncEngine::~AsyncEngine()
{
// Request all threads to stop
for (AsyncWorkerThread *workerThread : workerThreads) {
workerThread->stop();
}
// Wake up all threads
for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin();
it != workerThreads.end(); ++it) {
jobQueueCounter.post();
}
// Wait for threads to finish
for (AsyncWorkerThread *workerThread : workerThreads) {
workerThread->wait();
}
// Force kill all threads
for (AsyncWorkerThread *workerThread : workerThreads) {
delete workerThread;
}
jobQueueMutex.lock();
jobQueue.clear();
jobQueueMutex.unlock();
workerThreads.clear();
}
/******************************************************************************/
void AsyncEngine::registerStateInitializer(StateInitializer func)
{
stateInitializers.push_back(func);
}
/******************************************************************************/
void AsyncEngine::initialize(unsigned int numEngines)
{
initDone = true;
for (unsigned int i = 0; i < numEngines; i++) {
AsyncWorkerThread *toAdd = new AsyncWorkerThread(this,
std::string("AsyncWorker-") + itos(i));
workerThreads.push_back(toAdd);
toAdd->start();
}
}
/******************************************************************************/
unsigned int AsyncEngine::queueAsyncJob(const std::string &func,
const std::string ¶ms)
{
jobQueueMutex.lock();
LuaJobInfo toAdd;
toAdd.id = jobIdCounter++;
toAdd.serializedFunction = func;
toAdd.serializedParams = params;
jobQueue.push_back(toAdd);
jobQueueCounter.post();
jobQueueMutex.unlock();
return toAdd.id;
}
/******************************************************************************/
LuaJobInfo AsyncEngine::getJob()
{
jobQueueCounter.wait();
jobQueueMutex.lock();
LuaJobInfo retval;
if (!jobQueue.empty()) {
retval = jobQueue.front();
jobQueue.pop_front();
retval.valid = true;
}
jobQueueMutex.unlock();
return retval;
}
/******************************************************************************/
void AsyncEngine::putJobResult(const LuaJobInfo &result)
{
resultQueueMutex.lock();
resultQueue.push_back(result);
resultQueueMutex.unlock();
}
/******************************************************************************/
void AsyncEngine::step(lua_State *L)
{
int error_handler = PUSH_ERROR_HANDLER(L);
lua_getglobal(L, "core");
resultQueueMutex.lock();
while (!resultQueue.empty()) {
LuaJobInfo jobDone = resultQueue.front();
resultQueue.pop_front();
lua_getfield(L, -1, "async_event_handler");
if (lua_isnil(L, -1)) {
FATAL_ERROR("Async event handler does not exist!");
}
luaL_checktype(L, -1, LUA_TFUNCTION);
lua_pushinteger(L, jobDone.id);
lua_pushlstring(L, jobDone.serializedResult.data(),
jobDone.serializedResult.size());
PCALL_RESL(L, lua_pcall(L, 2, 0, error_handler));
}
resultQueueMutex.unlock();
lua_pop(L, 2); // Pop core and error handler
}
/******************************************************************************/
void AsyncEngine::pushFinishedJobs(lua_State* L) {
// Result Table
MutexAutoLock l(resultQueueMutex);
unsigned int index = 1;
lua_createtable(L, resultQueue.size(), 0);
int top = lua_gettop(L);
while (!resultQueue.empty()) {
LuaJobInfo jobDone = resultQueue.front();
resultQueue.pop_front();
lua_createtable(L, 0, 2); // Pre-allocate space for two map fields
int top_lvl2 = lua_gettop(L);
lua_pushstring(L, "jobid");
lua_pushnumber(L, jobDone.id);
lua_settable(L, top_lvl2);
lua_pushstring(L, "retval");
lua_pushlstring(L, jobDone.serializedResult.data(),
jobDone.serializedResult.size());
lua_settable(L, top_lvl2);
lua_rawseti(L, top, index++);
}
}
/******************************************************************************/
void AsyncEngine::prepareEnvironment(lua_State* L, int top)
{
for (StateInitializer &stateInitializer : stateInitializers) {
stateInitializer(L, top);
}
}
/******************************************************************************/
AsyncWorkerThread::AsyncWorkerThread(AsyncEngine* jobDispatcher,
const std::string &name) :
Thread(name),
ScriptApiBase(ScriptingType::Async),
jobDispatcher(jobDispatcher)
{
lua_State *L = getStack();
// Prepare job lua environment
lua_getglobal(L, "core");
int top = lua_gettop(L);
// Push builtin initialization type
lua_pushstring(L, "async");
lua_setglobal(L, "INIT");
jobDispatcher->prepareEnvironment(L, top);
}
/******************************************************************************/
AsyncWorkerThread::~AsyncWorkerThread()
{
sanity_check(!isRunning());
}
/******************************************************************************/
void* AsyncWorkerThread::run()
{
lua_State *L = getStack();
std::string script = getServer()->getBuiltinLuaPath() + DIR_DELIM + "init.lua";
try {
loadScript(script);
} catch (const ModError &e) {
errorstream << "Execution of async base environment failed: "
<< e.what() << std::endl;
FATAL_ERROR("Execution of async base environment failed");
}
int error_handler = PUSH_ERROR_HANDLER(L);
lua_getglobal(L, "core");
if (lua_isnil(L, -1)) {
FATAL_ERROR("Unable to find core within async environment!");
}
// Main loop
while (!stopRequested()) {
// Wait for job
LuaJobInfo toProcess = jobDispatcher->getJob();
if (!toProcess.valid || stopRequested()) {
continue;
}
lua_getfield(L, -1, "job_processor");
if (lua_isnil(L, -1)) {
FATAL_ERROR("Unable to get async job processor!");
}
luaL_checktype(L, -1, LUA_TFUNCTION);
// Call it
lua_pushlstring(L,
toProcess.serializedFunction.data(),
toProcess.serializedFunction.size());
lua_pushlstring(L,
toProcess.serializedParams.data(),
toProcess.serializedParams.size());
int result = lua_pcall(L, 2, 1, error_handler);
if (result) {
PCALL_RES(result);
toProcess.serializedResult = "";
} else {
// Fetch result
size_t length;
const char *retval = lua_tolstring(L, -1, &length);
toProcess.serializedResult = std::string(retval, length);
}
lua_pop(L, 1); // Pop retval
// Put job result
jobDispatcher->putJobResult(toProcess);
}
lua_pop(L, 2); // Pop core and error handler
return 0;
}
| pgimeno/minetest | src/script/cpp_api/s_async.cpp | C++ | mit | 7,326 |
/*
Minetest
Copyright (C) 2013 sapier, <sapier AT gmx DOT net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include <vector>
#include <deque>
#include <map>
#include "threading/semaphore.h"
#include "threading/thread.h"
#include "lua.h"
#include "cpp_api/s_base.h"
// Forward declarations
class AsyncEngine;
// Declarations
// Data required to queue a job
struct LuaJobInfo
{
LuaJobInfo() = default;
// Function to be called in async environment
std::string serializedFunction = "";
// Parameter to be passed to function
std::string serializedParams = "";
// Result of function call
std::string serializedResult = "";
// JobID used to identify a job and match it to callback
unsigned int id = 0;
bool valid = false;
};
// Asynchronous working environment
class AsyncWorkerThread : public Thread, public ScriptApiBase {
public:
AsyncWorkerThread(AsyncEngine* jobDispatcher, const std::string &name);
virtual ~AsyncWorkerThread();
void *run();
private:
AsyncEngine *jobDispatcher = nullptr;
};
// Asynchornous thread and job management
class AsyncEngine {
friend class AsyncWorkerThread;
typedef void (*StateInitializer)(lua_State *L, int top);
public:
AsyncEngine() = default;
~AsyncEngine();
/**
* Register function to be called on new states
* @param func C function to be called
*/
void registerStateInitializer(StateInitializer func);
/**
* Create async engine tasks and lock function registration
* @param numEngines Number of async threads to be started
*/
void initialize(unsigned int numEngines);
/**
* Queue an async job
* @param func Serialized lua function
* @param params Serialized parameters
* @return jobid The job is queued
*/
unsigned int queueAsyncJob(const std::string &func, const std::string ¶ms);
/**
* Engine step to process finished jobs
* the engine step is one way to pass events back, PushFinishedJobs another
* @param L The Lua stack
*/
void step(lua_State *L);
/**
* Push a list of finished jobs onto the stack
* @param L The Lua stack
*/
void pushFinishedJobs(lua_State *L);
protected:
/**
* Get a Job from queue to be processed
* this function blocks until a job is ready
* @return a job to be processed
*/
LuaJobInfo getJob();
/**
* Put a Job result back to result queue
* @param result result of completed job
*/
void putJobResult(const LuaJobInfo &result);
/**
* Initialize environment with current registred functions
* this function adds all functions registred by registerFunction to the
* passed lua stack
* @param L Lua stack to initialize
* @param top Stack position
*/
void prepareEnvironment(lua_State* L, int top);
private:
// Variable locking the engine against further modification
bool initDone = false;
// Internal store for registred state initializers
std::vector<StateInitializer> stateInitializers;
// Internal counter to create job IDs
unsigned int jobIdCounter = 0;
// Mutex to protect job queue
std::mutex jobQueueMutex;
// Job queue
std::deque<LuaJobInfo> jobQueue;
// Mutex to protect result queue
std::mutex resultQueueMutex;
// Result queue
std::deque<LuaJobInfo> resultQueue;
// List of current worker threads
std::vector<AsyncWorkerThread*> workerThreads;
// Counter semaphore for job dispatching
Semaphore jobQueueCounter;
};
| pgimeno/minetest | src/script/cpp_api/s_async.h | C++ | mit | 4,014 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "cpp_api/s_base.h"
#include "cpp_api/s_internal.h"
#include "cpp_api/s_security.h"
#include "lua_api/l_object.h"
#include "common/c_converter.h"
#include "serverobject.h"
#include "filesys.h"
#include "content/mods.h"
#include "porting.h"
#include "util/string.h"
#include "server.h"
#ifndef SERVER
#include "client/client.h"
#endif
extern "C" {
#include "lualib.h"
#if USE_LUAJIT
#include "luajit.h"
#endif
}
#include <cstdio>
#include <cstdarg>
#include "script/common/c_content.h"
#include "content_sao.h"
#include <sstream>
class ModNameStorer
{
private:
lua_State *L;
public:
ModNameStorer(lua_State *L_, const std::string &mod_name):
L(L_)
{
// Store current mod name in registry
lua_pushstring(L, mod_name.c_str());
lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
}
~ModNameStorer()
{
// Clear current mod name from registry
lua_pushnil(L);
lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
}
};
/*
ScriptApiBase
*/
ScriptApiBase::ScriptApiBase(ScriptingType type):
m_type(type)
{
#ifdef SCRIPTAPI_LOCK_DEBUG
m_lock_recursion_count = 0;
#endif
m_luastack = luaL_newstate();
FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
lua_atpanic(m_luastack, &luaPanic);
if (m_type == ScriptingType::Client)
clientOpenLibs(m_luastack);
else
luaL_openlibs(m_luastack);
// Make the ScriptApiBase* accessible to ModApiBase
lua_pushlightuserdata(m_luastack, this);
lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
// Add and save an error handler
lua_getglobal(m_luastack, "debug");
lua_getfield(m_luastack, -1, "traceback");
lua_rawseti(m_luastack, LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE);
lua_pop(m_luastack, 1); // pop debug
// If we are using LuaJIT add a C++ wrapper function to catch
// exceptions thrown in Lua -> C++ calls
#if USE_LUAJIT
lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper);
luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON);
lua_pop(m_luastack, 1);
#endif
// Add basic globals
lua_newtable(m_luastack);
lua_setglobal(m_luastack, "core");
if (m_type == ScriptingType::Client)
lua_pushstring(m_luastack, "/");
else
lua_pushstring(m_luastack, DIR_DELIM);
lua_setglobal(m_luastack, "DIR_DELIM");
lua_pushstring(m_luastack, porting::getPlatformName());
lua_setglobal(m_luastack, "PLATFORM");
// Make sure Lua uses the right locale
setlocale(LC_NUMERIC, "C");
}
ScriptApiBase::~ScriptApiBase()
{
lua_close(m_luastack);
}
int ScriptApiBase::luaPanic(lua_State *L)
{
std::ostringstream oss;
oss << "LUA PANIC: unprotected error in call to Lua API ("
<< readParam<std::string>(L, -1) << ")";
FATAL_ERROR(oss.str().c_str());
// NOTREACHED
return 0;
}
void ScriptApiBase::clientOpenLibs(lua_State *L)
{
static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = {
{ "", luaopen_base },
{ LUA_TABLIBNAME, luaopen_table },
{ LUA_OSLIBNAME, luaopen_os },
{ LUA_STRLIBNAME, luaopen_string },
{ LUA_MATHLIBNAME, luaopen_math },
{ LUA_DBLIBNAME, luaopen_debug },
#if USE_LUAJIT
{ LUA_JITLIBNAME, luaopen_jit },
#endif
};
for (const std::pair<std::string, lua_CFunction> &lib : m_libs) {
lua_pushcfunction(L, lib.second);
lua_pushstring(L, lib.first.c_str());
lua_call(L, 1, 0);
}
}
void ScriptApiBase::loadMod(const std::string &script_path,
const std::string &mod_name)
{
ModNameStorer mod_name_storer(getStack(), mod_name);
loadScript(script_path);
}
void ScriptApiBase::loadScript(const std::string &script_path)
{
verbosestream << "Loading and running script from " << script_path << std::endl;
lua_State *L = getStack();
int error_handler = PUSH_ERROR_HANDLER(L);
bool ok;
if (m_secure) {
ok = ScriptApiSecurity::safeLoadFile(L, script_path.c_str());
} else {
ok = !luaL_loadfile(L, script_path.c_str());
}
ok = ok && !lua_pcall(L, 0, 0, error_handler);
if (!ok) {
std::string error_msg = readParam<std::string>(L, -1);
lua_pop(L, 2); // Pop error message and error handler
throw ModError("Failed to load and run script from " +
script_path + ":\n" + error_msg);
}
lua_pop(L, 1); // Pop error handler
}
#ifndef SERVER
void ScriptApiBase::loadModFromMemory(const std::string &mod_name)
{
ModNameStorer mod_name_storer(getStack(), mod_name);
const std::string *init_filename = getClient()->getModFile(mod_name + ":init.lua");
const std::string display_filename = mod_name + ":init.lua";
if(init_filename == NULL)
throw ModError("Mod:\"" + mod_name + "\" lacks init.lua");
verbosestream << "Loading and running script " << display_filename << std::endl;
lua_State *L = getStack();
int error_handler = PUSH_ERROR_HANDLER(L);
bool ok = ScriptApiSecurity::safeLoadFile(L, init_filename->c_str(), display_filename.c_str());
if (ok)
ok = !lua_pcall(L, 0, 0, error_handler);
if (!ok) {
std::string error_msg = luaL_checkstring(L, -1);
lua_pop(L, 2); // Pop error message and error handler
throw ModError("Failed to load and run mod \"" +
mod_name + "\":\n" + error_msg);
}
lua_pop(L, 1); // Pop error handler
}
#endif
// Push the list of callbacks (a lua table).
// Then push nargs arguments.
// Then call this function, which
// - runs the callbacks
// - replaces the table and arguments with the return value,
// computed depending on mode
// This function must only be called with scriptlock held (i.e. inside of a
// code block with SCRIPTAPI_PRECHECKHEADER declared)
void ScriptApiBase::runCallbacksRaw(int nargs,
RunCallbacksMode mode, const char *fxn)
{
#ifdef SCRIPTAPI_LOCK_DEBUG
assert(m_lock_recursion_count > 0);
#endif
lua_State *L = getStack();
FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
// Insert error handler
PUSH_ERROR_HANDLER(L);
int error_handler = lua_gettop(L) - nargs - 1;
lua_insert(L, error_handler);
// Insert run_callbacks between error handler and table
lua_getglobal(L, "core");
lua_getfield(L, -1, "run_callbacks");
lua_remove(L, -2);
lua_insert(L, error_handler + 1);
// Insert mode after table
lua_pushnumber(L, (int)mode);
lua_insert(L, error_handler + 3);
// Stack now looks like this:
// ... <error handler> <run_callbacks> <table> <mode> <arg#1> <arg#2> ... <arg#n>
int result = lua_pcall(L, nargs + 2, 1, error_handler);
if (result != 0)
scriptError(result, fxn);
lua_remove(L, error_handler);
}
void ScriptApiBase::realityCheck()
{
int top = lua_gettop(m_luastack);
if (top >= 30) {
dstream << "Stack is over 30:" << std::endl;
stackDump(dstream);
std::string traceback = script_get_backtrace(m_luastack);
throw LuaError("Stack is over 30 (reality check)\n" + traceback);
}
}
void ScriptApiBase::scriptError(int result, const char *fxn)
{
script_error(getStack(), result, m_last_run_mod.c_str(), fxn);
}
void ScriptApiBase::stackDump(std::ostream &o)
{
int top = lua_gettop(m_luastack);
for (int i = 1; i <= top; i++) { /* repeat for each level */
int t = lua_type(m_luastack, i);
switch (t) {
case LUA_TSTRING: /* strings */
o << "\"" << readParam<std::string>(m_luastack, i) << "\"";
break;
case LUA_TBOOLEAN: /* booleans */
o << (readParam<bool>(m_luastack, i) ? "true" : "false");
break;
case LUA_TNUMBER: /* numbers */ {
char buf[10];
porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i));
o << buf;
break;
}
default: /* other values */
o << lua_typename(m_luastack, t);
break;
}
o << " ";
}
o << std::endl;
}
void ScriptApiBase::setOriginDirect(const char *origin)
{
m_last_run_mod = origin ? origin : "??";
}
void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn)
{
#ifdef SCRIPTAPI_DEBUG
lua_State *L = getStack();
m_last_run_mod = lua_istable(L, index) ?
getstringfield_default(L, index, "mod_origin", "") : "";
//printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str());
#endif
}
void ScriptApiBase::addObjectReference(ServerActiveObject *cobj)
{
SCRIPTAPI_PRECHECKHEADER
//infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
// Create object on stack
ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
int object = lua_gettop(L);
// Get core.object_refs table
lua_getglobal(L, "core");
lua_getfield(L, -1, "object_refs");
luaL_checktype(L, -1, LUA_TTABLE);
int objectstable = lua_gettop(L);
// object_refs[id] = object
lua_pushnumber(L, cobj->getId()); // Push id
lua_pushvalue(L, object); // Copy object to top of stack
lua_settable(L, objectstable);
}
void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj)
{
SCRIPTAPI_PRECHECKHEADER
//infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
// Get core.object_refs table
lua_getglobal(L, "core");
lua_getfield(L, -1, "object_refs");
luaL_checktype(L, -1, LUA_TTABLE);
int objectstable = lua_gettop(L);
// Get object_refs[id]
lua_pushnumber(L, cobj->getId()); // Push id
lua_gettable(L, objectstable);
// Set object reference to NULL
ObjectRef::set_null(L);
lua_pop(L, 1); // pop object
// Set object_refs[id] = nil
lua_pushnumber(L, cobj->getId()); // Push id
lua_pushnil(L);
lua_settable(L, objectstable);
}
// Creates a new anonymous reference if cobj=NULL or id=0
void ScriptApiBase::objectrefGetOrCreate(lua_State *L,
ServerActiveObject *cobj)
{
if (cobj == NULL || cobj->getId() == 0) {
ObjectRef::create(L, cobj);
} else {
push_objectRef(L, cobj->getId());
if (cobj->isGone())
warningstream << "ScriptApiBase::objectrefGetOrCreate(): "
<< "Pushing ObjectRef to removed/deactivated object"
<< ", this is probably a bug." << std::endl;
}
}
void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason)
{
if (reason.hasLuaReference())
lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference);
else
lua_newtable(L);
lua_getfield(L, -1, "type");
bool has_type = (bool)lua_isstring(L, -1);
lua_pop(L, 1);
if (!has_type) {
lua_pushstring(L, reason.getTypeAsString().c_str());
lua_setfield(L, -2, "type");
}
lua_pushstring(L, reason.from_mod ? "mod" : "engine");
lua_setfield(L, -2, "from");
if (reason.object) {
objectrefGetOrCreate(L, reason.object);
lua_setfield(L, -2, "object");
}
}
Server* ScriptApiBase::getServer()
{
return dynamic_cast<Server *>(m_gamedef);
}
#ifndef SERVER
Client* ScriptApiBase::getClient()
{
return dynamic_cast<Client *>(m_gamedef);
}
#endif
| pgimeno/minetest | src/script/cpp_api/s_base.cpp | C++ | mit | 11,291 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <unordered_map>
#include "common/helper.h"
#include "util/basic_macros.h"
extern "C" {
#include <lua.h>
#include <lualib.h>
}
#include "irrlichttypes.h"
#include "common/c_types.h"
#include "common/c_internal.h"
#include "debug.h"
#include "config.h"
#define SCRIPTAPI_LOCK_DEBUG
#define SCRIPTAPI_DEBUG
// MUST be an invalid mod name so that mods can't
// use that name to bypass security!
#define BUILTIN_MOD_NAME "*builtin*"
#define PCALL_RES(RES) { \
int result_ = (RES); \
if (result_ != 0) { \
scriptError(result_, __FUNCTION__); \
} \
}
#define runCallbacks(nargs, mode) \
runCallbacksRaw((nargs), (mode), __FUNCTION__)
#define setOriginFromTable(index) \
setOriginFromTableRaw(index, __FUNCTION__)
enum class ScriptingType: u8 {
Async,
Client,
MainMenu,
Server
};
class Server;
#ifndef SERVER
class Client;
#endif
class IGameDef;
class Environment;
class GUIEngine;
class ServerActiveObject;
struct PlayerHPChangeReason;
class ScriptApiBase : protected LuaHelper {
public:
ScriptApiBase(ScriptingType type);
// fake constructor to allow script API classes (e.g ScriptApiEnv) to virtually inherit from this one.
ScriptApiBase()
{
FATAL_ERROR("ScriptApiBase created without ScriptingType!");
}
virtual ~ScriptApiBase();
DISABLE_CLASS_COPY(ScriptApiBase);
// These throw a ModError on failure
void loadMod(const std::string &script_path, const std::string &mod_name);
void loadScript(const std::string &script_path);
#ifndef SERVER
void loadModFromMemory(const std::string &mod_name);
#endif
void runCallbacksRaw(int nargs,
RunCallbacksMode mode, const char *fxn);
/* object */
void addObjectReference(ServerActiveObject *cobj);
void removeObjectReference(ServerActiveObject *cobj);
IGameDef *getGameDef() { return m_gamedef; }
Server* getServer();
ScriptingType getType() { return m_type; }
#ifndef SERVER
Client* getClient();
#endif
std::string getOrigin() { return m_last_run_mod; }
void setOriginDirect(const char *origin);
void setOriginFromTableRaw(int index, const char *fxn);
void clientOpenLibs(lua_State *L);
protected:
friend class LuaABM;
friend class LuaLBM;
friend class InvRef;
friend class ObjectRef;
friend class NodeMetaRef;
friend class ModApiBase;
friend class ModApiEnvMod;
friend class LuaVoxelManip;
lua_State* getStack()
{ return m_luastack; }
void realityCheck();
void scriptError(int result, const char *fxn);
void stackDump(std::ostream &o);
void setGameDef(IGameDef* gamedef) { m_gamedef = gamedef; }
Environment* getEnv() { return m_environment; }
void setEnv(Environment* env) { m_environment = env; }
GUIEngine* getGuiEngine() { return m_guiengine; }
void setGuiEngine(GUIEngine* guiengine) { m_guiengine = guiengine; }
void objectrefGetOrCreate(lua_State *L, ServerActiveObject *cobj);
void pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason& reason);
std::recursive_mutex m_luastackmutex;
std::string m_last_run_mod;
bool m_secure = false;
#ifdef SCRIPTAPI_LOCK_DEBUG
int m_lock_recursion_count{};
std::thread::id m_owning_thread;
#endif
private:
static int luaPanic(lua_State *L);
lua_State *m_luastack = nullptr;
IGameDef *m_gamedef = nullptr;
Environment *m_environment = nullptr;
GUIEngine *m_guiengine = nullptr;
ScriptingType m_type;
};
| pgimeno/minetest | src/script/cpp_api/s_base.h | C++ | mit | 4,319 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "s_client.h"
#include "s_internal.h"
#include "client/client.h"
#include "common/c_converter.h"
#include "common/c_content.h"
#include "s_item.h"
void ScriptApiClient::on_mods_loaded()
{
SCRIPTAPI_PRECHECKHEADER
// Get registered shutdown hooks
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_mods_loaded");
// Call callbacks
runCallbacks(0, RUN_CALLBACKS_MODE_FIRST);
}
void ScriptApiClient::on_shutdown()
{
SCRIPTAPI_PRECHECKHEADER
// Get registered shutdown hooks
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_shutdown");
// Call callbacks
runCallbacks(0, RUN_CALLBACKS_MODE_FIRST);
}
bool ScriptApiClient::on_sending_message(const std::string &message)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_chat_messages
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_sending_chat_message");
// Call callbacks
lua_pushstring(L, message.c_str());
runCallbacks(1, RUN_CALLBACKS_MODE_OR_SC);
return readParam<bool>(L, -1);
}
bool ScriptApiClient::on_receiving_message(const std::string &message)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_chat_messages
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_receiving_chat_message");
// Call callbacks
lua_pushstring(L, message.c_str());
runCallbacks(1, RUN_CALLBACKS_MODE_OR_SC);
return readParam<bool>(L, -1);
}
void ScriptApiClient::on_damage_taken(int32_t damage_amount)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_chat_messages
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_damage_taken");
// Call callbacks
lua_pushinteger(L, damage_amount);
runCallbacks(1, RUN_CALLBACKS_MODE_OR_SC);
}
void ScriptApiClient::on_hp_modification(int32_t newhp)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_chat_messages
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_hp_modification");
// Call callbacks
lua_pushinteger(L, newhp);
runCallbacks(1, RUN_CALLBACKS_MODE_OR_SC);
}
void ScriptApiClient::on_death()
{
SCRIPTAPI_PRECHECKHEADER
// Get registered shutdown hooks
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_death");
// Call callbacks
runCallbacks(0, RUN_CALLBACKS_MODE_FIRST);
}
void ScriptApiClient::environment_step(float dtime)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_globalsteps
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_globalsteps");
// Call callbacks
lua_pushnumber(L, dtime);
try {
runCallbacks(1, RUN_CALLBACKS_MODE_FIRST);
} catch (LuaError &e) {
getClient()->setFatalError(std::string("Client environment_step: ") + e.what() + "\n"
+ script_get_backtrace(L));
}
}
void ScriptApiClient::on_formspec_input(const std::string &formname,
const StringMap &fields)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_chat_messages
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_formspec_input");
// Call callbacks
// param 1
lua_pushstring(L, formname.c_str());
// param 2
lua_newtable(L);
StringMap::const_iterator it;
for (it = fields.begin(); it != fields.end(); ++it) {
const std::string &name = it->first;
const std::string &value = it->second;
lua_pushstring(L, name.c_str());
lua_pushlstring(L, value.c_str(), value.size());
lua_settable(L, -3);
}
runCallbacks(2, RUN_CALLBACKS_MODE_OR_SC);
}
bool ScriptApiClient::on_dignode(v3s16 p, MapNode node)
{
SCRIPTAPI_PRECHECKHEADER
const NodeDefManager *ndef = getClient()->ndef();
// Get core.registered_on_dignode
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_dignode");
// Push data
push_v3s16(L, p);
pushnode(L, node, ndef);
// Call functions
runCallbacks(2, RUN_CALLBACKS_MODE_OR);
return lua_toboolean(L, -1);
}
bool ScriptApiClient::on_punchnode(v3s16 p, MapNode node)
{
SCRIPTAPI_PRECHECKHEADER
const NodeDefManager *ndef = getClient()->ndef();
// Get core.registered_on_punchgnode
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_punchnode");
// Push data
push_v3s16(L, p);
pushnode(L, node, ndef);
// Call functions
runCallbacks(2, RUN_CALLBACKS_MODE_OR);
return readParam<bool>(L, -1);
}
bool ScriptApiClient::on_placenode(const PointedThing &pointed, const ItemDefinition &item)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_placenode
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_placenode");
// Push data
push_pointed_thing(L, pointed, true);
push_item_definition(L, item);
// Call functions
runCallbacks(2, RUN_CALLBACKS_MODE_OR);
return readParam<bool>(L, -1);
}
bool ScriptApiClient::on_item_use(const ItemStack &item, const PointedThing &pointed)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_item_use
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_item_use");
// Push data
LuaItemStack::create(L, item);
push_pointed_thing(L, pointed, true);
// Call functions
runCallbacks(2, RUN_CALLBACKS_MODE_OR);
return readParam<bool>(L, -1);
}
bool ScriptApiClient::on_inventory_open(Inventory *inventory)
{
SCRIPTAPI_PRECHECKHEADER
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_inventory_open");
std::vector<const InventoryList*> lists = inventory->getLists();
std::vector<const InventoryList*>::iterator iter = lists.begin();
lua_createtable(L, 0, lists.size());
for (; iter != lists.end(); iter++) {
const char* name = (*iter)->getName().c_str();
lua_pushstring(L, name);
push_inventory_list(L, inventory, name);
lua_rawset(L, -3);
}
runCallbacks(1, RUN_CALLBACKS_MODE_OR);
return readParam<bool>(L, -1);
}
void ScriptApiClient::setEnv(ClientEnvironment *env)
{
ScriptApiBase::setEnv(env);
}
| pgimeno/minetest | src/script/cpp_api/s_client.cpp | C++ | mit | 6,503 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "util/pointedthing.h"
#include "cpp_api/s_base.h"
#include "mapnode.h"
#include "itemdef.h"
#include "util/string.h"
#include "util/pointedthing.h"
#include "lua_api/l_item.h"
#ifdef _CRT_MSVCP_CURRENT
#include <cstdint>
#endif
class ClientEnvironment;
class ScriptApiClient : virtual public ScriptApiBase
{
public:
// Calls when mods are loaded
void on_mods_loaded();
// Calls on_shutdown handlers
void on_shutdown();
// Chat message handlers
bool on_sending_message(const std::string &message);
bool on_receiving_message(const std::string &message);
void on_damage_taken(int32_t damage_amount);
void on_hp_modification(int32_t newhp);
void on_death();
void environment_step(float dtime);
void on_formspec_input(const std::string &formname, const StringMap &fields);
bool on_dignode(v3s16 p, MapNode node);
bool on_punchnode(v3s16 p, MapNode node);
bool on_placenode(const PointedThing &pointed, const ItemDefinition &item);
bool on_item_use(const ItemStack &item, const PointedThing &pointed);
bool on_inventory_open(Inventory *inventory);
void setEnv(ClientEnvironment *env);
};
| pgimeno/minetest | src/script/cpp_api/s_client.h | C++ | mit | 1,986 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "cpp_api/s_entity.h"
#include "cpp_api/s_internal.h"
#include "log.h"
#include "object_properties.h"
#include "common/c_converter.h"
#include "common/c_content.h"
#include "server.h"
bool ScriptApiEntity::luaentity_Add(u16 id, const char *name)
{
SCRIPTAPI_PRECHECKHEADER
verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
<<name<<"\""<<std::endl;
// Get core.registered_entities[name]
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_entities");
luaL_checktype(L, -1, LUA_TTABLE);
lua_pushstring(L, name);
lua_gettable(L, -2);
// Should be a table, which we will use as a prototype
//luaL_checktype(L, -1, LUA_TTABLE);
if (lua_type(L, -1) != LUA_TTABLE){
errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
return false;
}
int prototype_table = lua_gettop(L);
//dump2(L, "prototype_table");
// Create entity object
lua_newtable(L);
int object = lua_gettop(L);
// Set object metatable
lua_pushvalue(L, prototype_table);
lua_setmetatable(L, -2);
// Add object reference
// This should be userdata with metatable ObjectRef
push_objectRef(L, id);
luaL_checktype(L, -1, LUA_TUSERDATA);
if (!luaL_checkudata(L, -1, "ObjectRef"))
luaL_typerror(L, -1, "ObjectRef");
lua_setfield(L, -2, "object");
// core.luaentities[id] = object
lua_getglobal(L, "core");
lua_getfield(L, -1, "luaentities");
luaL_checktype(L, -1, LUA_TTABLE);
lua_pushnumber(L, id); // Push id
lua_pushvalue(L, object); // Copy object to top of stack
lua_settable(L, -3);
return true;
}
void ScriptApiEntity::luaentity_Activate(u16 id,
const std::string &staticdata, u32 dtime_s)
{
SCRIPTAPI_PRECHECKHEADER
verbosestream << "scriptapi_luaentity_activate: id=" << id << std::endl;
int error_handler = PUSH_ERROR_HANDLER(L);
// Get core.luaentities[id]
luaentity_get(L, id);
int object = lua_gettop(L);
// Get on_activate function
lua_getfield(L, -1, "on_activate");
if (!lua_isnil(L, -1)) {
luaL_checktype(L, -1, LUA_TFUNCTION);
lua_pushvalue(L, object); // self
lua_pushlstring(L, staticdata.c_str(), staticdata.size());
lua_pushinteger(L, dtime_s);
setOriginFromTable(object);
PCALL_RES(lua_pcall(L, 3, 0, error_handler));
} else {
lua_pop(L, 1);
}
lua_pop(L, 2); // Pop object and error handler
}
void ScriptApiEntity::luaentity_Remove(u16 id)
{
SCRIPTAPI_PRECHECKHEADER
verbosestream << "scriptapi_luaentity_rm: id=" << id << std::endl;
// Get core.luaentities table
lua_getglobal(L, "core");
lua_getfield(L, -1, "luaentities");
luaL_checktype(L, -1, LUA_TTABLE);
int objectstable = lua_gettop(L);
// Set luaentities[id] = nil
lua_pushnumber(L, id); // Push id
lua_pushnil(L);
lua_settable(L, objectstable);
lua_pop(L, 2); // pop luaentities, core
}
std::string ScriptApiEntity::luaentity_GetStaticdata(u16 id)
{
SCRIPTAPI_PRECHECKHEADER
//infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
int error_handler = PUSH_ERROR_HANDLER(L);
// Get core.luaentities[id]
luaentity_get(L, id);
int object = lua_gettop(L);
// Get get_staticdata function
lua_getfield(L, -1, "get_staticdata");
if (lua_isnil(L, -1)) {
lua_pop(L, 2); // Pop entity and get_staticdata
return "";
}
luaL_checktype(L, -1, LUA_TFUNCTION);
lua_pushvalue(L, object); // self
setOriginFromTable(object);
PCALL_RES(lua_pcall(L, 1, 1, error_handler));
lua_remove(L, object);
lua_remove(L, error_handler);
size_t len = 0;
const char *s = lua_tolstring(L, -1, &len);
lua_pop(L, 1); // Pop static data
return std::string(s, len);
}
void ScriptApiEntity::luaentity_GetProperties(u16 id,
ObjectProperties *prop)
{
SCRIPTAPI_PRECHECKHEADER
//infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
// Get core.luaentities[id]
luaentity_get(L, id);
// Set default values that differ from ObjectProperties defaults
prop->hp_max = 10;
// Deprecated: read object properties directly
read_object_properties(L, -1, prop, getServer()->idef());
// Read initial_properties
lua_getfield(L, -1, "initial_properties");
read_object_properties(L, -1, prop, getServer()->idef());
lua_pop(L, 1);
}
void ScriptApiEntity::luaentity_Step(u16 id, float dtime)
{
SCRIPTAPI_PRECHECKHEADER
//infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
int error_handler = PUSH_ERROR_HANDLER(L);
// Get core.luaentities[id]
luaentity_get(L, id);
int object = lua_gettop(L);
// State: object is at top of stack
// Get step function
lua_getfield(L, -1, "on_step");
if (lua_isnil(L, -1)) {
lua_pop(L, 2); // Pop on_step and entity
return;
}
luaL_checktype(L, -1, LUA_TFUNCTION);
lua_pushvalue(L, object); // self
lua_pushnumber(L, dtime); // dtime
setOriginFromTable(object);
PCALL_RES(lua_pcall(L, 2, 0, error_handler));
lua_pop(L, 2); // Pop object and error handler
}
// Calls entity:on_punch(ObjectRef puncher, time_from_last_punch,
// tool_capabilities, direction, damage)
bool ScriptApiEntity::luaentity_Punch(u16 id,
ServerActiveObject *puncher, float time_from_last_punch,
const ToolCapabilities *toolcap, v3f dir, s16 damage)
{
SCRIPTAPI_PRECHECKHEADER
//infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
int error_handler = PUSH_ERROR_HANDLER(L);
// Get core.luaentities[id]
luaentity_get(L,id);
int object = lua_gettop(L);
// State: object is at top of stack
// Get function
lua_getfield(L, -1, "on_punch");
if (lua_isnil(L, -1)) {
lua_pop(L, 2); // Pop on_punch and entity
return false;
}
luaL_checktype(L, -1, LUA_TFUNCTION);
lua_pushvalue(L, object); // self
objectrefGetOrCreate(L, puncher); // Clicker reference
lua_pushnumber(L, time_from_last_punch);
push_tool_capabilities(L, *toolcap);
push_v3f(L, dir);
lua_pushnumber(L, damage);
setOriginFromTable(object);
PCALL_RES(lua_pcall(L, 6, 1, error_handler));
bool retval = readParam<bool>(L, -1);
lua_pop(L, 2); // Pop object and error handler
return retval;
}
// Calls entity[field](ObjectRef self, ObjectRef sao)
bool ScriptApiEntity::luaentity_run_simple_callback(u16 id,
ServerActiveObject *sao, const char *field)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
// Get core.luaentities[id]
luaentity_get(L, id);
int object = lua_gettop(L);
// State: object is at top of stack
// Get function
lua_getfield(L, -1, field);
if (lua_isnil(L, -1)) {
lua_pop(L, 2); // Pop callback field and entity
return false;
}
luaL_checktype(L, -1, LUA_TFUNCTION);
lua_pushvalue(L, object); // self
objectrefGetOrCreate(L, sao); // killer reference
setOriginFromTable(object);
PCALL_RES(lua_pcall(L, 2, 1, error_handler));
bool retval = readParam<bool>(L, -1);
lua_pop(L, 2); // Pop object and error handler
return retval;
}
bool ScriptApiEntity::luaentity_on_death(u16 id, ServerActiveObject *killer)
{
return luaentity_run_simple_callback(id, killer, "on_death");
}
// Calls entity:on_rightclick(ObjectRef clicker)
void ScriptApiEntity::luaentity_Rightclick(u16 id, ServerActiveObject *clicker)
{
luaentity_run_simple_callback(id, clicker, "on_rightclick");
}
void ScriptApiEntity::luaentity_on_attach_child(u16 id, ServerActiveObject *child)
{
luaentity_run_simple_callback(id, child, "on_attach_child");
}
void ScriptApiEntity::luaentity_on_detach_child(u16 id, ServerActiveObject *child)
{
luaentity_run_simple_callback(id, child, "on_detach_child");
}
void ScriptApiEntity::luaentity_on_detach(u16 id, ServerActiveObject *parent)
{
luaentity_run_simple_callback(id, parent, "on_detach");
}
| pgimeno/minetest | src/script/cpp_api/s_entity.cpp | C++ | mit | 8,318 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "cpp_api/s_base.h"
#include "irr_v3d.h"
struct ObjectProperties;
struct ToolCapabilities;
class ScriptApiEntity
: virtual public ScriptApiBase
{
public:
bool luaentity_Add(u16 id, const char *name);
void luaentity_Activate(u16 id,
const std::string &staticdata, u32 dtime_s);
void luaentity_Remove(u16 id);
std::string luaentity_GetStaticdata(u16 id);
void luaentity_GetProperties(u16 id,
ObjectProperties *prop);
void luaentity_Step(u16 id, float dtime);
bool luaentity_Punch(u16 id,
ServerActiveObject *puncher, float time_from_last_punch,
const ToolCapabilities *toolcap, v3f dir, s16 damage);
bool luaentity_on_death(u16 id, ServerActiveObject *killer);
void luaentity_Rightclick(u16 id, ServerActiveObject *clicker);
void luaentity_on_attach_child(u16 id, ServerActiveObject *child);
void luaentity_on_detach_child(u16 id, ServerActiveObject *child);
void luaentity_on_detach(u16 id, ServerActiveObject *parent);
private:
bool luaentity_run_simple_callback(u16 id, ServerActiveObject *sao,
const char *field);
};
| pgimeno/minetest | src/script/cpp_api/s_entity.h | C++ | mit | 1,857 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "cpp_api/s_env.h"
#include "cpp_api/s_internal.h"
#include "common/c_converter.h"
#include "log.h"
#include "environment.h"
#include "mapgen/mapgen.h"
#include "lua_api/l_env.h"
#include "server.h"
void ScriptApiEnv::environment_OnGenerated(v3s16 minp, v3s16 maxp,
u32 blockseed)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_generateds
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_generateds");
// Call callbacks
push_v3s16(L, minp);
push_v3s16(L, maxp);
lua_pushnumber(L, blockseed);
runCallbacks(3, RUN_CALLBACKS_MODE_FIRST);
}
void ScriptApiEnv::environment_Step(float dtime)
{
SCRIPTAPI_PRECHECKHEADER
//infostream << "scriptapi_environment_step" << std::endl;
// Get core.registered_globalsteps
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_globalsteps");
// Call callbacks
lua_pushnumber(L, dtime);
try {
runCallbacks(1, RUN_CALLBACKS_MODE_FIRST);
} catch (LuaError &e) {
getServer()->setAsyncFatalError(
std::string("environment_Step: ") + e.what() + "\n"
+ script_get_backtrace(L));
}
}
void ScriptApiEnv::player_event(ServerActiveObject *player, const std::string &type)
{
SCRIPTAPI_PRECHECKHEADER
if (player == NULL)
return;
// Get minetest.registered_playerevents
lua_getglobal(L, "minetest");
lua_getfield(L, -1, "registered_playerevents");
// Call callbacks
objectrefGetOrCreate(L, player); // player
lua_pushstring(L,type.c_str()); // event type
try {
runCallbacks(2, RUN_CALLBACKS_MODE_FIRST);
} catch (LuaError &e) {
getServer()->setAsyncFatalError(
std::string("player_event: ") + e.what() + "\n"
+ script_get_backtrace(L) );
}
}
void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env)
{
SCRIPTAPI_PRECHECKHEADER
verbosestream << "scriptapi_add_environment" << std::endl;
setEnv(env);
/*
Add {Loading,Active}BlockModifiers to environment
*/
// Get core.registered_abms
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_abms");
int registered_abms = lua_gettop(L);
if (!lua_istable(L, registered_abms)) {
lua_pop(L, 1);
throw LuaError("core.registered_abms was not a lua table, as expected.");
}
lua_pushnil(L);
while (lua_next(L, registered_abms)) {
// key at index -2 and value at index -1
int id = lua_tonumber(L, -2);
int current_abm = lua_gettop(L);
std::vector<std::string> trigger_contents;
lua_getfield(L, current_abm, "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.emplace_back(readParam<std::string>(L, -1));
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
} else if (lua_isstring(L, -1)) {
trigger_contents.emplace_back(readParam<std::string>(L, -1));
}
lua_pop(L, 1);
std::vector<std::string> required_neighbors;
lua_getfield(L, current_abm, "neighbors");
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);
required_neighbors.emplace_back(readParam<std::string>(L, -1));
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
} else if (lua_isstring(L, -1)) {
required_neighbors.emplace_back(readParam<std::string>(L, -1));
}
lua_pop(L, 1);
float trigger_interval = 10.0;
getfloatfield(L, current_abm, "interval", trigger_interval);
int trigger_chance = 50;
getintfield(L, current_abm, "chance", trigger_chance);
bool simple_catch_up = true;
getboolfield(L, current_abm, "catch_up", simple_catch_up);
LuaABM *abm = new LuaABM(L, id, trigger_contents, required_neighbors,
trigger_interval, trigger_chance, simple_catch_up);
env->addActiveBlockModifier(abm);
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
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(readParam<std::string>(L, -1));
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
} else if (lua_isstring(L, -1)) {
trigger_contents.insert(readParam<std::string>(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);
}
void ScriptApiEnv::on_emerge_area_completion(
v3s16 blockpos, int action, ScriptCallbackState *state)
{
Server *server = getServer();
// This function should be executed with envlock held.
// The caller (LuaEmergeAreaCallback in src/script/lua_api/l_env.cpp)
// should have obtained the lock.
// Note that the order of these locks is important! Envlock must *ALWAYS*
// be acquired before attempting to acquire scriptlock, or else ServerThread
// will try to acquire scriptlock after it already owns envlock, thus
// deadlocking EmergeThread and ServerThread
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
lua_rawgeti(L, LUA_REGISTRYINDEX, state->callback_ref);
luaL_checktype(L, -1, LUA_TFUNCTION);
push_v3s16(L, blockpos);
lua_pushinteger(L, action);
lua_pushinteger(L, state->refcount);
lua_rawgeti(L, LUA_REGISTRYINDEX, state->args_ref);
setOriginDirect(state->origin.c_str());
try {
PCALL_RES(lua_pcall(L, 4, 0, error_handler));
} catch (LuaError &e) {
server->setAsyncFatalError(
std::string("on_emerge_area_completion: ") + e.what() + "\n"
+ script_get_backtrace(L));
}
lua_pop(L, 1); // Pop error handler
if (state->refcount == 0) {
luaL_unref(L, LUA_REGISTRYINDEX, state->callback_ref);
luaL_unref(L, LUA_REGISTRYINDEX, state->args_ref);
}
}
| pgimeno/minetest | src/script/cpp_api/s_env.cpp | C++ | mit | 7,417 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "cpp_api/s_base.h"
#include "irr_v3d.h"
class ServerEnvironment;
struct ScriptCallbackState;
class ScriptApiEnv : virtual public ScriptApiBase
{
public:
// Called on environment step
void environment_Step(float dtime);
// Called after generating a piece of map
void environment_OnGenerated(v3s16 minp, v3s16 maxp, u32 blockseed);
// Called on player event
void player_event(ServerActiveObject *player, const std::string &type);
// Called after emerge of a block queued from core.emerge_area()
void on_emerge_area_completion(v3s16 blockpos, int action,
ScriptCallbackState *state);
void initializeEnvironment(ServerEnvironment *env);
};
| pgimeno/minetest | src/script/cpp_api/s_env.h | C++ | mit | 1,461 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/******************************************************************************/
/******************************************************************************/
/* WARNING!!!! do NOT add this header in any include file or any code file */
/* not being a modapi file!!!!!!!! */
/******************************************************************************/
/******************************************************************************/
#pragma once
#include <thread>
#include "common/c_internal.h"
#include "cpp_api/s_base.h"
#include "threading/mutex_auto_lock.h"
#ifdef SCRIPTAPI_LOCK_DEBUG
#include <cassert>
class LockChecker {
public:
LockChecker(int *recursion_counter, std::thread::id *owning_thread)
{
m_lock_recursion_counter = recursion_counter;
m_owning_thread = owning_thread;
m_original_level = *recursion_counter;
if (*m_lock_recursion_counter > 0) {
assert(*m_owning_thread == std::this_thread::get_id());
} else {
*m_owning_thread = std::this_thread::get_id();
}
(*m_lock_recursion_counter)++;
}
~LockChecker()
{
assert(*m_owning_thread == std::this_thread::get_id());
assert(*m_lock_recursion_counter > 0);
(*m_lock_recursion_counter)--;
assert(*m_lock_recursion_counter == m_original_level);
}
private:
int *m_lock_recursion_counter;
int m_original_level;
std::thread::id *m_owning_thread;
};
#define SCRIPTAPI_LOCK_CHECK \
LockChecker scriptlock_checker( \
&this->m_lock_recursion_count, \
&this->m_owning_thread)
#else
#define SCRIPTAPI_LOCK_CHECK while(0)
#endif
#define SCRIPTAPI_PRECHECKHEADER \
RecursiveMutexAutoLock scriptlock(this->m_luastackmutex); \
SCRIPTAPI_LOCK_CHECK; \
realityCheck(); \
lua_State *L = getStack(); \
assert(lua_checkstack(L, 20)); \
StackUnroller stack_unroller(L);
| pgimeno/minetest | src/script/cpp_api/s_internal.h | C++ | mit | 2,896 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "cpp_api/s_inventory.h"
#include "cpp_api/s_internal.h"
#include "inventorymanager.h"
#include "lua_api/l_inventory.h"
#include "lua_api/l_item.h"
#include "log.h"
// Return number of accepted items to be moved
int ScriptApiDetached::detached_inventory_AllowMove(
const MoveAction &ma, int count,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
// Push callback function on stack
if (!getDetachedInventoryCallback(ma.from_inv.name, "allow_move"))
return count;
// function(inv, from_list, from_index, to_list, to_index, count, player)
// inv
InvRef::create(L, ma.from_inv);
lua_pushstring(L, ma.from_list.c_str()); // from_list
lua_pushinteger(L, ma.from_i + 1); // from_index
lua_pushstring(L, ma.to_list.c_str()); // to_list
lua_pushinteger(L, ma.to_i + 1); // to_index
lua_pushinteger(L, count); // count
objectrefGetOrCreate(L, player); // player
PCALL_RES(lua_pcall(L, 7, 1, error_handler));
if(!lua_isnumber(L, -1))
throw LuaError("allow_move should return a number. name=" + ma.from_inv.name);
int ret = luaL_checkinteger(L, -1);
lua_pop(L, 2); // Pop integer and error handler
return ret;
}
// Return number of accepted items to be put
int ScriptApiDetached::detached_inventory_AllowPut(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
// Push callback function on stack
if (!getDetachedInventoryCallback(ma.to_inv.name, "allow_put"))
return stack.count; // All will be accepted
// Call function(inv, listname, index, stack, player)
InvRef::create(L, ma.to_inv); // inv
lua_pushstring(L, ma.to_list.c_str()); // listname
lua_pushinteger(L, ma.to_i + 1); // index
LuaItemStack::create(L, stack); // stack
objectrefGetOrCreate(L, player); // player
PCALL_RES(lua_pcall(L, 5, 1, error_handler));
if (!lua_isnumber(L, -1))
throw LuaError("allow_put should return a number. name=" + ma.to_inv.name);
int ret = luaL_checkinteger(L, -1);
lua_pop(L, 2); // Pop integer and error handler
return ret;
}
// Return number of accepted items to be taken
int ScriptApiDetached::detached_inventory_AllowTake(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
// Push callback function on stack
if (!getDetachedInventoryCallback(ma.from_inv.name, "allow_take"))
return stack.count; // All will be accepted
// Call function(inv, listname, index, stack, player)
InvRef::create(L, ma.from_inv); // inv
lua_pushstring(L, ma.from_list.c_str()); // listname
lua_pushinteger(L, ma.from_i + 1); // index
LuaItemStack::create(L, stack); // stack
objectrefGetOrCreate(L, player); // player
PCALL_RES(lua_pcall(L, 5, 1, error_handler));
if (!lua_isnumber(L, -1))
throw LuaError("allow_take should return a number. name=" + ma.from_inv.name);
int ret = luaL_checkinteger(L, -1);
lua_pop(L, 2); // Pop integer and error handler
return ret;
}
// Report moved items
void ScriptApiDetached::detached_inventory_OnMove(
const MoveAction &ma, int count,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
// Push callback function on stack
if (!getDetachedInventoryCallback(ma.from_inv.name, "on_move"))
return;
// function(inv, from_list, from_index, to_list, to_index, count, player)
// inv
InvRef::create(L, ma.from_inv);
lua_pushstring(L, ma.from_list.c_str()); // from_list
lua_pushinteger(L, ma.from_i + 1); // from_index
lua_pushstring(L, ma.to_list.c_str()); // to_list
lua_pushinteger(L, ma.to_i + 1); // to_index
lua_pushinteger(L, count); // count
objectrefGetOrCreate(L, player); // player
PCALL_RES(lua_pcall(L, 7, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
// Report put items
void ScriptApiDetached::detached_inventory_OnPut(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
// Push callback function on stack
if (!getDetachedInventoryCallback(ma.to_inv.name, "on_put"))
return;
// Call function(inv, listname, index, stack, player)
// inv
InvRef::create(L, ma.to_inv);
lua_pushstring(L, ma.to_list.c_str()); // listname
lua_pushinteger(L, ma.to_i + 1); // index
LuaItemStack::create(L, stack); // stack
objectrefGetOrCreate(L, player); // player
PCALL_RES(lua_pcall(L, 5, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
// Report taken items
void ScriptApiDetached::detached_inventory_OnTake(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
// Push callback function on stack
if (!getDetachedInventoryCallback(ma.from_inv.name, "on_take"))
return;
// Call function(inv, listname, index, stack, player)
// inv
InvRef::create(L, ma.from_inv);
lua_pushstring(L, ma.from_list.c_str()); // listname
lua_pushinteger(L, ma.from_i + 1); // index
LuaItemStack::create(L, stack); // stack
objectrefGetOrCreate(L, player); // player
PCALL_RES(lua_pcall(L, 5, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
// Retrieves core.detached_inventories[name][callbackname]
// If that is nil or on error, return false and stack is unchanged
// If that is a function, returns true and pushes the
// function onto the stack
bool ScriptApiDetached::getDetachedInventoryCallback(
const std::string &name, const char *callbackname)
{
lua_State *L = getStack();
lua_getglobal(L, "core");
lua_getfield(L, -1, "detached_inventories");
lua_remove(L, -2);
luaL_checktype(L, -1, LUA_TTABLE);
lua_getfield(L, -1, name.c_str());
lua_remove(L, -2);
// Should be a table
if (lua_type(L, -1) != LUA_TTABLE) {
errorstream<<"Detached inventory \""<<name<<"\" not defined"<<std::endl;
lua_pop(L, 1);
return false;
}
setOriginFromTable(-1);
lua_getfield(L, -1, callbackname);
lua_remove(L, -2);
// Should be a function or nil
if (lua_type(L, -1) == LUA_TFUNCTION) {
return true;
}
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
return false;
}
errorstream << "Detached inventory \"" << name << "\" callback \""
<< callbackname << "\" is not a function" << std::endl;
lua_pop(L, 1);
return false;
}
| pgimeno/minetest | src/script/cpp_api/s_inventory.cpp | C++ | mit | 7,313 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "cpp_api/s_base.h"
struct MoveAction;
struct ItemStack;
class ScriptApiDetached
: virtual public ScriptApiBase
{
public:
/* Detached inventory callbacks */
// Return number of accepted items to be moved
int detached_inventory_AllowMove(
const MoveAction &ma, int count,
ServerActiveObject *player);
// Return number of accepted items to be put
int detached_inventory_AllowPut(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player);
// Return number of accepted items to be taken
int detached_inventory_AllowTake(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player);
// Report moved items
void detached_inventory_OnMove(
const MoveAction &ma, int count,
ServerActiveObject *player);
// Report put items
void detached_inventory_OnPut(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player);
// Report taken items
void detached_inventory_OnTake(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player);
private:
bool getDetachedInventoryCallback(
const std::string &name, const char *callbackname);
};
| pgimeno/minetest | src/script/cpp_api/s_inventory.h | C++ | mit | 1,943 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "cpp_api/s_item.h"
#include "cpp_api/s_internal.h"
#include "common/c_converter.h"
#include "common/c_content.h"
#include "lua_api/l_item.h"
#include "lua_api/l_inventory.h"
#include "server.h"
#include "log.h"
#include "util/pointedthing.h"
#include "inventory.h"
#include "inventorymanager.h"
bool ScriptApiItem::item_OnDrop(ItemStack &item,
ServerActiveObject *dropper, v3f pos)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
// Push callback function on stack
if (!getItemCallback(item.name.c_str(), "on_drop"))
return false;
// Call function
LuaItemStack::create(L, item);
objectrefGetOrCreate(L, dropper);
pushFloatPos(L, pos);
PCALL_RES(lua_pcall(L, 3, 1, error_handler));
if (!lua_isnil(L, -1)) {
try {
item = read_item(L, -1, getServer()->idef());
} catch (LuaError &e) {
throw LuaError(std::string(e.what()) + ". item=" + item.name);
}
}
lua_pop(L, 2); // Pop item and error handler
return true;
}
bool ScriptApiItem::item_OnPlace(ItemStack &item,
ServerActiveObject *placer, const PointedThing &pointed)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
// Push callback function on stack
if (!getItemCallback(item.name.c_str(), "on_place"))
return false;
// Call function
LuaItemStack::create(L, item);
if (!placer)
lua_pushnil(L);
else
objectrefGetOrCreate(L, placer);
pushPointedThing(pointed);
PCALL_RES(lua_pcall(L, 3, 1, error_handler));
if (!lua_isnil(L, -1)) {
try {
item = read_item(L, -1, getServer()->idef());
} catch (LuaError &e) {
throw LuaError(std::string(e.what()) + ". item=" + item.name);
}
}
lua_pop(L, 2); // Pop item and error handler
return true;
}
bool ScriptApiItem::item_OnUse(ItemStack &item,
ServerActiveObject *user, const PointedThing &pointed)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
// Push callback function on stack
if (!getItemCallback(item.name.c_str(), "on_use"))
return false;
// Call function
LuaItemStack::create(L, item);
objectrefGetOrCreate(L, user);
pushPointedThing(pointed);
PCALL_RES(lua_pcall(L, 3, 1, error_handler));
if(!lua_isnil(L, -1)) {
try {
item = read_item(L, -1, getServer()->idef());
} catch (LuaError &e) {
throw LuaError(std::string(e.what()) + ". item=" + item.name);
}
}
lua_pop(L, 2); // Pop item and error handler
return true;
}
bool ScriptApiItem::item_OnSecondaryUse(ItemStack &item, ServerActiveObject *user)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
if (!getItemCallback(item.name.c_str(), "on_secondary_use"))
return false;
LuaItemStack::create(L, item);
objectrefGetOrCreate(L, user);
PointedThing pointed;
pointed.type = POINTEDTHING_NOTHING;
pushPointedThing(pointed);
PCALL_RES(lua_pcall(L, 3, 1, error_handler));
if (!lua_isnil(L, -1)) {
try {
item = read_item(L, -1, getServer()->idef());
} catch (LuaError &e) {
throw LuaError(std::string(e.what()) + ". item=" + item.name);
}
}
lua_pop(L, 2); // Pop item and error handler
return true;
}
bool ScriptApiItem::item_OnCraft(ItemStack &item, ServerActiveObject *user,
const InventoryList *old_craft_grid, const InventoryLocation &craft_inv)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
lua_getglobal(L, "core");
lua_getfield(L, -1, "on_craft");
LuaItemStack::create(L, item);
objectrefGetOrCreate(L, user);
// Push inventory list
std::vector<ItemStack> items;
for (u32 i = 0; i < old_craft_grid->getSize(); i++) {
items.push_back(old_craft_grid->getItem(i));
}
push_items(L, items);
InvRef::create(L, craft_inv);
PCALL_RES(lua_pcall(L, 4, 1, error_handler));
if (!lua_isnil(L, -1)) {
try {
item = read_item(L, -1, getServer()->idef());
} catch (LuaError &e) {
throw LuaError(std::string(e.what()) + ". item=" + item.name);
}
}
lua_pop(L, 2); // Pop item and error handler
return true;
}
bool ScriptApiItem::item_CraftPredict(ItemStack &item, ServerActiveObject *user,
const InventoryList *old_craft_grid, const InventoryLocation &craft_inv)
{
SCRIPTAPI_PRECHECKHEADER
sanity_check(old_craft_grid);
int error_handler = PUSH_ERROR_HANDLER(L);
lua_getglobal(L, "core");
lua_getfield(L, -1, "craft_predict");
LuaItemStack::create(L, item);
objectrefGetOrCreate(L, user);
//Push inventory list
std::vector<ItemStack> items;
for (u32 i = 0; i < old_craft_grid->getSize(); i++) {
items.push_back(old_craft_grid->getItem(i));
}
push_items(L, items);
InvRef::create(L, craft_inv);
PCALL_RES(lua_pcall(L, 4, 1, error_handler));
if (!lua_isnil(L, -1)) {
try {
item = read_item(L, -1, getServer()->idef());
} catch (LuaError &e) {
throw LuaError(std::string(e.what()) + ". item=" + item.name);
}
}
lua_pop(L, 2); // Pop item and error handler
return true;
}
// Retrieves core.registered_items[name][callbackname]
// If that is nil or on error, return false and stack is unchanged
// If that is a function, returns true and pushes the
// function onto the stack
// If core.registered_items[name] doesn't exist, core.nodedef_default
// is tried instead so unknown items can still be manipulated to some degree
bool ScriptApiItem::getItemCallback(const char *name, const char *callbackname,
const v3s16 *p)
{
lua_State* L = getStack();
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_items");
lua_remove(L, -2); // Remove core
luaL_checktype(L, -1, LUA_TTABLE);
lua_getfield(L, -1, name);
lua_remove(L, -2); // Remove registered_items
// Should be a table
if (lua_type(L, -1) != LUA_TTABLE) {
// Report error and clean up
errorstream << "Item \"" << name << "\" not defined";
if (p)
errorstream << " at position " << PP(*p);
errorstream << std::endl;
lua_pop(L, 1);
// Try core.nodedef_default instead
lua_getglobal(L, "core");
lua_getfield(L, -1, "nodedef_default");
lua_remove(L, -2);
luaL_checktype(L, -1, LUA_TTABLE);
}
setOriginFromTable(-1);
lua_getfield(L, -1, callbackname);
lua_remove(L, -2); // Remove item def
// Should be a function or nil
if (lua_type(L, -1) == LUA_TFUNCTION) {
return true;
}
if (!lua_isnil(L, -1)) {
errorstream << "Item \"" << name << "\" callback \""
<< callbackname << "\" is not a function" << std::endl;
}
lua_pop(L, 1);
return false;
}
void ScriptApiItem::pushPointedThing(const PointedThing &pointed, bool hitpoint)
{
lua_State* L = getStack();
push_pointed_thing(L, pointed, false, hitpoint);
}
| pgimeno/minetest | src/script/cpp_api/s_item.cpp | C++ | mit | 7,267 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "cpp_api/s_base.h"
#include "irr_v3d.h"
struct PointedThing;
struct ItemStack;
class ServerActiveObject;
struct ItemDefinition;
class LuaItemStack;
class ModApiItemMod;
class InventoryList;
struct InventoryLocation;
class ScriptApiItem
: virtual public ScriptApiBase
{
public:
bool item_OnDrop(ItemStack &item,
ServerActiveObject *dropper, v3f pos);
bool item_OnPlace(ItemStack &item,
ServerActiveObject *placer, const PointedThing &pointed);
bool item_OnUse(ItemStack &item,
ServerActiveObject *user, const PointedThing &pointed);
bool item_OnSecondaryUse(ItemStack &item,
ServerActiveObject *user);
bool item_OnCraft(ItemStack &item, ServerActiveObject *user,
const InventoryList *old_craft_grid, const InventoryLocation &craft_inv);
bool item_CraftPredict(ItemStack &item, ServerActiveObject *user,
const InventoryList *old_craft_grid, const InventoryLocation &craft_inv);
protected:
friend class LuaItemStack;
friend class ModApiItemMod;
friend class LuaRaycast;
bool getItemCallback(const char *name, const char *callbackname, const v3s16 *p = nullptr);
/*!
* Pushes a `pointed_thing` tabe to the stack.
* \param hitpoint If true, the exact pointing location is also pushed
*/
void pushPointedThing(const PointedThing &pointed, bool hitpoint = false);
};
| pgimeno/minetest | src/script/cpp_api/s_item.h | C++ | mit | 2,109 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "cpp_api/s_mainmenu.h"
#include "cpp_api/s_internal.h"
#include "common/c_converter.h"
void ScriptApiMainMenu::setMainMenuData(MainMenuDataForScript *data)
{
SCRIPTAPI_PRECHECKHEADER
lua_getglobal(L, "gamedata");
int gamedata_idx = lua_gettop(L);
lua_pushstring(L, "errormessage");
if (!data->errormessage.empty()) {
lua_pushstring(L, data->errormessage.c_str());
} else {
lua_pushnil(L);
}
lua_settable(L, gamedata_idx);
setboolfield(L, gamedata_idx, "reconnect_requested", data->reconnect_requested);
lua_pop(L, 1);
}
void ScriptApiMainMenu::handleMainMenuEvent(std::string text)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
// Get handler function
lua_getglobal(L, "core");
lua_getfield(L, -1, "event_handler");
lua_remove(L, -2); // Remove core
if (lua_isnil(L, -1)) {
lua_pop(L, 1); // Pop event_handler
return;
}
luaL_checktype(L, -1, LUA_TFUNCTION);
// Call it
lua_pushstring(L, text.c_str());
PCALL_RES(lua_pcall(L, 1, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
void ScriptApiMainMenu::handleMainMenuButtons(const StringMap &fields)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
// Get handler function
lua_getglobal(L, "core");
lua_getfield(L, -1, "button_handler");
lua_remove(L, -2); // Remove core
if (lua_isnil(L, -1)) {
lua_pop(L, 1); // Pop button handler
return;
}
luaL_checktype(L, -1, LUA_TFUNCTION);
// Convert fields to a Lua table
lua_newtable(L);
StringMap::const_iterator it;
for (it = fields.begin(); it != fields.end(); ++it) {
const std::string &name = it->first;
const std::string &value = it->second;
lua_pushstring(L, name.c_str());
lua_pushlstring(L, value.c_str(), value.size());
lua_settable(L, -3);
}
// Call it
PCALL_RES(lua_pcall(L, 1, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
| pgimeno/minetest | src/script/cpp_api/s_mainmenu.cpp | C++ | mit | 2,660 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "cpp_api/s_base.h"
#include "util/string.h"
#include "gui/guiMainMenu.h"
class ScriptApiMainMenu : virtual public ScriptApiBase {
public:
/**
* Hand over MainMenuDataForScript to lua to inform lua of the content
* @param data the data
*/
void setMainMenuData(MainMenuDataForScript *data);
/**
* process events received from formspec
* @param text events in textual form
*/
void handleMainMenuEvent(std::string text);
/**
* process field data recieved from formspec
* @param fields data in field format
*/
void handleMainMenuButtons(const StringMap &fields);
};
| pgimeno/minetest | src/script/cpp_api/s_mainmenu.h | C++ | mit | 1,396 |
/*
Minetest
Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "s_modchannels.h"
#include "s_internal.h"
void ScriptApiModChannels::on_modchannel_message(const std::string &channel,
const std::string &sender, const std::string &message)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_generateds
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_modchannel_message");
// Call callbacks
lua_pushstring(L, channel.c_str());
lua_pushstring(L, sender.c_str());
lua_pushstring(L, message.c_str());
runCallbacks(3, RUN_CALLBACKS_MODE_AND);
}
void ScriptApiModChannels::on_modchannel_signal(
const std::string &channel, ModChannelSignal signal)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_generateds
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_modchannel_signal");
// Call callbacks
lua_pushstring(L, channel.c_str());
lua_pushinteger(L, (int)signal);
runCallbacks(2, RUN_CALLBACKS_MODE_AND);
}
| pgimeno/minetest | src/script/cpp_api/s_modchannels.cpp | C++ | mit | 1,690 |
/*
Minetest
Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "cpp_api/s_base.h"
#include "modchannels.h"
class ScriptApiModChannels : virtual public ScriptApiBase
{
public:
void on_modchannel_message(const std::string &channel, const std::string &sender,
const std::string &message);
void on_modchannel_signal(const std::string &channel, ModChannelSignal signal);
};
| pgimeno/minetest | src/script/cpp_api/s_modchannels.h | C++ | mit | 1,124 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "cpp_api/s_node.h"
#include "cpp_api/s_internal.h"
#include "common/c_converter.h"
#include "common/c_content.h"
#include "nodedef.h"
#include "server.h"
#include "environment.h"
#include "util/pointedthing.h"
// Should be ordered exactly like enum NodeDrawType in nodedef.h
struct EnumString ScriptApiNode::es_DrawType[] =
{
{NDT_NORMAL, "normal"},
{NDT_AIRLIKE, "airlike"},
{NDT_LIQUID, "liquid"},
{NDT_FLOWINGLIQUID, "flowingliquid"},
{NDT_GLASSLIKE, "glasslike"},
{NDT_ALLFACES, "allfaces"},
{NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
{NDT_TORCHLIKE, "torchlike"},
{NDT_SIGNLIKE, "signlike"},
{NDT_PLANTLIKE, "plantlike"},
{NDT_FENCELIKE, "fencelike"},
{NDT_RAILLIKE, "raillike"},
{NDT_NODEBOX, "nodebox"},
{NDT_GLASSLIKE_FRAMED, "glasslike_framed"},
{NDT_FIRELIKE, "firelike"},
{NDT_GLASSLIKE_FRAMED_OPTIONAL, "glasslike_framed_optional"},
{NDT_MESH, "mesh"},
{NDT_PLANTLIKE_ROOTED, "plantlike_rooted"},
{0, NULL},
};
struct EnumString ScriptApiNode::es_ContentParamType2[] =
{
{CPT2_NONE, "none"},
{CPT2_FULL, "full"},
{CPT2_FLOWINGLIQUID, "flowingliquid"},
{CPT2_FACEDIR, "facedir"},
{CPT2_WALLMOUNTED, "wallmounted"},
{CPT2_LEVELED, "leveled"},
{CPT2_DEGROTATE, "degrotate"},
{CPT2_MESHOPTIONS, "meshoptions"},
{CPT2_COLOR, "color"},
{CPT2_COLORED_FACEDIR, "colorfacedir"},
{CPT2_COLORED_WALLMOUNTED, "colorwallmounted"},
{CPT2_GLASSLIKE_LIQUID_LEVEL, "glasslikeliquidlevel"},
{0, NULL},
};
struct EnumString ScriptApiNode::es_LiquidType[] =
{
{LIQUID_NONE, "none"},
{LIQUID_FLOWING, "flowing"},
{LIQUID_SOURCE, "source"},
{0, NULL},
};
struct EnumString ScriptApiNode::es_ContentParamType[] =
{
{CPT_NONE, "none"},
{CPT_LIGHT, "light"},
{0, NULL},
};
struct EnumString ScriptApiNode::es_NodeBoxType[] =
{
{NODEBOX_REGULAR, "regular"},
{NODEBOX_FIXED, "fixed"},
{NODEBOX_WALLMOUNTED, "wallmounted"},
{NODEBOX_LEVELED, "leveled"},
{NODEBOX_CONNECTED, "connected"},
{0, NULL},
};
bool ScriptApiNode::node_on_punch(v3s16 p, MapNode node,
ServerActiveObject *puncher, PointedThing pointed)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// Push callback function on stack
if (!getItemCallback(ndef->get(node).name.c_str(), "on_punch", &p))
return false;
// Call function
push_v3s16(L, p);
pushnode(L, node, ndef);
objectrefGetOrCreate(L, puncher);
pushPointedThing(pointed);
PCALL_RES(lua_pcall(L, 4, 0, error_handler));
lua_pop(L, 1); // Pop error handler
return true;
}
bool ScriptApiNode::node_on_dig(v3s16 p, MapNode node,
ServerActiveObject *digger)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// Push callback function on stack
if (!getItemCallback(ndef->get(node).name.c_str(), "on_dig", &p))
return false;
// Call function
push_v3s16(L, p);
pushnode(L, node, ndef);
objectrefGetOrCreate(L, digger);
PCALL_RES(lua_pcall(L, 3, 0, error_handler));
lua_pop(L, 1); // Pop error handler
return true;
}
void ScriptApiNode::node_on_construct(v3s16 p, MapNode node)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// Push callback function on stack
if (!getItemCallback(ndef->get(node).name.c_str(), "on_construct", &p))
return;
// Call function
push_v3s16(L, p);
PCALL_RES(lua_pcall(L, 1, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
void ScriptApiNode::node_on_destruct(v3s16 p, MapNode node)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// Push callback function on stack
if (!getItemCallback(ndef->get(node).name.c_str(), "on_destruct", &p))
return;
// Call function
push_v3s16(L, p);
PCALL_RES(lua_pcall(L, 1, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
bool ScriptApiNode::node_on_flood(v3s16 p, MapNode node, MapNode newnode)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// Push callback function on stack
if (!getItemCallback(ndef->get(node).name.c_str(), "on_flood", &p))
return false;
// Call function
push_v3s16(L, p);
pushnode(L, node, ndef);
pushnode(L, newnode, ndef);
PCALL_RES(lua_pcall(L, 3, 1, error_handler));
lua_remove(L, error_handler);
return readParam<bool>(L, -1, false);
}
void ScriptApiNode::node_after_destruct(v3s16 p, MapNode node)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// Push callback function on stack
if (!getItemCallback(ndef->get(node).name.c_str(), "after_destruct", &p))
return;
// Call function
push_v3s16(L, p);
pushnode(L, node, ndef);
PCALL_RES(lua_pcall(L, 2, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
bool ScriptApiNode::node_on_timer(v3s16 p, MapNode node, f32 dtime)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// Push callback function on stack
if (!getItemCallback(ndef->get(node).name.c_str(), "on_timer", &p))
return false;
// Call function
push_v3s16(L, p);
lua_pushnumber(L,dtime);
PCALL_RES(lua_pcall(L, 2, 1, error_handler));
lua_remove(L, error_handler);
return readParam<bool>(L, -1, false);
}
void ScriptApiNode::node_on_receive_fields(v3s16 p,
const std::string &formname,
const StringMap &fields,
ServerActiveObject *sender)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// If node doesn't exist, we don't know what callback to call
MapNode node = getEnv()->getMap().getNodeNoEx(p);
if (node.getContent() == CONTENT_IGNORE)
return;
// Push callback function on stack
if (!getItemCallback(ndef->get(node).name.c_str(), "on_receive_fields", &p))
return;
// Call function
push_v3s16(L, p); // pos
lua_pushstring(L, formname.c_str()); // formname
lua_newtable(L); // fields
StringMap::const_iterator it;
for (it = fields.begin(); it != fields.end(); ++it) {
const std::string &name = it->first;
const std::string &value = it->second;
lua_pushstring(L, name.c_str());
lua_pushlstring(L, value.c_str(), value.size());
lua_settable(L, -3);
}
objectrefGetOrCreate(L, sender); // player
PCALL_RES(lua_pcall(L, 4, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
| pgimeno/minetest | src/script/cpp_api/s_node.cpp | C++ | mit | 7,398 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "irr_v3d.h"
#include "cpp_api/s_base.h"
#include "cpp_api/s_nodemeta.h"
#include "util/string.h"
struct MapNode;
class ServerActiveObject;
class ScriptApiNode
: virtual public ScriptApiBase,
public ScriptApiNodemeta
{
public:
ScriptApiNode() = default;
virtual ~ScriptApiNode() = default;
bool node_on_punch(v3s16 p, MapNode node,
ServerActiveObject *puncher, PointedThing pointed);
bool node_on_dig(v3s16 p, MapNode node,
ServerActiveObject *digger);
void node_on_construct(v3s16 p, MapNode node);
void node_on_destruct(v3s16 p, MapNode node);
bool node_on_flood(v3s16 p, MapNode node, MapNode newnode);
void node_after_destruct(v3s16 p, MapNode node);
bool node_on_timer(v3s16 p, MapNode node, f32 dtime);
void node_on_receive_fields(v3s16 p,
const std::string &formname,
const StringMap &fields,
ServerActiveObject *sender);
public:
static struct EnumString es_DrawType[];
static struct EnumString es_ContentParamType[];
static struct EnumString es_ContentParamType2[];
static struct EnumString es_LiquidType[];
static struct EnumString es_NodeBoxType[];
};
| pgimeno/minetest | src/script/cpp_api/s_node.h | C++ | mit | 1,908 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "cpp_api/s_nodemeta.h"
#include "cpp_api/s_internal.h"
#include "common/c_converter.h"
#include "nodedef.h"
#include "mapnode.h"
#include "server.h"
#include "environment.h"
#include "lua_api/l_item.h"
// Return number of accepted items to be moved
int ScriptApiNodemeta::nodemeta_inventory_AllowMove(
const MoveAction &ma, int count,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// If node doesn't exist, we don't know what callback to call
MapNode node = getEnv()->getMap().getNodeNoEx(ma.to_inv.p);
if (node.getContent() == CONTENT_IGNORE)
return 0;
// Push callback function on stack
std::string nodename = ndef->get(node).name;
if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_move", &ma.to_inv.p))
return count;
// function(pos, from_list, from_index, to_list, to_index, count, player)
push_v3s16(L, ma.to_inv.p); // pos
lua_pushstring(L, ma.from_list.c_str()); // from_list
lua_pushinteger(L, ma.from_i + 1); // from_index
lua_pushstring(L, ma.to_list.c_str()); // to_list
lua_pushinteger(L, ma.to_i + 1); // to_index
lua_pushinteger(L, count); // count
objectrefGetOrCreate(L, player); // player
PCALL_RES(lua_pcall(L, 7, 1, error_handler));
if (!lua_isnumber(L, -1))
throw LuaError("allow_metadata_inventory_move should"
" return a number, guilty node: " + nodename);
int num = luaL_checkinteger(L, -1);
lua_pop(L, 2); // Pop integer and error handler
return num;
}
// Return number of accepted items to be put
int ScriptApiNodemeta::nodemeta_inventory_AllowPut(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// If node doesn't exist, we don't know what callback to call
MapNode node = getEnv()->getMap().getNodeNoEx(ma.to_inv.p);
if (node.getContent() == CONTENT_IGNORE)
return 0;
// Push callback function on stack
std::string nodename = ndef->get(node).name;
if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_put", &ma.to_inv.p))
return stack.count;
// Call function(pos, listname, index, stack, player)
push_v3s16(L, ma.to_inv.p); // pos
lua_pushstring(L, ma.to_list.c_str()); // listname
lua_pushinteger(L, ma.to_i + 1); // index
LuaItemStack::create(L, stack); // stack
objectrefGetOrCreate(L, player); // player
PCALL_RES(lua_pcall(L, 5, 1, error_handler));
if(!lua_isnumber(L, -1))
throw LuaError("allow_metadata_inventory_put should"
" return a number, guilty node: " + nodename);
int num = luaL_checkinteger(L, -1);
lua_pop(L, 2); // Pop integer and error handler
return num;
}
// Return number of accepted items to be taken
int ScriptApiNodemeta::nodemeta_inventory_AllowTake(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// If node doesn't exist, we don't know what callback to call
MapNode node = getEnv()->getMap().getNodeNoEx(ma.from_inv.p);
if (node.getContent() == CONTENT_IGNORE)
return 0;
// Push callback function on stack
std::string nodename = ndef->get(node).name;
if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_take", &ma.from_inv.p))
return stack.count;
// Call function(pos, listname, index, count, player)
push_v3s16(L, ma.from_inv.p); // pos
lua_pushstring(L, ma.from_list.c_str()); // listname
lua_pushinteger(L, ma.from_i + 1); // index
LuaItemStack::create(L, stack); // stack
objectrefGetOrCreate(L, player); // player
PCALL_RES(lua_pcall(L, 5, 1, error_handler));
if (!lua_isnumber(L, -1))
throw LuaError("allow_metadata_inventory_take should"
" return a number, guilty node: " + nodename);
int num = luaL_checkinteger(L, -1);
lua_pop(L, 2); // Pop integer and error handler
return num;
}
// Report moved items
void ScriptApiNodemeta::nodemeta_inventory_OnMove(
const MoveAction &ma, int count,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// If node doesn't exist, we don't know what callback to call
MapNode node = getEnv()->getMap().getNodeNoEx(ma.from_inv.p);
if (node.getContent() == CONTENT_IGNORE)
return;
// Push callback function on stack
std::string nodename = ndef->get(node).name;
if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_move", &ma.from_inv.p))
return;
// function(pos, from_list, from_index, to_list, to_index, count, player)
push_v3s16(L, ma.from_inv.p); // pos
lua_pushstring(L, ma.from_list.c_str()); // from_list
lua_pushinteger(L, ma.from_i + 1); // from_index
lua_pushstring(L, ma.to_list.c_str()); // to_list
lua_pushinteger(L, ma.to_i + 1); // to_index
lua_pushinteger(L, count); // count
objectrefGetOrCreate(L, player); // player
PCALL_RES(lua_pcall(L, 7, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
// Report put items
void ScriptApiNodemeta::nodemeta_inventory_OnPut(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// If node doesn't exist, we don't know what callback to call
MapNode node = getEnv()->getMap().getNodeNoEx(ma.to_inv.p);
if (node.getContent() == CONTENT_IGNORE)
return;
// Push callback function on stack
std::string nodename = ndef->get(node).name;
if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_put", &ma.to_inv.p))
return;
// Call function(pos, listname, index, stack, player)
push_v3s16(L, ma.to_inv.p); // pos
lua_pushstring(L, ma.to_list.c_str()); // listname
lua_pushinteger(L, ma.to_i + 1); // index
LuaItemStack::create(L, stack); // stack
objectrefGetOrCreate(L, player); // player
PCALL_RES(lua_pcall(L, 5, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
// Report taken items
void ScriptApiNodemeta::nodemeta_inventory_OnTake(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
const NodeDefManager *ndef = getServer()->ndef();
// If node doesn't exist, we don't know what callback to call
MapNode node = getEnv()->getMap().getNodeNoEx(ma.from_inv.p);
if (node.getContent() == CONTENT_IGNORE)
return;
// Push callback function on stack
std::string nodename = ndef->get(node).name;
if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_take", &ma.from_inv.p))
return;
// Call function(pos, listname, index, stack, player)
push_v3s16(L, ma.from_inv.p); // pos
lua_pushstring(L, ma.from_list.c_str()); // listname
lua_pushinteger(L, ma.from_i + 1); // index
LuaItemStack::create(L, stack); // stack
objectrefGetOrCreate(L, player); // player
PCALL_RES(lua_pcall(L, 5, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
| pgimeno/minetest | src/script/cpp_api/s_nodemeta.cpp | C++ | mit | 8,121 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "cpp_api/s_base.h"
#include "cpp_api/s_item.h"
#include "irr_v3d.h"
struct MoveAction;
struct ItemStack;
class ScriptApiNodemeta
: virtual public ScriptApiBase,
public ScriptApiItem
{
public:
ScriptApiNodemeta() = default;
virtual ~ScriptApiNodemeta() = default;
// Return number of accepted items to be moved
int nodemeta_inventory_AllowMove(
const MoveAction &ma, int count,
ServerActiveObject *player);
// Return number of accepted items to be put
int nodemeta_inventory_AllowPut(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player);
// Return number of accepted items to be taken
int nodemeta_inventory_AllowTake(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player);
// Report moved items
void nodemeta_inventory_OnMove(
const MoveAction &ma, int count,
ServerActiveObject *player);
// Report put items
void nodemeta_inventory_OnPut(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player);
// Report taken items
void nodemeta_inventory_OnTake(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player);
private:
};
| pgimeno/minetest | src/script/cpp_api/s_nodemeta.h | C++ | mit | 1,966 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "cpp_api/s_player.h"
#include "cpp_api/s_internal.h"
#include "common/c_converter.h"
#include "common/c_content.h"
#include "debug.h"
#include "inventorymanager.h"
#include "lua_api/l_inventory.h"
#include "lua_api/l_item.h"
#include "util/string.h"
void ScriptApiPlayer::on_newplayer(ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_newplayers
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_newplayers");
// Call callbacks
objectrefGetOrCreate(L, player);
runCallbacks(1, RUN_CALLBACKS_MODE_FIRST);
}
void ScriptApiPlayer::on_dieplayer(ServerActiveObject *player, const PlayerHPChangeReason &reason)
{
SCRIPTAPI_PRECHECKHEADER
// Get callback table
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_dieplayers");
// Push arguments
objectrefGetOrCreate(L, player);
pushPlayerHPChangeReason(L, reason);
// Run callbacks
runCallbacks(2, RUN_CALLBACKS_MODE_FIRST);
}
bool ScriptApiPlayer::on_punchplayer(ServerActiveObject *player,
ServerActiveObject *hitter,
float time_from_last_punch,
const ToolCapabilities *toolcap,
v3f dir,
s16 damage)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_punchplayers
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_punchplayers");
// Call callbacks
objectrefGetOrCreate(L, player);
objectrefGetOrCreate(L, hitter);
lua_pushnumber(L, time_from_last_punch);
push_tool_capabilities(L, *toolcap);
push_v3f(L, dir);
lua_pushnumber(L, damage);
runCallbacks(6, RUN_CALLBACKS_MODE_OR);
return readParam<bool>(L, -1);
}
s32 ScriptApiPlayer::on_player_hpchange(ServerActiveObject *player,
s32 hp_change, const PlayerHPChangeReason &reason)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
// Get core.registered_on_player_hpchange
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_player_hpchange");
lua_remove(L, -2);
// Push arguments
objectrefGetOrCreate(L, player);
lua_pushnumber(L, hp_change);
pushPlayerHPChangeReason(L, reason);
// Call callbacks
PCALL_RES(lua_pcall(L, 3, 1, error_handler));
hp_change = lua_tointeger(L, -1);
lua_pop(L, 2); // Pop result and error handler
return hp_change;
}
bool ScriptApiPlayer::on_respawnplayer(ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_respawnplayers
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_respawnplayers");
// Call callbacks
objectrefGetOrCreate(L, player);
runCallbacks(1, RUN_CALLBACKS_MODE_OR);
return readParam<bool>(L, -1);
}
bool ScriptApiPlayer::on_prejoinplayer(
const std::string &name,
const std::string &ip,
std::string *reason)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_prejoinplayers
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_prejoinplayers");
lua_pushstring(L, name.c_str());
lua_pushstring(L, ip.c_str());
runCallbacks(2, RUN_CALLBACKS_MODE_OR);
if (lua_isstring(L, -1)) {
reason->assign(readParam<std::string>(L, -1));
return true;
}
return false;
}
bool ScriptApiPlayer::can_bypass_userlimit(const std::string &name, const std::string &ip)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_prejoinplayers
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_can_bypass_userlimit");
lua_pushstring(L, name.c_str());
lua_pushstring(L, ip.c_str());
runCallbacks(2, RUN_CALLBACKS_MODE_OR);
return lua_toboolean(L, -1);
}
void ScriptApiPlayer::on_joinplayer(ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_joinplayers
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_joinplayers");
// Call callbacks
objectrefGetOrCreate(L, player);
runCallbacks(1, RUN_CALLBACKS_MODE_FIRST);
}
void ScriptApiPlayer::on_leaveplayer(ServerActiveObject *player,
bool timeout)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_leaveplayers
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_leaveplayers");
// Call callbacks
objectrefGetOrCreate(L, player);
lua_pushboolean(L, timeout);
runCallbacks(2, RUN_CALLBACKS_MODE_FIRST);
}
void ScriptApiPlayer::on_cheat(ServerActiveObject *player,
const std::string &cheat_type)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_cheats
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_cheats");
// Call callbacks
objectrefGetOrCreate(L, player);
lua_newtable(L);
lua_pushlstring(L, cheat_type.c_str(), cheat_type.size());
lua_setfield(L, -2, "type");
runCallbacks(2, RUN_CALLBACKS_MODE_FIRST);
}
void ScriptApiPlayer::on_playerReceiveFields(ServerActiveObject *player,
const std::string &formname,
const StringMap &fields)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_player_receive_fields
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_player_receive_fields");
// Call callbacks
// param 1
objectrefGetOrCreate(L, player);
// param 2
lua_pushstring(L, formname.c_str());
// param 3
lua_newtable(L);
StringMap::const_iterator it;
for (it = fields.begin(); it != fields.end(); ++it) {
const std::string &name = it->first;
const std::string &value = it->second;
lua_pushstring(L, name.c_str());
lua_pushlstring(L, value.c_str(), value.size());
lua_settable(L, -3);
}
runCallbacks(3, RUN_CALLBACKS_MODE_OR_SC);
}
void ScriptApiPlayer::on_auth_failure(const std::string &name, const std::string &ip)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_auth_failure
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_auth_fail");
lua_pushstring(L, name.c_str());
lua_pushstring(L, ip.c_str());
runCallbacks(2, RUN_CALLBACKS_MODE_FIRST);
}
void ScriptApiPlayer::pushMoveArguments(
const MoveAction &ma, int count,
ServerActiveObject *player)
{
lua_State *L = getStack();
objectrefGetOrCreate(L, player); // player
lua_pushstring(L, "move"); // action
InvRef::create(L, ma.from_inv); // inventory
lua_newtable(L);
{
// Table containing the action information
lua_pushstring(L, ma.from_list.c_str());
lua_setfield(L, -2, "from_list");
lua_pushstring(L, ma.to_list.c_str());
lua_setfield(L, -2, "to_list");
lua_pushinteger(L, ma.from_i + 1);
lua_setfield(L, -2, "from_index");
lua_pushinteger(L, ma.to_i + 1);
lua_setfield(L, -2, "to_index");
lua_pushinteger(L, count);
lua_setfield(L, -2, "count");
}
}
void ScriptApiPlayer::pushPutTakeArguments(
const char *method, const InventoryLocation &loc,
const std::string &listname, int index, const ItemStack &stack,
ServerActiveObject *player)
{
lua_State *L = getStack();
objectrefGetOrCreate(L, player); // player
lua_pushstring(L, method); // action
InvRef::create(L, loc); // inventory
lua_newtable(L);
{
// Table containing the action information
lua_pushstring(L, listname.c_str());
lua_setfield(L, -2, "listname");
lua_pushinteger(L, index + 1);
lua_setfield(L, -2, "index");
LuaItemStack::create(L, stack);
lua_setfield(L, -2, "stack");
}
}
// Return number of accepted items to be moved
int ScriptApiPlayer::player_inventory_AllowMove(
const MoveAction &ma, int count,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_allow_player_inventory_actions");
pushMoveArguments(ma, count, player);
runCallbacks(4, RUN_CALLBACKS_MODE_OR_SC);
return lua_type(L, -1) == LUA_TNUMBER ? lua_tonumber(L, -1) : count;
}
// Return number of accepted items to be put
int ScriptApiPlayer::player_inventory_AllowPut(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_allow_player_inventory_actions");
pushPutTakeArguments("put", ma.to_inv, ma.to_list, ma.to_i, stack, player);
runCallbacks(4, RUN_CALLBACKS_MODE_OR_SC);
return lua_type(L, -1) == LUA_TNUMBER ? lua_tonumber(L, -1) : stack.count;
}
// Return number of accepted items to be taken
int ScriptApiPlayer::player_inventory_AllowTake(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_allow_player_inventory_actions");
pushPutTakeArguments("take", ma.from_inv, ma.from_list, ma.from_i, stack, player);
runCallbacks(4, RUN_CALLBACKS_MODE_OR_SC);
return lua_type(L, -1) == LUA_TNUMBER ? lua_tonumber(L, -1) : stack.count;
}
// Report moved items
void ScriptApiPlayer::player_inventory_OnMove(
const MoveAction &ma, int count,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_player_inventory_actions");
pushMoveArguments(ma, count, player);
runCallbacks(4, RUN_CALLBACKS_MODE_FIRST);
}
// Report put items
void ScriptApiPlayer::player_inventory_OnPut(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_player_inventory_actions");
pushPutTakeArguments("put", ma.to_inv, ma.to_list, ma.to_i, stack, player);
runCallbacks(4, RUN_CALLBACKS_MODE_FIRST);
}
// Report taken items
void ScriptApiPlayer::player_inventory_OnTake(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player)
{
SCRIPTAPI_PRECHECKHEADER
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_player_inventory_actions");
pushPutTakeArguments("take", ma.from_inv, ma.from_list, ma.from_i, stack, player);
runCallbacks(4, RUN_CALLBACKS_MODE_FIRST);
}
| pgimeno/minetest | src/script/cpp_api/s_player.cpp | C++ | mit | 10,334 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "cpp_api/s_base.h"
#include "irr_v3d.h"
#include "util/string.h"
struct MoveAction;
struct InventoryLocation;
struct ItemStack;
struct ToolCapabilities;
struct PlayerHPChangeReason;
class ScriptApiPlayer : virtual public ScriptApiBase
{
public:
virtual ~ScriptApiPlayer() = default;
void on_newplayer(ServerActiveObject *player);
void on_dieplayer(ServerActiveObject *player, const PlayerHPChangeReason &reason);
bool on_respawnplayer(ServerActiveObject *player);
bool on_prejoinplayer(const std::string &name, const std::string &ip,
std::string *reason);
bool can_bypass_userlimit(const std::string &name, const std::string &ip);
void on_joinplayer(ServerActiveObject *player);
void on_leaveplayer(ServerActiveObject *player, bool timeout);
void on_cheat(ServerActiveObject *player, const std::string &cheat_type);
bool on_punchplayer(ServerActiveObject *player, ServerActiveObject *hitter,
float time_from_last_punch, const ToolCapabilities *toolcap,
v3f dir, s16 damage);
s32 on_player_hpchange(ServerActiveObject *player, s32 hp_change,
const PlayerHPChangeReason &reason);
void on_playerReceiveFields(ServerActiveObject *player,
const std::string &formname, const StringMap &fields);
void on_auth_failure(const std::string &name, const std::string &ip);
// Player inventory callbacks
// Return number of accepted items to be moved
int player_inventory_AllowMove(
const MoveAction &ma, int count,
ServerActiveObject *player);
// Return number of accepted items to be put
int player_inventory_AllowPut(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player);
// Return number of accepted items to be taken
int player_inventory_AllowTake(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player);
// Report moved items
void player_inventory_OnMove(
const MoveAction &ma, int count,
ServerActiveObject *player);
// Report put items
void player_inventory_OnPut(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player);
// Report taken items
void player_inventory_OnTake(
const MoveAction &ma, const ItemStack &stack,
ServerActiveObject *player);
private:
void pushPutTakeArguments(
const char *method, const InventoryLocation &loc,
const std::string &listname, int index, const ItemStack &stack,
ServerActiveObject *player);
void pushMoveArguments(const MoveAction &ma,
int count, ServerActiveObject *player);
};
| pgimeno/minetest | src/script/cpp_api/s_player.h | C++ | mit | 3,254 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "cpp_api/s_security.h"
#include "filesys.h"
#include "porting.h"
#include "server.h"
#include "client/client.h"
#include "settings.h"
#include <cerrno>
#include <string>
#include <iostream>
#define SECURE_API(lib, name) \
lua_pushcfunction(L, sl_##lib##_##name); \
lua_setfield(L, -2, #name);
static inline void copy_safe(lua_State *L, const char *list[], unsigned len, int from=-2, int to=-1)
{
if (from < 0) from = lua_gettop(L) + from + 1;
if (to < 0) to = lua_gettop(L) + to + 1;
for (unsigned i = 0; i < (len / sizeof(list[0])); i++) {
lua_getfield(L, from, list[i]);
lua_setfield(L, to, list[i]);
}
}
// Pushes the original version of a library function on the stack, from the old version
static inline void push_original(lua_State *L, const char *lib, const char *func)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
lua_getfield(L, -1, lib);
lua_remove(L, -2); // Remove globals_backup
lua_getfield(L, -1, func);
lua_remove(L, -2); // Remove lib
}
void ScriptApiSecurity::initializeSecurity()
{
static const char *whitelist[] = {
"assert",
"core",
"collectgarbage",
"DIR_DELIM",
"error",
"getfenv",
"getmetatable",
"ipairs",
"next",
"pairs",
"pcall",
"print",
"rawequal",
"rawget",
"rawset",
"select",
"setfenv",
"setmetatable",
"tonumber",
"tostring",
"type",
"unpack",
"_VERSION",
"xpcall",
// Completely safe libraries
"coroutine",
"string",
"table",
"math",
};
static const char *io_whitelist[] = {
"close",
"flush",
"read",
"type",
"write",
};
static const char *os_whitelist[] = {
"clock",
"date",
"difftime",
"getenv",
"setlocale",
"time",
"tmpname",
};
static const char *debug_whitelist[] = {
"gethook",
"traceback",
"getinfo",
"getmetatable",
"setupvalue",
"setmetatable",
"upvalueid",
"upvaluejoin",
"sethook",
"debug",
"setlocal",
};
static const char *package_whitelist[] = {
"config",
"cpath",
"path",
"searchpath",
};
#if USE_LUAJIT
static const char *jit_whitelist[] = {
"arch",
"flush",
"off",
"on",
"opt",
"os",
"status",
"version",
"version_num",
};
#endif
m_secure = true;
lua_State *L = getStack();
// Backup globals to the registry
lua_getglobal(L, "_G");
lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
// Replace the global environment with an empty one
int thread = getThread(L);
createEmptyEnv(L);
setLuaEnv(L, thread);
// Get old globals
lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
int old_globals = lua_gettop(L);
// Copy safe base functions
lua_getglobal(L, "_G");
copy_safe(L, whitelist, sizeof(whitelist));
// And replace unsafe ones
SECURE_API(g, dofile);
SECURE_API(g, load);
SECURE_API(g, loadfile);
SECURE_API(g, loadstring);
SECURE_API(g, require);
lua_pop(L, 1);
// Copy safe IO functions
lua_getfield(L, old_globals, "io");
lua_newtable(L);
copy_safe(L, io_whitelist, sizeof(io_whitelist));
// And replace unsafe ones
SECURE_API(io, open);
SECURE_API(io, input);
SECURE_API(io, output);
SECURE_API(io, lines);
lua_setglobal(L, "io");
lua_pop(L, 1); // Pop old IO
// Copy safe OS functions
lua_getfield(L, old_globals, "os");
lua_newtable(L);
copy_safe(L, os_whitelist, sizeof(os_whitelist));
// And replace unsafe ones
SECURE_API(os, remove);
SECURE_API(os, rename);
lua_setglobal(L, "os");
lua_pop(L, 1); // Pop old OS
// Copy safe debug functions
lua_getfield(L, old_globals, "debug");
lua_newtable(L);
copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
lua_setglobal(L, "debug");
lua_pop(L, 1); // Pop old debug
// Copy safe package fields
lua_getfield(L, old_globals, "package");
lua_newtable(L);
copy_safe(L, package_whitelist, sizeof(package_whitelist));
lua_setglobal(L, "package");
lua_pop(L, 1); // Pop old package
#if USE_LUAJIT
// Copy safe jit functions, if they exist
lua_getfield(L, -1, "jit");
if (!lua_isnil(L, -1)) {
lua_newtable(L);
copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
lua_setglobal(L, "jit");
}
lua_pop(L, 1); // Pop old jit
#endif
lua_pop(L, 1); // Pop globals_backup
}
void ScriptApiSecurity::initializeSecurityClient()
{
static const char *whitelist[] = {
"assert",
"core",
"collectgarbage",
"DIR_DELIM",
"error",
"getfenv",
"ipairs",
"next",
"pairs",
"pcall",
"print",
"rawequal",
"rawget",
"rawset",
"select",
"setfenv",
"setmetatable",
"tonumber",
"tostring",
"type",
"unpack",
"_VERSION",
"xpcall",
// Completely safe libraries
"coroutine",
"string",
"table",
"math",
};
static const char *os_whitelist[] = {
"clock",
"date",
"difftime",
"time"
};
static const char *debug_whitelist[] = {
"getinfo",
};
#if USE_LUAJIT
static const char *jit_whitelist[] = {
"arch",
"flush",
"off",
"on",
"opt",
"os",
"status",
"version",
"version_num",
};
#endif
m_secure = true;
lua_State *L = getStack();
int thread = getThread(L);
// create an empty environment
createEmptyEnv(L);
// Copy safe base functions
lua_getglobal(L, "_G");
lua_getfield(L, -2, "_G");
copy_safe(L, whitelist, sizeof(whitelist));
// And replace unsafe ones
SECURE_API(g, dofile);
SECURE_API(g, load);
SECURE_API(g, loadfile);
SECURE_API(g, loadstring);
SECURE_API(g, require);
lua_pop(L, 2);
// Copy safe OS functions
lua_getglobal(L, "os");
lua_newtable(L);
copy_safe(L, os_whitelist, sizeof(os_whitelist));
lua_setfield(L, -3, "os");
lua_pop(L, 1); // Pop old OS
// Copy safe debug functions
lua_getglobal(L, "debug");
lua_newtable(L);
copy_safe(L, debug_whitelist, sizeof(debug_whitelist));
lua_setfield(L, -3, "debug");
lua_pop(L, 1); // Pop old debug
#if USE_LUAJIT
// Copy safe jit functions, if they exist
lua_getglobal(L, "jit");
lua_newtable(L);
copy_safe(L, jit_whitelist, sizeof(jit_whitelist));
lua_setfield(L, -3, "jit");
lua_pop(L, 1); // Pop old jit
#endif
// Set the environment to the one we created earlier
setLuaEnv(L, thread);
}
int ScriptApiSecurity::getThread(lua_State *L)
{
#if LUA_VERSION_NUM <= 501
int is_main = lua_pushthread(L); // Push the main thread
FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state "
"isn't the main Lua thread!");
return lua_gettop(L);
#endif
return 0;
}
void ScriptApiSecurity::createEmptyEnv(lua_State *L)
{
lua_newtable(L); // Create new environment
lua_pushvalue(L, -1);
lua_setfield(L, -2, "_G"); // Create the _G loop
}
void ScriptApiSecurity::setLuaEnv(lua_State *L, int thread)
{
#if LUA_VERSION_NUM >= 502 // Lua >= 5.2
// Set the global environment
lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);
#else // Lua <= 5.1
// Set the environment of the main thread
FATAL_ERROR_IF(!lua_setfenv(L, thread), "Security: Unable to set "
"environment of the main Lua thread!");
lua_pop(L, 1); // Pop thread
#endif
}
bool ScriptApiSecurity::isSecure(lua_State *L)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP);
bool secure = !lua_isnil(L, -1);
lua_pop(L, 1);
return secure;
}
#define CHECK_FILE_ERR(ret, fp) \
if (ret) { \
lua_pushfstring(L, "%s: %s", path, strerror(errno)); \
if (fp) std::fclose(fp); \
return false; \
}
bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char *display_name)
{
FILE *fp;
char *chunk_name;
if (!display_name)
display_name = path;
if (!path) {
fp = stdin;
chunk_name = const_cast<char *>("=stdin");
} else {
fp = fopen(path, "rb");
if (!fp) {
lua_pushfstring(L, "%s: %s", path, strerror(errno));
return false;
}
chunk_name = new char[strlen(display_name) + 2];
chunk_name[0] = '@';
chunk_name[1] = '\0';
strcat(chunk_name, display_name);
}
size_t start = 0;
int c = std::getc(fp);
if (c == '#') {
// Skip the first line
while ((c = std::getc(fp)) != EOF && c != '\n');
if (c == '\n') c = std::getc(fp);
start = std::ftell(fp);
}
if (c == LUA_SIGNATURE[0]) {
lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
std::fclose(fp);
if (path) {
delete [] chunk_name;
}
return false;
}
// Read the file
int ret = std::fseek(fp, 0, SEEK_END);
if (ret) {
lua_pushfstring(L, "%s: %s", path, strerror(errno));
std::fclose(fp);
if (path) {
delete [] chunk_name;
}
return false;
}
size_t size = std::ftell(fp) - start;
char *code = new char[size];
ret = std::fseek(fp, start, SEEK_SET);
if (ret) {
lua_pushfstring(L, "%s: %s", path, strerror(errno));
std::fclose(fp);
delete [] code;
if (path) {
delete [] chunk_name;
}
return false;
}
size_t num_read = std::fread(code, 1, size, fp);
if (path) {
std::fclose(fp);
}
if (num_read != size) {
lua_pushliteral(L, "Error reading file to load.");
delete [] code;
if (path) {
delete [] chunk_name;
}
return false;
}
if (luaL_loadbuffer(L, code, size, chunk_name)) {
delete [] code;
return false;
}
delete [] code;
if (path) {
delete [] chunk_name;
}
return true;
}
bool ScriptApiSecurity::checkPath(lua_State *L, const char *path,
bool write_required, bool *write_allowed)
{
if (write_allowed)
*write_allowed = false;
std::string str; // Transient
std::string abs_path = fs::AbsolutePath(path);
if (!abs_path.empty()) {
// Don't allow accessing the settings file
str = fs::AbsolutePath(g_settings_path);
if (str == abs_path) return false;
}
// If we couldn't find the absolute path (path doesn't exist) then
// try removing the last components until it works (to allow
// non-existent files/folders for mkdir).
std::string cur_path = path;
std::string removed;
while (abs_path.empty() && !cur_path.empty()) {
std::string component;
cur_path = fs::RemoveLastPathComponent(cur_path, &component);
if (component == "..") {
// Parent components can't be allowed or we could allow something like
// /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd.
// If we have previous non-relative elements in the path we might be
// able to remove them so that things like worlds/foo/noexist/../auth.txt
// could be allowed, but those paths will be interpreted as nonexistent
// by the operating system anyways.
return false;
}
removed.append(component).append(removed.empty() ? "" : DIR_DELIM + removed);
abs_path = fs::AbsolutePath(cur_path);
}
if (abs_path.empty())
return false;
// Add the removed parts back so that you can't, eg, create a
// directory in worldmods if worldmods doesn't exist.
if (!removed.empty())
abs_path += DIR_DELIM + removed;
// Get server from registry
lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
lua_pop(L, 1);
const IGameDef *gamedef = script->getGameDef();
if (!gamedef)
return false;
// Get mod name
lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME);
if (lua_isstring(L, -1)) {
std::string mod_name = readParam<std::string>(L, -1);
// Builtin can access anything
if (mod_name == BUILTIN_MOD_NAME) {
if (write_allowed) *write_allowed = true;
return true;
}
// Allow paths in mod path
// Don't bother if write access isn't important, since it will be handled later
if (write_required || write_allowed != NULL) {
const ModSpec *mod = gamedef->getModSpec(mod_name);
if (mod) {
str = fs::AbsolutePath(mod->path);
if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
if (write_allowed) *write_allowed = true;
return true;
}
}
}
}
lua_pop(L, 1); // Pop mod name
// Allow read-only access to all mod directories
if (!write_required) {
const std::vector<ModSpec> &mods = gamedef->getMods();
for (const ModSpec &mod : mods) {
str = fs::AbsolutePath(mod.path);
if (!str.empty() && fs::PathStartsWith(abs_path, str)) {
return true;
}
}
}
str = fs::AbsolutePath(gamedef->getWorldPath());
if (!str.empty()) {
// Don't allow access to other paths in the world mod/game path.
// These have to be blocked so you can't override a trusted mod
// by creating a mod with the same name in a world mod directory.
// We add to the absolute path of the world instead of getting
// the absolute paths directly because that won't work if they
// don't exist.
if (fs::PathStartsWith(abs_path, str + DIR_DELIM + "worldmods") ||
fs::PathStartsWith(abs_path, str + DIR_DELIM + "game")) {
return false;
}
// Allow all other paths in world path
if (fs::PathStartsWith(abs_path, str)) {
if (write_allowed) *write_allowed = true;
return true;
}
}
// Default to disallowing
return false;
}
int ScriptApiSecurity::sl_g_dofile(lua_State *L)
{
int nret = sl_g_loadfile(L);
if (nret != 1) {
lua_error(L);
// code after this function isn't executed
}
int top_precall = lua_gettop(L);
lua_call(L, 0, LUA_MULTRET);
// Return number of arguments returned by the function,
// adjusting for the function being poped.
return lua_gettop(L) - (top_precall - 1);
}
int ScriptApiSecurity::sl_g_load(lua_State *L)
{
size_t len;
const char *buf;
std::string code;
const char *chunk_name = "=(load)";
luaL_checktype(L, 1, LUA_TFUNCTION);
if (!lua_isnone(L, 2)) {
luaL_checktype(L, 2, LUA_TSTRING);
chunk_name = lua_tostring(L, 2);
}
while (true) {
lua_pushvalue(L, 1);
lua_call(L, 0, 1);
int t = lua_type(L, -1);
if (t == LUA_TNIL) {
break;
}
if (t != LUA_TSTRING) {
lua_pushnil(L);
lua_pushliteral(L, "Loader didn't return a string");
return 2;
}
buf = lua_tolstring(L, -1, &len);
code += std::string(buf, len);
lua_pop(L, 1); // Pop return value
}
if (code[0] == LUA_SIGNATURE[0]) {
lua_pushnil(L);
lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
return 2;
}
if (luaL_loadbuffer(L, code.data(), code.size(), chunk_name)) {
lua_pushnil(L);
lua_insert(L, lua_gettop(L) - 1);
return 2;
}
return 1;
}
int ScriptApiSecurity::sl_g_loadfile(lua_State *L)
{
#ifndef SERVER
lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI);
ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1);
lua_pop(L, 1);
if (script->getType() == ScriptingType::Client) {
std::string display_path = readParam<std::string>(L, 1);
const std::string *path = script->getClient()->getModFile(display_path);
if (!path) {
std::string error_msg = "Coudln't find script called:" + display_path;
lua_pushnil(L);
lua_pushstring(L, error_msg.c_str());
return 2;
}
if (!safeLoadFile(L, path->c_str(), display_path.c_str())) {
lua_pushnil(L);
lua_insert(L, -2);
return 2;
}
return 1;
}
#endif
const char *path = NULL;
if (lua_isstring(L, 1)) {
path = lua_tostring(L, 1);
CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
}
if (!safeLoadFile(L, path)) {
lua_pushnil(L);
lua_insert(L, -2);
return 2;
}
return 1;
}
int ScriptApiSecurity::sl_g_loadstring(lua_State *L)
{
const char *chunk_name = "=(load)";
luaL_checktype(L, 1, LUA_TSTRING);
if (!lua_isnone(L, 2)) {
luaL_checktype(L, 2, LUA_TSTRING);
chunk_name = lua_tostring(L, 2);
}
size_t size;
const char *code = lua_tolstring(L, 1, &size);
if (size > 0 && code[0] == LUA_SIGNATURE[0]) {
lua_pushnil(L);
lua_pushliteral(L, "Bytecode prohibited when mod security is enabled.");
return 2;
}
if (luaL_loadbuffer(L, code, size, chunk_name)) {
lua_pushnil(L);
lua_insert(L, lua_gettop(L) - 1);
return 2;
}
return 1;
}
int ScriptApiSecurity::sl_g_require(lua_State *L)
{
lua_pushliteral(L, "require() is disabled when mod security is on.");
return lua_error(L);
}
int ScriptApiSecurity::sl_io_open(lua_State *L)
{
bool with_mode = lua_gettop(L) > 1;
luaL_checktype(L, 1, LUA_TSTRING);
const char *path = lua_tostring(L, 1);
bool write_requested = false;
if (with_mode) {
luaL_checktype(L, 2, LUA_TSTRING);
const char *mode = lua_tostring(L, 2);
write_requested = strchr(mode, 'w') != NULL ||
strchr(mode, '+') != NULL ||
strchr(mode, 'a') != NULL;
}
CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL);
push_original(L, "io", "open");
lua_pushvalue(L, 1);
if (with_mode) {
lua_pushvalue(L, 2);
}
lua_call(L, with_mode ? 2 : 1, 2);
return 2;
}
int ScriptApiSecurity::sl_io_input(lua_State *L)
{
if (lua_isstring(L, 1)) {
const char *path = lua_tostring(L, 1);
CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
}
push_original(L, "io", "input");
lua_pushvalue(L, 1);
lua_call(L, 1, 1);
return 1;
}
int ScriptApiSecurity::sl_io_output(lua_State *L)
{
if (lua_isstring(L, 1)) {
const char *path = lua_tostring(L, 1);
CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
}
push_original(L, "io", "output");
lua_pushvalue(L, 1);
lua_call(L, 1, 1);
return 1;
}
int ScriptApiSecurity::sl_io_lines(lua_State *L)
{
if (lua_isstring(L, 1)) {
const char *path = lua_tostring(L, 1);
CHECK_SECURE_PATH_INTERNAL(L, path, false, NULL);
}
int top_precall = lua_gettop(L);
push_original(L, "io", "lines");
lua_pushvalue(L, 1);
lua_call(L, 1, LUA_MULTRET);
// Return number of arguments returned by the function,
// adjusting for the function being poped.
return lua_gettop(L) - top_precall;
}
int ScriptApiSecurity::sl_os_rename(lua_State *L)
{
luaL_checktype(L, 1, LUA_TSTRING);
const char *path1 = lua_tostring(L, 1);
CHECK_SECURE_PATH_INTERNAL(L, path1, true, NULL);
luaL_checktype(L, 2, LUA_TSTRING);
const char *path2 = lua_tostring(L, 2);
CHECK_SECURE_PATH_INTERNAL(L, path2, true, NULL);
push_original(L, "os", "rename");
lua_pushvalue(L, 1);
lua_pushvalue(L, 2);
lua_call(L, 2, 2);
return 2;
}
int ScriptApiSecurity::sl_os_remove(lua_State *L)
{
luaL_checktype(L, 1, LUA_TSTRING);
const char *path = lua_tostring(L, 1);
CHECK_SECURE_PATH_INTERNAL(L, path, true, NULL);
push_original(L, "os", "remove");
lua_pushvalue(L, 1);
lua_call(L, 1, 2);
return 2;
}
| pgimeno/minetest | src/script/cpp_api/s_security.cpp | C++ | mit | 18,727 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "cpp_api/s_base.h"
#define CHECK_SECURE_PATH_INTERNAL(L, path, write_required, ptr) \
if (!ScriptApiSecurity::checkPath(L, path, write_required, ptr)) { \
throw LuaError(std::string("Mod security: Blocked attempted ") + \
(write_required ? "write to " : "read from ") + path); \
}
#define CHECK_SECURE_PATH(L, path, write_required) \
if (ScriptApiSecurity::isSecure(L)) { \
CHECK_SECURE_PATH_INTERNAL(L, path, write_required, NULL); \
}
#define CHECK_SECURE_PATH_POSSIBLE_WRITE(L, path, ptr) \
if (ScriptApiSecurity::isSecure(L)) { \
CHECK_SECURE_PATH_INTERNAL(L, path, false, ptr); \
}
class ScriptApiSecurity : virtual public ScriptApiBase
{
public:
int getThread(lua_State *L);
// creates an empty Lua environment
void createEmptyEnv(lua_State *L);
// sets the enviroment to the table thats on top of the stack
void setLuaEnv(lua_State *L, int thread);
// Sets up security on the ScriptApi's Lua state
void initializeSecurity();
void initializeSecurityClient();
// Checks if the Lua state has been secured
static bool isSecure(lua_State *L);
// Loads a file as Lua code safely (doesn't allow bytecode).
static bool safeLoadFile(lua_State *L, const char *path, const char *display_name = NULL);
// Checks if mods are allowed to read (and optionally write) to the path
static bool checkPath(lua_State *L, const char *path, bool write_required,
bool *write_allowed=NULL);
private:
// Syntax: "sl_" <Library name or 'g' (global)> '_' <Function name>
// (sl stands for Secure Lua)
static int sl_g_dofile(lua_State *L);
static int sl_g_load(lua_State *L);
static int sl_g_loadfile(lua_State *L);
static int sl_g_loadstring(lua_State *L);
static int sl_g_require(lua_State *L);
static int sl_io_open(lua_State *L);
static int sl_io_input(lua_State *L);
static int sl_io_output(lua_State *L);
static int sl_io_lines(lua_State *L);
static int sl_os_rename(lua_State *L);
static int sl_os_remove(lua_State *L);
};
| pgimeno/minetest | src/script/cpp_api/s_security.h | C++ | mit | 2,769 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "cpp_api/s_server.h"
#include "cpp_api/s_internal.h"
#include "common/c_converter.h"
bool ScriptApiServer::getAuth(const std::string &playername,
std::string *dst_password,
std::set<std::string> *dst_privs)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
getAuthHandler();
lua_getfield(L, -1, "get_auth");
if (lua_type(L, -1) != LUA_TFUNCTION)
throw LuaError("Authentication handler missing get_auth");
lua_pushstring(L, playername.c_str());
PCALL_RES(lua_pcall(L, 1, 1, error_handler));
lua_remove(L, -2); // Remove auth handler
lua_remove(L, error_handler);
// nil = login not allowed
if (lua_isnil(L, -1))
return false;
luaL_checktype(L, -1, LUA_TTABLE);
std::string password;
bool found = getstringfield(L, -1, "password", password);
if (!found)
throw LuaError("Authentication handler didn't return password");
if (dst_password)
*dst_password = password;
lua_getfield(L, -1, "privileges");
if (!lua_istable(L, -1))
throw LuaError("Authentication handler didn't return privilege table");
if (dst_privs)
readPrivileges(-1, *dst_privs);
lua_pop(L, 1);
return true;
}
void ScriptApiServer::getAuthHandler()
{
lua_State *L = getStack();
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_auth_handler");
if (lua_isnil(L, -1)){
lua_pop(L, 1);
lua_getfield(L, -1, "builtin_auth_handler");
}
setOriginFromTable(-1);
lua_remove(L, -2); // Remove core
if (lua_type(L, -1) != LUA_TTABLE)
throw LuaError("Authentication handler table not valid");
}
void ScriptApiServer::readPrivileges(int index, std::set<std::string> &result)
{
lua_State *L = getStack();
result.clear();
lua_pushnil(L);
if (index < 0)
index -= 1;
while (lua_next(L, index) != 0) {
// key at index -2 and value at index -1
std::string key = luaL_checkstring(L, -2);
bool value = readParam<bool>(L, -1);
if (value)
result.insert(key);
// removes value, keeps key for next iteration
lua_pop(L, 1);
}
}
void ScriptApiServer::createAuth(const std::string &playername,
const std::string &password)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
getAuthHandler();
lua_getfield(L, -1, "create_auth");
lua_remove(L, -2); // Remove auth handler
if (lua_type(L, -1) != LUA_TFUNCTION)
throw LuaError("Authentication handler missing create_auth");
lua_pushstring(L, playername.c_str());
lua_pushstring(L, password.c_str());
PCALL_RES(lua_pcall(L, 2, 0, error_handler));
lua_pop(L, 1); // Pop error handler
}
bool ScriptApiServer::setPassword(const std::string &playername,
const std::string &password)
{
SCRIPTAPI_PRECHECKHEADER
int error_handler = PUSH_ERROR_HANDLER(L);
getAuthHandler();
lua_getfield(L, -1, "set_password");
lua_remove(L, -2); // Remove auth handler
if (lua_type(L, -1) != LUA_TFUNCTION)
throw LuaError("Authentication handler missing set_password");
lua_pushstring(L, playername.c_str());
lua_pushstring(L, password.c_str());
PCALL_RES(lua_pcall(L, 2, 1, error_handler));
lua_remove(L, error_handler);
return lua_toboolean(L, -1);
}
bool ScriptApiServer::on_chat_message(const std::string &name,
const std::string &message)
{
SCRIPTAPI_PRECHECKHEADER
// Get core.registered_on_chat_messages
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_chat_messages");
// Call callbacks
lua_pushstring(L, name.c_str());
lua_pushstring(L, message.c_str());
runCallbacks(2, RUN_CALLBACKS_MODE_OR_SC);
return readParam<bool>(L, -1);
}
void ScriptApiServer::on_mods_loaded()
{
SCRIPTAPI_PRECHECKHEADER
// Get registered shutdown hooks
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_mods_loaded");
// Call callbacks
runCallbacks(0, RUN_CALLBACKS_MODE_FIRST);
}
void ScriptApiServer::on_shutdown()
{
SCRIPTAPI_PRECHECKHEADER
// Get registered shutdown hooks
lua_getglobal(L, "core");
lua_getfield(L, -1, "registered_on_shutdown");
// Call callbacks
runCallbacks(0, RUN_CALLBACKS_MODE_FIRST);
}
| pgimeno/minetest | src/script/cpp_api/s_server.cpp | C++ | mit | 4,765 |
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#include "cpp_api/s_base.h"
#include <set>
class ScriptApiServer
: virtual public ScriptApiBase
{
public:
// Calls on_chat_message handlers
// Returns true if script handled message
bool on_chat_message(const std::string &name, const std::string &message);
// Calls when mods are loaded
void on_mods_loaded();
// Calls on_shutdown handlers
void on_shutdown();
/* auth */
bool getAuth(const std::string &playername,
std::string *dst_password,
std::set<std::string> *dst_privs);
void createAuth(const std::string &playername,
const std::string &password);
bool setPassword(const std::string &playername,
const std::string &password);
private:
void getAuthHandler();
void readPrivileges(int index, std::set<std::string> &result);
};
| pgimeno/minetest | src/script/cpp_api/s_server.h | C++ | mit | 1,560 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.