1
0
This commit is contained in:
HaoTNN 2015-06-02 16:08:57 -07:00
commit 3142598dee
235 changed files with 2505 additions and 1354 deletions

View File

@ -1,39 +1,27 @@
language: cpp
compiler: clang
compiler:
- clang
- gcc
before_install:
# - if [ "$TRAVIS_MCSERVER_BUILD_TYPE" == "COVERAGE" ]; then sudo pip install cpp_coveralls; fi
# g++4.8
- sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
- sudo apt-get update -qq
install:
# g++4.8 and clang
- sudo apt-get install -qq g++-4.8
- sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.8 90
- sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 90
# lua, needed for style checking and possibly later on for bindings generation
- sudo apt-get install -qq lua5.1
# g++4.8
- if [ "$CXX" == "g++" ]; then export CXX="g++-4.8"; export CC="gcc-4.8"; fi
# Build MCServer
script: ./CIbuild.sh
#after_success:
# - ./uploadCoverage.sh
env:
- TRAVIS_MCSERVER_BUILD_TYPE=RELEASE MCSERVER_PATH=./MCServer
- TRAVIS_MCSERVER_BUILD_TYPE=DEBUG MCSERVER_PATH=./MCServer_debug
#matrix:
# include:
# - compiler: gcc
# env: TRAVIS_MCSERVER_BUILD_TYPE=COVERAGE MCSERVER_PATH=./MCServer
# Notification Settings
notifications:
email:
on_success: change

View File

@ -3,6 +3,7 @@ Many people have contributed to MCServer, and this list attempts to broadcast at
BasedDoge (Donated AlchemistVillage prefabs)
bearbin (Alexander Harkness)
beeduck
birkett (Anthony Birkett)
derouinw
Diusrex
Duralex
@ -12,21 +13,24 @@ jasperarmstrong
keyboard
Lapayo
Luksor
linnemannr (Reid Linnemann)
M10360
marmot21
Masy98
mborland
mgueydan
MikeHunsinger
missingchar (mathias-github)
mtilden
nesco
p-mcgowan
rs2k
SafwatHalaby (Safwat Halaby)
SamJBarney
Seadragon91 (Lukas Pioch)
Sofapriester
SphinxC0re
STR_Warrior
NiLSPACE (formerly STR_Warrior)
structinf (xdot)
Sxw1212
Taugeshtu
@ -35,7 +39,7 @@ tonibm19
UltraCoderRU
WebFreak001
worktycho
xoft
xoft (Mattes Dolak/madmaxoft on GH)
Yeeeeezus (Donated AlchemistVillage prefabs)
Please add yourself to this list if you contribute to MCServer.

View File

@ -2061,6 +2061,7 @@ a_Player:OpenWindow(Window);
GetPrimaryServerVersion = { Params = "", Return = "number", Notes = "Returns the servers primary server version." },
GetProtocolVersionTextFromInt = { Params = "Protocol Version", Return = "string", Notes = "Returns the Minecraft version from the given Protocol. If there is no version found, it returns 'Unknown protocol(Parameter)'" },
GetServer = { Params = "", Return = "{{cServer|cServer}}", Notes = "Returns the cServer object." },
GetServerUpTime = { Params = "", Return = "number", Notes = "Returns the uptime of the server in seconds." },
GetTotalChunkCount = { Params = "", Return = "number", Notes = "Returns the amount of loaded chunks." },
GetVirtualRAMUsage = { Params = "", Return = "number", Notes = "Returns the amount of virtual RAM that the entire MCServer process is using, in KiB. Negative if the OS doesn't support this query." },
GetWebAdmin = { Params = "", Return = "{{cWebAdmin|cWebAdmin}}", Notes = "Returns the cWebAdmin object." },
@ -3020,7 +3021,3 @@ end
{ FileName = "WebWorldThreads.html", Title = "Webserver vs World threads" },
}
} ;

View File

@ -15,7 +15,7 @@
<ul>
<li><a href="#Introduction">Introduction</a></li>
<li><a href="#Overall">The overall structure</a></li>
<li><a href="#AdditionalInformation">AdditionalInformation table</a></li>
<li><a href="#AdditionalInfo">AdditionalInfo table</a></li>
<li><a href="#Commands">Commands table</a></li>
<li><a href="#ConsoleCommands">ConsoleCommands table</a></li>
<li><a href="#Permissions">Permissions table</a></li>
@ -51,7 +51,7 @@ g_PluginInfo =
Description = "This is an example plugin that shows how to use the Info.lua file",
-- The following members will be documented in greater detail later:
AdditionalInformation = {},
AdditionalInfo = {},
Commands = {},
ConsoleCommands = {},
Permissions = {},
@ -63,13 +63,13 @@ g_PluginInfo =
<hr />
<a name="AdditionalInformation"><h2>AdditionalInformation table</h2></a>
<a name="AdditionalInfo"><h2>AdditionalInfo table</h2></a>
<p>This table is used for more detailed description of the plugin. If there is any non-trivial setup process, dependencies, describe them here. This is where the description should get detailed. Don't worry about using several paragraphs of text here, if it makes the plugin easier to understand.</p>
<p>The table should have the following layout:</p>
<pre class="prettyprint lang-lua">
AdditionalInformation =
AdditionalInfo =
{
{
Title = "Chapter 1",

View File

@ -33,15 +33,17 @@ function HandleDumpPluginRequest(a_Request)
</tr>]]
-- Loop through each plugin that is found.
for PluginName, k in pairs(cPluginManager:Get():GetAllPlugins()) do
-- Check if there is a file called 'Info.lua' or 'info.lua'
if (cFile:Exists("Plugins/" .. PluginName .. "/Info.lua")) then
cPluginManager:Get():ForEachPlugin(
function(a_Plugin)
-- Check if there is a file called 'Info.lua'
if (cFile:Exists("Plugins/" .. a_Plugin:GetName() .. "/Info.lua")) then
Content = Content .. "\n<tr>\n"
Content = Content .. "\t<td>" .. PluginName .. "</td>\n"
Content = Content .. "\t<td><form method='POST'> <input type='hidden' value='" .. PluginName .. "' name='DumpInfo'> <input type='submit' value='DumpInfo'></form></td>\n"
Content = Content .. "\t<td>" .. a_Plugin:GetName() .. "</td>\n"
Content = Content .. "\t<td><form method='POST'> <input type='hidden' value='" .. a_Plugin:GetName() .. "' name='DumpInfo'> <input type='submit' value='DumpInfo'></form></td>\n"
Content = Content .. "</tr>\n"
end
end
)
Content = Content .. [[
</table>]]

@ -1 +1 @@
Subproject commit 493f2dfa6d39f134e37c4c614cf8d6ffd10c825f
Subproject commit 94da343b62f0498a5843247f36d6ee00cbeb8f21

View File

@ -303,7 +303,7 @@ Dispenser = Cobblestone, 1:1, 1:2, 1:3, 2:1, 3:1, 3:2, 3:3 | Redston
Dropper = Cobblestone, 1:1, 2:1, 3:1, 1:2, 1:3, 3:2, 3:3 | Hopper, 2:2 | RedstoneDust, 2:3
Repeater = Stone, 1:2, 2:2, 3:2 | RedstoneTorchOn, 1:1, 3:1 | RedstoneDust, 2:1
Comparator = RedstoneTorchOn, 2:1, 1:2, 3:2 | NetherQuartz, 2:2 | Stone, 1:3, 2:3, 3:3
DaylightSensor = Glass, 1:1, 2:1, 3:1 | NetherQuartz, 1:2, 2:2, 3:2 | Woodslab, 1:3, 2:3, 3:3
DaylightSensor = Glass, 1:1, 2:1, 3:1 | NetherQuartz, 1:2, 2:2, 3:2 | WoodenSlab^-1, 1:3, 2:3, 3:3
Hopper = IronIngot, 1:1, 3:1, 1:2, 3:2, 2:3 | Chest, 2:2
Piston = Planks^-1, 1:1, 2:1, 3:1 | RedstoneDust, 2:3 | Cobblestone, 1:2, 3:2, 1:3, 3:3 | IronIngot, 2:2
StickyPiston = Piston, * | SlimeBall, *
@ -322,7 +322,7 @@ MushroomStew = Bowl, * | BrownMushroom, * | RedMushroom, *
Bread = Wheat, 1:1, 2:1, 3:1
Sugar = Sugarcane, *
Cake = MilkBucket, 1:1, 2:1, 3:1 | Sugar, 1:2, 3:2 | Egg, 2:2 | Wheat, 1:3, 2:3, 3:3
Cookie = Wheat, *, * | CocoaBeans, *
Cookie, 8 = Wheat, *, * | CocoaBeans, *
GoldenApple = RedApple, 2:2 | GoldIngot, 1:1, 1:2, 1:3, 2:1, 2:3, 3:1, 3:2, 3:3
EnchantedGoldenApple = RedApple, 2:2 | GoldBlock, 1:1, 1:2, 1:3, 2:1, 2:3, 3:1, 3:2, 3:3
Melon = MelonSlice, 1:1, 1:2, 1:3, 2:1, 2:2, 2:3, 3:1, 3:2, 3:3

View File

@ -3,5 +3,5 @@ rem Alter this if you need to install multiple instances.
set SERVICENAME="MCServer"
set CURRENTDIR=%CD%
sc create %SERVICENAME% binPath= "%CURRENTDIR%\MCServer.exe /service" start= auto DisplayName= %SERVICENAME%
sc create %SERVICENAME% binPath= "%CURRENTDIR%\MCServer.exe -d" start= auto DisplayName= %SERVICENAME%
sc description %SERVICENAME% "Minecraft server instance"

View File

@ -815,7 +815,7 @@ rawrabbit=411
cookedrabbit=412
rabbitstew=413
rabbitsoup=413
rabbitsfood=414
rabbitsfoot=414
rabbithide=415
armorstand=416
ironhorsearmor=417

View File

@ -22,7 +22,11 @@ For Windows, you just need to download a file and extract it:
- [Windows 32 bit](http://builds.cuberite.org/job/MCServer%20Windows%20x86/lastSuccessfulBuild/artifact/Install/MCServer.zip)
- [Windows 64 bit](http://builds.cuberite.org/job/MCServer%20Windows%20x64/lastSuccessfulBuild/artifact/Install/MCServer.zip)
For other operating systems you need to download and compile yourself. There is also an archive of binary builds on the buildserver: http://builds.cuberite.org
For other operating systems you need to download and compile yourself. This can be done either manually, or with this automatic script:
bash -c "$(wget -O - https://raw.githubusercontent.com/mc-server/MCServer/master/compile.sh)"
There is also an archive of binary builds on the buildserver: http://builds.cuberite.org
Compiling the server yourself has other benefits: you may get better performance performance (1.5-3x as fast) and it supports more operating systems. See the [COMPILING.md](https://github.com/mc-server/MCServer/blob/master/COMPILING.md) file for more details.

View File

@ -18,12 +18,16 @@ endmacro()
macro(add_flags_cxx FLAGS)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLAGS}")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${FLAGS}")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${FLAGS}")
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${FLAGS}")
set(CMAKE_CXX_FLAGS_COVERAGE "${CMAKE_CXX_FLAGS_COVERAGE} ${FLAGS}")
set(CMAKE_C_FLAGS_COVERAGE "${CMAKE_C_FLAGS_COVERAGE} ${FLAGS}")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${FLAGS}")
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} ${FLAGS}")
endmacro()
#this is a hack because we can't use cmake 2.8.10 because of travis
macro(get_clang_version)
execute_process(
COMMAND "${CMAKE_CXX_COMPILER}" "--version"
OUTPUT_VARIABLE CLANG_VERSION_OUTPUT)
string(REGEX MATCH "version ([0-9]\\.[0-9])" x ${CLANG_VERSION_OUTPUT})
set(CLANG_VERSION ${CMAKE_MATCH_1})
endmacro()
@ -80,8 +84,9 @@ macro(set_flags)
else()
# Let gcc / clang know that we're compiling a multi-threaded app:
if (UNIX)
if (${UNIX})
add_flags_cxx("-pthread")
add_flags_lnk("-pthread")
endif()
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
@ -112,6 +117,10 @@ macro(set_flags)
add_flags_cxx("-march=native")
endif()
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
get_clang_version()
endif()
# Use static CRT in MSVC builds:
if (MSVC)
@ -214,15 +223,6 @@ macro(enable_profile)
endif()
endmacro()
#this is a hack because we can't use cmake 2.8.10 because of travis
macro(get_clang_version)
execute_process(
COMMAND "${CMAKE_CXX_COMPILER}" "--version"
OUTPUT_VARIABLE CLANG_VERSION_OUTPUT)
string(REGEX MATCH "version ([0-9]\\.[0-9])" x ${CLANG_VERSION_OUTPUT})
set(CLANG_VERSION ${CMAKE_MATCH_1})
endmacro()
macro(set_exe_flags)
# Remove disabling the maximum warning level:
# clang does not like a command line that reads -Wall -Wextra -w -Wall -Wextra and does not output any warnings
@ -235,29 +235,27 @@ macro(set_exe_flags)
string(REPLACE "-w" "" CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG}")
string(REPLACE "-w" "" CMAKE_CXX_FLAGS_COVERAGE "${CMAKE_CXX_FLAGS_COVERAGE}")
string(REPLACE "-w" "" CMAKE_C_FLAGS_COVERAGE "${CMAKE_C_FLAGS_COVERAGE}")
add_flags_cxx("-Wall -Wextra -Wno-unused-parameter -Wno-error=switch")
add_flags_cxx("-Wall -Wextra -Wno-unused-parameter")
# we support non-IEEE 754 fpus so can make no guarentees about error
add_flags_cxx("-ffast-math")
if(${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD")
# backtrace() and friends are in libexecinfo
add_flags_lnk("-lexecinfo")
endif()
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
get_clang_version()
if ("${CLANG_VERSION}" VERSION_LESS 3.0)
message(FATAL_ERROR "MCServer requires clang version 3.0 or higher, version is ${CLANG_VERSION}")
endif()
# clang does not provide the __extern_always_inline macro and a part of libm depends on this when using fast-math
add_flags_cxx("-D__extern_always_inline=inline")
add_flags_cxx("-Werror -Weverything -Wno-c++98-compat-pedantic -Wno-string-conversion")
add_flags_cxx("-Wno-exit-time-destructors -Wno-padded")
add_flags_cxx("-Wno-error=sign-conversion -Wno-error=conversion -Wno-error=deprecated")
add_flags_cxx("-Wno-error=missing-prototypes")
add_flags_cxx("-Wno-error=shadow -Wno-error=old-style-cast -Wno-error=global-constructors")
add_flags_cxx("-Wno-error=float-equal")
add_flags_cxx("-Wno-weak-vtables -Wno-switch-enum")
add_flags_cxx("-Weverything -Werror -Wno-c++98-compat-pedantic -Wno-string-conversion")
add_flags_cxx("-Wno-exit-time-destructors -Wno-padded -Wno-weak-vtables")
if ("${CLANG_VERSION}" VERSION_GREATER 3.0)
# flags that are not present in 3.0
add_flags_cxx("-Wno-error=covered-switch-default -Wno-error=missing-variable-declarations")
add_flags_cxx("-Wno-implicit-fallthrough -Wno-error=extra-semi")
add_flags_cxx("-Wno-implicit-fallthrough")
endif()
if ("${CLANG_VERSION}" VERSION_GREATER 3.1)
# flags introduced in 3.2
@ -271,3 +269,21 @@ macro(set_exe_flags)
endif()
endmacro()
# if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
# foreach(FILENAME ${ARGN})
# message("downgrade_warnings for ${FILENAME}")
# set_source_files_properties(${FILENAME} PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion -Wno-error=conversion")
# set_source_files_properties(${FILENAME} PROPERTIES COMPILE_FLAGS "-Wno-error=missing-prototypes -Wno-error=deprecated")
# set_source_files_properties(${FILENAME} PROPERTIES COMPILE_FLAGS "-Wno-error=shadow -Wno-error=old-style-cast -Wno-error=switch-enum -Wno-error=switch")
# set_source_files_properties(${FILENAME} PROPERTIES COMPILE_FLAGS "-Wno-error=float-equal -Wno-error=global-constructors")
# if ("${CLANG_VERSION}" VERSION_GREATER 3.0)
# # flags that are not present in 3.0
# set_source_files_properties(${FILENAME} PROPERTIES COMPILE_FLAGS "-Wno-error=covered-switch-default ")
# set_source_files_properties(${FILENAME} PROPERTIES COMPILE_FLAGS "-Wno-implicit-fallthrough -Wno-error=extra-semi")
# set_source_files_properties(${FILENAME} PROPERTIES COMPILE_FLAGS "-Wno-error=missing-variable-declarations")
# endif()
# endforeach()
# endif()

View File

@ -11,8 +11,13 @@ set_flags()
set_lib_flags()
enable_profile()
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
add_flags_cxx("-Wno-error=sign-conversion -Wno-error=conversion -Wno-error=shorten-64-to-32")
add_flags_cxx("-Wno-error=old-style-cast")
if ("${CLANG_VERSION}" VERSION_GREATER 3.5)
add_flags_cxx("-Wno-error=keyword-macro")
endif()
endif()
# Set include paths to the used libraries:
include_directories("../../lib")

View File

@ -14,7 +14,13 @@ include_directories("../../lib")
include_directories("../../lib/polarssl/include")
include_directories("../../src")
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
add_flags_cxx("-Wno-error=sign-conversion -Wno-error=conversion -Wno-error=shorten-64-to-32")
add_flags_cxx("-Wno-error=old-style-cast")
if ("${CLANG_VERSION}" VERSION_GREATER 3.5)
add_flags_cxx("-Wno-error=keyword-macro")
endif()
endif()
function(flatten_files arg1)
set(res "")

198
compile.sh Executable file
View File

@ -0,0 +1,198 @@
#|| goto :windows_detected
# Do we already have a repo?
if [[ -d .git && -f easyinstall.sh && -f MakeLuaAPI.cmd ]]; then # A good enough indicator that we're in the MCServer git repo.
cd ../
echo "MCServer repository detected. This should make the process faster, especially if you compiled before."
fi
# Error functions.
function error
{
echo
echo "-----------------"
echo "Script aborted, reason:"
echo $1
exit -1
}
function missingDepsExit
{
echo
echo "Please install the dependencies, then come back."
echo
exit -2
}
# Echo: Greetings.
echo
echo "Hello, this script will download and compile Cuberite/MCServer."
echo "On subsequent runs, it will update your MCServer."
echo "The compilation and download will occur in the current directory."
echo "If you're updating, you should run <Path to MCServer>/MCServer/compile.sh"
echo "Compiling from source takes time, but it usually generates better executables."
echo "If you prefer ready-to-use binaries or if you want more info, please visit:"
echo "http://cuberite.org/"
echo "http://mc-server.org/"
MISSING_PROGRAMS=""
# Compiler check.
GCC_EXISTS=0
CLANG_EXISTS=0
g++ --help > /dev/null 2> /dev/null && GCC_EXISTS=1
clang --help > /dev/null 2> /dev/null && CLANG_EXISTS=1
if [[ $GCC_EXISTS == 0 && $CLANG_EXISTS == 0 ]]; then
MISSING_PROGRAMS="gcc g++"
fi
# Depdendency check.
while read program; do
$program --help > /dev/null 2> /dev/null || MISSING_PROGRAMS="$MISSING_PROGRAMS $program"
done <<"EOF"
git
make
cmake
EOF
if [[ $MISSING_PROGRAMS != "" ]]; then
echo
echo "-----------------"
echo "You have missing compilation dependencies:"
echo $MISSING_PROGRAMS
echo
# apt-get guide.
apt-get --help > /dev/null 2> /dev/null && \
echo "You can install the missing depndencies via:" && \
echo -n "sudo apt-get install " && echo $MISSING_PROGRAMS && missingDepsExit
# yum guide.
yum --help > /dev/null 2> /dev/null && \
echo "You can install the missing depndencies via:" && \
echo -n "sudo yum install " && echo $MISSING_PROGRAMS && missingDepsExit
# rpm guide.
rpm --help > /dev/null 2> /dev/null && \
echo "You can install the missing depndencies via:" && \
echo -n "sudo rpm -i " && echo $MISSING_PROGRAMS && missingDepsExit
# pacman guide.
pacman --help > /dev/null 2> /dev/null && \
echo "You can install the missing depndencies via:" && \
echo -n "sudo pacman -S " && echo $MISSING_PROGRAMS && missingDepsExit
missingDepsExit
fi
# Echo: Branch choice.
echo
echo "You can choose between 2 branches:"
echo "* (S)Stable: (Coming soon) Choose the stable branch if you want the most reliable server."
echo " As of now, Stable is not yet available, please use testing instead."
echo
echo "* (T)Testing: The testing branch is less stable,"
echo " but using it and finding and reporting bugs helps us a lot!"
echo
echo "* (D)Dev: The least stable of the three. (Master branch)"
echo " Choose the development branch if you are feeling adventurous and"
echo " want to try new, bleeding edge features."
echo
# Input: Branch choice.
echo -n "Choose the branch (s/t/d): "
read BRANCH
if [[ ($BRANCH == "s") || ($BRANCH == "S" ) ]]; then
#BRANCH="stable"
error "We don't have a stable branch yet, please use testing, sorry."
elif [[ ($BRANCH == "t") || ($BRANCH == "T" ) ]]; then
BRANCH="testing"
elif [[ ($BRANCH == "d") || ($BRANCH == "D" ) ]]; then
BRANCH="master"
else
error "Unrecognized user input."
fi
# Echo: Compile mode choice.
echo
echo "Choose compile mode:"
echo "* (N)Normal: Compiles normally."
echo
echo "* (D)Debug: Compiles in debug mode. Makes your console and crashes much more verbose."
echo " But it costs performance."
echo
echo "Note that the script will connect to the internet in order to fetch code after this step."
echo "It will then compile your program."
echo
# Input: Compile mode choice.
echo -n "Choose compile mode: (n/d): "
read BUILDTYPE
if [[ ($BUILDTYPE == "d") || ($BUILDTYPE == "D") ]]; then
BUILDTYPE="Debug"
elif [[ ($BUILDTYPE == "n") || ($BUILDTYPE == "N") ]]; then
BUILDTYPE="Release"
else
error "Unrecognized user input."
fi
# Echo: Downloading began.
echo
echo " --- Downloading MCServer's source code from the $BRANCH branch..."
# Git: Clone.
if [ ! -d MCServer ]; then
echo " --- Looks like your first run, cloning the whole code..."
git clone https://github.com/mc-server/MCServer.git
fi
# Git: Fetch.
pushd MCServer
echo " --- Updating the $BRANCH branch..."
git fetch origin $BRANCH || error "git fetch failed"
git checkout $BRANCH || error "git checkout failed"
git merge origin/$BRANCH || error "git merge failed"
# Git: Submodules.
echo " --- Updating submodules..."
git submodule init
git submodule update
# Cmake.
echo " --- Running cmake..."
popd
if [ ! -d build-mcserver ]; then mkdir build-mcserver; fi
pushd build-mcserver
cmake ../MCServer/ -DCMAKE_BUILD_TYPE=$BUILDTYPE || error "cmake failed"
# Make.
echo " --- Compiling..."
make -j`nproc` || error "Compiling failed"
echo
# Echo: Compilation complete.
popd
pushd MCServer/MCServer
echo
echo "-----------------"
echo "Compilation done!"
echo
echo "Cuberite awaits you at:"
echo "`pwd`/MCServer"
echo
echo "Enjoy :)"
popd
exit 0
:windows_detected
echo "This script is not available for Windows yet, sorry."
echo "You can still download the Windows binaries from: http://mc-server.org"

View File

@ -25,7 +25,7 @@ endif()
# FreeBSD requires us to define this to get POSIX 2001 standard
if (${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD")
add_flags_cxx(-D__POSIX_VISIBLE=200112)
add_flags_cxx("-D_XOPEN_SOURCE=600")
endif()
add_library(sqlite ${SOURCE})

View File

@ -53,4 +53,8 @@ if(UNIX)
target_link_libraries(tolua m ${DYNAMIC_LOADER})
endif()
if (${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD")
add_flags_lnk(-L/usr/local/lib)
endif()
target_link_libraries(tolua tolualib lua)

View File

@ -39,8 +39,8 @@ class cListAllocationPool : public cAllocationPool<T>
{
public:
cListAllocationPool(std::auto_ptr<typename cAllocationPool<T>::cStarvationCallbacks> a_Callbacks) :
m_Callbacks(a_Callbacks)
cListAllocationPool(std::unique_ptr<typename cAllocationPool<T>::cStarvationCallbacks> a_Callbacks) :
m_Callbacks(std::move(a_Callbacks))
{
for (size_t i = 0; i < NumElementsInReserve; i++)
{
@ -105,7 +105,7 @@ class cListAllocationPool : public cAllocationPool<T>
private:
std::list<void *> m_FreeList;
std::auto_ptr<typename cAllocationPool<T>::cStarvationCallbacks> m_Callbacks;
std::unique_ptr<typename cAllocationPool<T>::cStarvationCallbacks> m_Callbacks;
};

View File

@ -101,7 +101,7 @@ local function OutputLuaStateHelpers(a_Package)
f:write("void Push(" .. item.name .. " * a_Value);\n")
end
for _, item in ipairs(types) do
f:write("void GetStackValue(int a_StackPos, Ptr" .. item.lname .. " & a_ReturnedVal);\n")
f:write("bool GetStackValue(int a_StackPos, Ptr" .. item.lname .. " & a_ReturnedVal);\n")
end
f:write("\n\n\n\n\n")
f:close()
@ -125,15 +125,17 @@ local function OutputLuaStateHelpers(a_Package)
end
end
for _, item in ipairs(types) do
f:write("void cLuaState::GetStackValue(int a_StackPos, Ptr" .. item.lname .. " & a_ReturnedVal)\n{\n\tASSERT(IsValid());\n")
f:write("bool cLuaState::GetStackValue(int a_StackPos, Ptr" .. item.lname .. " & a_ReturnedVal)\n{\n\tASSERT(IsValid());\n")
f:write("\tif (lua_isnil(m_LuaState, a_StackPos))\n\t{\n")
f:write("\t a_ReturnedVal = nullptr;\n")
f:write("\t return;\n\t}\n")
f:write("\t\ta_ReturnedVal = nullptr;\n")
f:write("\t\treturn false;\n\t}\n")
f:write("\ttolua_Error err;\n")
f:write("\tif (tolua_isusertype(m_LuaState, a_StackPos, \"" .. item.name .. "\", false, &err))\n")
f:write("\t{\n")
f:write("\t a_ReturnedVal = *(reinterpret_cast<" .. item.name .. " **>(lua_touserdata(m_LuaState, a_StackPos)));\n")
f:write("\t\ta_ReturnedVal = *(reinterpret_cast<" .. item.name .. " **>(lua_touserdata(m_LuaState, a_StackPos)));\n")
f:write("\t\treturn true;\n");
f:write("\t}\n")
f:write("\treturn false;\n")
f:write("}\n\n\n\n\n\n")
end
f:close()

View File

@ -145,6 +145,15 @@ set_source_files_properties(${BINDING_OUTPUTS} PROPERTIES GENERATED TRUE)
set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/Bindings.cpp PROPERTIES COMPILE_FLAGS -Wno-error)
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
set_source_files_properties(DeprecatedBindings.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(LuaState.cpp COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(LuaWindow.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=switch-enum")
set_source_files_properties(ManualBindings.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(ManualBindings_World.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(PluginLua.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
endif()
if(NOT MSVC)
add_library(Bindings ${SRCS} ${HDRS})

View File

@ -41,7 +41,7 @@ bool cLuaChunkStay::AddChunks(int a_ChunkCoordTableStackPos)
// Add each set of coords:
int NumChunks = luaL_getn(L, a_ChunkCoordTableStackPos);
m_Chunks.reserve((size_t)NumChunks);
m_Chunks.reserve(static_cast<size_t>(NumChunks));
for (int idx = 1; idx <= NumChunks; idx++)
{
// Push the idx-th element of the array onto stack top, check that it's a table:
@ -133,7 +133,7 @@ void cLuaChunkStay::OnChunkAvailable(int a_ChunkX, int a_ChunkZ)
if (m_OnChunkAvailable.IsValid())
{
cPluginLua::cOperation Op(m_Plugin);
Op().Call((int)m_OnChunkAvailable, a_ChunkX, a_ChunkZ);
Op().Call(static_cast<int>(m_OnChunkAvailable), a_ChunkX, a_ChunkZ);
}
}
@ -147,7 +147,7 @@ bool cLuaChunkStay::OnAllChunksAvailable(void)
{
// Call the callback:
cPluginLua::cOperation Op(m_Plugin);
Op().Call((int)m_OnAllChunksAvailable);
Op().Call(static_cast<int>(m_OnAllChunksAvailable));
// Remove the callback references - they won't be needed anymore
m_OnChunkAvailable.UnRef();

View File

@ -701,108 +701,95 @@ void cLuaState::PushUserType(void * a_Object, const char * a_Type)
void cLuaState::GetStackValue(int a_StackPos, AString & a_Value)
bool cLuaState::GetStackValue(int a_StackPos, AString & a_Value)
{
size_t len = 0;
const char * data = lua_tolstring(m_LuaState, a_StackPos, &len);
if (data != nullptr)
{
a_Value.assign(data, len);
return true;
}
return false;
}
void cLuaState::GetStackValue(int a_StackPos, BLOCKTYPE & a_ReturnedVal)
{
if (lua_isnumber(m_LuaState, a_StackPos))
{
a_ReturnedVal = static_cast<BLOCKTYPE>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal));
}
}
void cLuaState::GetStackValue(int a_StackPos, bool & a_ReturnedVal)
bool cLuaState::GetStackValue(int a_StackPos, bool & a_ReturnedVal)
{
a_ReturnedVal = (tolua_toboolean(m_LuaState, a_StackPos, a_ReturnedVal ? 1 : 0) > 0);
return true;
}
void cLuaState::GetStackValue(int a_StackPos, cPluginManager::CommandResult & a_Result)
bool cLuaState::GetStackValue(int a_StackPos, cPluginManager::CommandResult & a_Result)
{
if (lua_isnumber(m_LuaState, a_StackPos))
{
a_Result = static_cast<cPluginManager::CommandResult>(static_cast<int>((tolua_tonumber(m_LuaState, a_StackPos, a_Result))));
return true;
}
return false;
}
void cLuaState::GetStackValue(int a_StackPos, cRef & a_Ref)
bool cLuaState::GetStackValue(int a_StackPos, cRef & a_Ref)
{
a_Ref.RefStack(*this, a_StackPos);
return true;
}
void cLuaState::GetStackValue(int a_StackPos, double & a_ReturnedVal)
bool cLuaState::GetStackValue(int a_StackPos, double & a_ReturnedVal)
{
if (lua_isnumber(m_LuaState, a_StackPos))
{
a_ReturnedVal = tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal);
return true;
}
return false;
}
void cLuaState::GetStackValue(int a_StackPos, float & a_ReturnedVal)
bool cLuaState::GetStackValue(int a_StackPos, float & a_ReturnedVal)
{
if (lua_isnumber(m_LuaState, a_StackPos))
{
a_ReturnedVal = static_cast<float>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal));
return true;
}
return false;
}
void cLuaState::GetStackValue(int a_StackPos, eWeather & a_ReturnedVal)
bool cLuaState::GetStackValue(int a_StackPos, eWeather & a_ReturnedVal)
{
if (!lua_isnumber(m_LuaState, a_StackPos))
{
return;
return false;
}
a_ReturnedVal = static_cast<eWeather>(Clamp(
static_cast<int>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal)),
static_cast<int>(wSunny), static_cast<int>(wThunderstorm))
);
}
void cLuaState::GetStackValue(int a_StackPos, int & a_ReturnedVal)
{
if (lua_isnumber(m_LuaState, a_StackPos))
{
a_ReturnedVal = static_cast<int>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal));
}
return true;
}

View File

@ -187,16 +187,37 @@ public:
void Push(cLuaUDPEndpoint * a_UDPEndpoint);
// GetStackValue() retrieves the value at a_StackPos, if it is a valid type. If not, a_Value is unchanged.
// Returns whether value was changed
// Enum values are clamped to their allowed range.
void GetStackValue(int a_StackPos, AString & a_Value);
void GetStackValue(int a_StackPos, BLOCKTYPE & a_Value);
void GetStackValue(int a_StackPos, bool & a_Value);
void GetStackValue(int a_StackPos, cPluginManager::CommandResult & a_Result);
void GetStackValue(int a_StackPos, cRef & a_Ref);
void GetStackValue(int a_StackPos, double & a_Value);
void GetStackValue(int a_StackPos, eWeather & a_Value);
void GetStackValue(int a_StackPos, float & a_ReturnedVal);
void GetStackValue(int a_StackPos, int & a_Value);
bool GetStackValue(int a_StackPos, AString & a_Value);
bool GetStackValue(int a_StackPos, bool & a_Value);
bool GetStackValue(int a_StackPos, cPluginManager::CommandResult & a_Result);
bool GetStackValue(int a_StackPos, cRef & a_Ref);
bool GetStackValue(int a_StackPos, double & a_Value);
bool GetStackValue(int a_StackPos, eWeather & a_Value);
bool GetStackValue(int a_StackPos, float & a_ReturnedVal);
// template to catch all of the various c++ integral types without overload conflicts
template <class T>
bool GetStackValue(int a_StackPos, T & a_ReturnedVal, typename std::enable_if<std::is_integral<T>::value>::type * unused = nullptr)
{
UNUSED(unused);
if (lua_isnumber(m_LuaState, a_StackPos))
{
lua_Number Val = tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal);
if (Val > std::numeric_limits<T>::max())
{
return false;
}
if (Val < std::numeric_limits<T>::min())
{
return false;
}
a_ReturnedVal = static_cast<T>(Val);
return true;
}
return false;
}
// Include the auto-generated Push and GetStackValue() functions:
#include "LuaState_Declaration.inc"
@ -218,10 +239,13 @@ public:
/** Retrieves a list of values from the Lua stack, starting at the specified index. */
template <typename T, typename... Args>
inline void GetStackValues(int a_StartStackPos, T & a_Ret, Args &&... args)
inline bool GetStackValues(int a_StartStackPos, T & a_Ret, Args &&... args)
{
GetStackValue(a_StartStackPos, a_Ret);
GetStackValues(a_StartStackPos + 1, args...);
if (!GetStackValue(a_StartStackPos, a_Ret))
{
return false;
}
return GetStackValues(a_StartStackPos + 1, args...);
}
/** Returns true if the specified parameters on the stack are of the specified usertable type; also logs warning if not. Used for static functions */
@ -349,9 +373,9 @@ protected:
/** Variadic template terminator: If there are no more values to get, bail out.
This function is not available in the public API, because it's an error to request no values directly; only internal functions can do that.
If you get a compile error saying this function is not accessible, check your calling code, you aren't reading any stack values. */
void GetStackValues(int a_StartingStackPos)
bool GetStackValues(int a_StartingStackPos)
{
// Do nothing
return true;
}
/** Pushes the function of the specified name onto the stack.
@ -369,7 +393,7 @@ protected:
*/
bool PushFunction(const cRef & a_FnRef)
{
return PushFunction((int)a_FnRef);
return PushFunction(static_cast<int>(a_FnRef));
}
/** Pushes a function that is stored in a referenced table by name

View File

@ -158,7 +158,7 @@ static int tolua_UncompressStringZLIB(lua_State * tolua_S)
// Get the params:
AString ToUncompress;
int UncompressedSize;
size_t UncompressedSize;
S.GetStackValues(1, ToUncompress, UncompressedSize);
// Compress the string:
@ -1801,7 +1801,7 @@ static int tolua_cMojangAPI_GetUUIDsFromPlayerNames(lua_State * L)
// Convert the input table into AStringVector:
AStringVector PlayerNames;
int NumNames = luaL_getn(L, 2);
PlayerNames.reserve(NumNames);
PlayerNames.reserve(static_cast<size_t>(NumNames));
for (int i = 1; i <= NumNames; i++)
{
lua_rawgeti(L, 2, i);

View File

@ -199,7 +199,7 @@ public:
// Get parameters:
Ty1 * Self = nullptr;
int ItemID;
UInt32 ItemID;
cLuaState::cRef FnRef;
L.GetStackValues(1, Self, ItemID, FnRef);
if (Self == nullptr)
@ -253,8 +253,9 @@ public:
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamNumber(2, 5) ||
!L.CheckParamFunction(6)
!L.CheckParamNumber(2, 4) ||
!L.CheckParamFunction(5) ||
!L.CheckParamEnd(6)
)
{
return 0;
@ -316,8 +317,9 @@ public:
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamNumber(2, 4) ||
!L.CheckParamFunction(5)
!L.CheckParamNumber(2, 3) ||
!L.CheckParamFunction(4) ||
!L.CheckParamEnd(5)
)
{
return 0;

View File

@ -101,13 +101,12 @@ static int tolua_cNetwork_CreateUDPEndpoint(lua_State * L)
}
// Read the params:
int Port;
S.GetStackValues(2, Port);
UInt16 Port;
// Check validity:
if ((Port < 0) || (Port > 65535))
if (!S.GetStackValues(2, Port))
{
LOGWARNING("cNetwork:CreateUDPEndpoint() called with invalid port (%d), failing the request.", Port);
LOGWARNING("cNetwork:CreateUDPEndpoint() called with invalid port, failing the request.");
S.Push(false);
return 1;
}

View File

@ -50,7 +50,7 @@ static int tolua_cWorld_BroadcastParticleEffect(lua_State * tolua_S)
std::array<int, 2> data;
for (int i = 0; (i < 2) && L.IsParamNumber(11 + i); i++)
{
L.GetStackValue(11 + i, data[i]);
L.GetStackValue(11 + i, data[static_cast<size_t>(i)]);
}
World->GetBroadcaster().BroadcastParticleEffect(Name, Vector3f(PosX, PosY, PosZ), Vector3f(OffX, OffY, OffZ), ParticleData, ParticleAmmount, ExcludeClient);
@ -303,10 +303,9 @@ static int tolua_cWorld_PrepareChunk(lua_State * tolua_S)
cLuaState m_LuaState;
cLuaState::cRef m_Callback;
};
cCallback * callback = new cCallback(tolua_S);
// Call the chunk preparation:
world->PrepareChunk(chunkX, chunkZ, callback);
world->PrepareChunk(chunkX, chunkZ, cpp14::make_unique<cCallback>(tolua_S));
return 0;
}

View File

@ -629,11 +629,6 @@ bool cPluginLua::OnExploded(cWorld & a_World, double a_ExplosionSize, bool a_Can
case esWitherSkullBlue: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break;
case esWitherBirth: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break;
case esPlugin: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break;
default:
{
ASSERT(!"Unhandled ExplosionSource");
return false;
}
}
if (res)
{
@ -670,11 +665,6 @@ bool cPluginLua::OnExploding(cWorld & a_World, double & a_ExplosionSize, bool &
case esWitherSkullBlue: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res, a_CanCauseFire, a_ExplosionSize); break;
case esWitherBirth: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res, a_CanCauseFire, a_ExplosionSize); break;
case esPlugin: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res, a_CanCauseFire, a_ExplosionSize); break;
default:
{
ASSERT(!"Unhandled ExplosionSource");
return false;
}
}
if (res)
{

View File

@ -1935,7 +1935,7 @@ size_t cPluginManager::GetNumLoadedPlugins(void) const
AStringVector cPluginManager::GetFoldersToLoad(cSettingsRepositoryInterface & a_Settings)
{
// Check if the Plugins section exists.
if (a_Settings.KeyExists("Plugins"))
if (!a_Settings.KeyExists("Plugins"))
{
InsertDefaultPlugins(a_Settings);
}

View File

@ -98,11 +98,11 @@ EMCSBiome StringToBiome(const AString & a_BiomeString)
{
if ((res >= biFirstBiome) && (res < biNumBiomes))
{
return (EMCSBiome)res;
return static_cast<EMCSBiome>(res);
}
else if ((res >= biFirstVariantBiome) && (res < biNumVariantBiomes))
{
return (EMCSBiome)res;
return static_cast<EMCSBiome>(res);
}
// It was an invalid number
return biInvalidBiome;

View File

@ -60,7 +60,7 @@ void InternalMergeBlocks(
else
{
NIBBLETYPE FakeDestMeta = 0;
Combinator(a_DstTypes[DstIdx], a_SrcTypes[SrcIdx], FakeDestMeta, (NIBBLETYPE)0);
Combinator(a_DstTypes[DstIdx], a_SrcTypes[SrcIdx], FakeDestMeta, static_cast<NIBBLETYPE>(0));
}
++DstIdx;
++SrcIdx;
@ -620,7 +620,7 @@ void cBlockArea::DumpToRawFile(const AString & a_FileName)
f.Write(&SizeX, 4);
f.Write(&SizeY, 4);
f.Write(&SizeZ, 4);
unsigned char DataTypes = (unsigned char)GetDataTypes();
unsigned char DataTypes = static_cast<unsigned char>(GetDataTypes());
f.Write(&DataTypes, 1);
size_t NumBlocks = GetBlockCount();
if (HasBlockTypes())
@ -2157,7 +2157,7 @@ void cBlockArea::ExpandBlockTypes(int a_SubMinX, int a_AddMaxX, int a_SubMinY, i
int NewSizeX = m_Size.x + a_SubMinX + a_AddMaxX;
int NewSizeY = m_Size.y + a_SubMinY + a_AddMaxY;
int NewSizeZ = m_Size.z + a_SubMinZ + a_AddMaxZ;
size_t BlockCount = (size_t)(NewSizeX * NewSizeY * NewSizeZ);
size_t BlockCount = static_cast<size_t>(NewSizeX * NewSizeY * NewSizeZ);
BLOCKTYPE * NewBlockTypes = new BLOCKTYPE[BlockCount];
memset(NewBlockTypes, 0, BlockCount * sizeof(BLOCKTYPE));
int OldIndex = 0;
@ -2187,7 +2187,7 @@ void cBlockArea::ExpandNibbles(NIBBLEARRAY & a_Array, int a_SubMinX, int a_AddMa
int NewSizeX = m_Size.x + a_SubMinX + a_AddMaxX;
int NewSizeY = m_Size.y + a_SubMinY + a_AddMaxY;
int NewSizeZ = m_Size.z + a_SubMinZ + a_AddMaxZ;
size_t BlockCount = (size_t)(NewSizeX * NewSizeY * NewSizeZ);
size_t BlockCount = static_cast<size_t>(NewSizeX * NewSizeY * NewSizeZ);
NIBBLETYPE * NewNibbles = new NIBBLETYPE[BlockCount];
memset(NewNibbles, 0, BlockCount * sizeof(NIBBLETYPE));
int OldIndex = 0;

View File

@ -321,7 +321,7 @@ public:
NIBBLETYPE * GetBlockMetas (void) const { return m_BlockMetas; } // NOTE: one byte per block!
NIBBLETYPE * GetBlockLight (void) const { return m_BlockLight; } // NOTE: one byte per block!
NIBBLETYPE * GetBlockSkyLight(void) const { return m_BlockSkyLight; } // NOTE: one byte per block!
size_t GetBlockCount(void) const { return (size_t)(m_Size.x * m_Size.y * m_Size.z); }
size_t GetBlockCount(void) const { return static_cast<size_t>(m_Size.x * m_Size.y * m_Size.z); }
int MakeIndex(int a_RelX, int a_RelY, int a_RelZ) const;
protected:

View File

@ -77,7 +77,7 @@ bool cBeaconEntity::IsValidEffect(cEntityEffect::eType a_Effect, char a_BeaconLe
default:
{
LOGD("%s: Invalid beacon effect: %d", __FUNCTION__, (int)a_Effect);
LOGD("%s: Invalid beacon effect: %d", __FUNCTION__, static_cast<int>(a_Effect));
return false;
}
}
@ -228,9 +228,9 @@ void cBeaconEntity::GiveEffects(void)
virtual bool Item(cPlayer * a_Player)
{
Vector3d PlayerPosition = Vector3d(a_Player->GetPosition());
if (PlayerPosition.y > (double)m_PosY)
if (PlayerPosition.y > static_cast<double>(m_PosY))
{
PlayerPosition.y = (double)m_PosY;
PlayerPosition.y = static_cast<double>(m_PosY);
}
// TODO: Vanilla minecraft uses an AABB check instead of a radius one

View File

@ -41,6 +41,11 @@ SET (HDRS
NoteEntity.h
SignEntity.h)
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
set_source_files_properties(BeaconEntity.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=conversion -Wno-error=switch-enum")
set_source_files_properties(NoteEntity.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=conversion -Wno-error=sign-conversion")
endif()
if(NOT MSVC)
add_library(BlockEntities ${SRCS} ${HDRS})
endif()

View File

@ -145,9 +145,9 @@ void cMobSpawnerEntity::SpawnEntity(void)
break;
}
int RelX = (int) (m_RelX + (double)(Random.NextFloat() - Random.NextFloat()) * 4.0);
int RelX = static_cast<int>(m_RelX + static_cast<double>(Random.NextFloat() - Random.NextFloat()) * 4.0);
int RelY = m_RelY + Random.NextInt(3) - 1;
int RelZ = (int) (m_RelZ + (double)(Random.NextFloat() - Random.NextFloat()) * 4.0);
int RelZ = static_cast<int>(m_RelZ + static_cast<double>(Random.NextFloat() - Random.NextFloat()) * 4.0);
cChunk * Chunk = a_Chunk->GetRelNeighborChunkAdjustCoords(RelX, RelZ);
if ((Chunk == nullptr) || !Chunk->IsValid())
@ -172,7 +172,13 @@ void cMobSpawnerEntity::SpawnEntity(void)
if (Chunk->GetWorld()->SpawnMobFinalize(Monster) != cEntity::INVALID_ID)
{
EntitiesSpawned = true;
Chunk->BroadcastSoundParticleEffect(2004, (int)(PosX * 8.0), (int)(RelY * 8.0), (int)(PosZ * 8.0), 0);
Chunk->BroadcastSoundParticleEffect(
2004,
static_cast<int>(PosX * 8.0),
static_cast<int>(RelY * 8.0),
static_cast<int>(PosZ * 8.0),
0
);
m_NearbyEntitiesNum++;
}
}
@ -246,9 +252,9 @@ int cMobSpawnerEntity::GetNearbyMonsterNum(eMonsterType a_EntityType)
class cCallback : public cChunkDataCallback
{
public:
cCallback(Vector3d a_SpawnerPos, eMonsterType a_EntityType, int & a_NumEntities) :
cCallback(Vector3d a_SpawnerPos, eMonsterType a_CallbackEntityType, int & a_NumEntities) :
m_SpawnerPos(a_SpawnerPos),
m_EntityType(a_EntityType),
m_EntityType(a_CallbackEntityType),
m_NumEntities(a_NumEntities)
{
}
@ -260,7 +266,7 @@ int cMobSpawnerEntity::GetNearbyMonsterNum(eMonsterType a_EntityType)
return;
}
cMonster * Mob = (cMonster *)a_Entity;
cMonster * Mob = static_cast<cMonster *>(a_Entity);
if (Mob->GetMobType() != m_EntityType)
{
return;

View File

@ -90,8 +90,15 @@ void cNoteEntity::MakeSound(void)
m_World->BroadcastBlockAction(m_PosX, m_PosY, m_PosZ, instrument, m_Pitch, E_BLOCK_NOTE_BLOCK);
// TODO: instead of calculating the power function over and over, make a precalculated table - there's only 24 pitches after all
float calcPitch = pow(2.0f, ((float)m_Pitch - 12.0f) / 12.0f);
m_World->BroadcastSoundEffect(sampleName, (double)m_PosX, (double)m_PosY, (double)m_PosZ, 3.0f, calcPitch);
float calcPitch = pow(2.0f, static_cast<float>(m_Pitch - 12.0f) / 12.0f);
m_World->BroadcastSoundEffect(
sampleName,
static_cast<double>(m_PosX),
static_cast<double>(m_PosY),
static_cast<double>(m_PosZ),
3.0f,
calcPitch
);
}

View File

@ -96,8 +96,7 @@ public:
else
{
// Not a resolvable string, try pure numbers: "45:6", "45^6" etc.
a_Item.m_ItemType = (short)atoi(Split[0].c_str());
if ((a_Item.m_ItemType == 0) && (Split[0] != "0"))
if (!StringToInteger(Split[0], a_Item.m_ItemType))
{
// Parsing the number failed
return false;
@ -112,8 +111,7 @@ public:
return true;
}
a_Item.m_ItemDamage = (short)atoi(Split[1].c_str());
if ((a_Item.m_ItemDamage == 0) && (Split[1] != "0"))
if (!StringToInteger(Split[1], a_Item.m_ItemDamage))
{
// Parsing the number failed
return false;
@ -175,8 +173,16 @@ protected:
{
return;
}
short ItemType = (short)atoi(Split[0].c_str());
short ItemDamage = (Split.size() > 1) ? (short)atoi(Split[1].c_str()) : -1;
short ItemType;
if (!StringToInteger(Split[0], ItemType))
{
ASSERT(!"Invalid item type");
}
short ItemDamage = -1;
if (Split.size() > 1 && !StringToInteger(Split[1], ItemDamage))
{
ASSERT(!"Invalid item damage");
}
m_Map[a_Name] = std::make_pair(ItemType, ItemDamage);
}
} ;
@ -288,11 +294,11 @@ AString ItemToFullString(const cItem & a_Item)
eDimension StringToDimension(const AString & a_DimensionString)
{
// First try decoding as a number
int res = atoi(a_DimensionString.c_str());
if ((res != 0) || (a_DimensionString == "0"))
int res;
if (StringToInteger(a_DimensionString, res))
{
// It was a valid number
return (eDimension)res;
return static_cast<eDimension>(res);
}
// Decode using a built-in map:
@ -350,7 +356,7 @@ AString DimensionToString(eDimension a_Dimension)
} // for i - DimensionMap[]
// Not found
LOGWARNING("Unknown dimension: \"%i\". Setting to Overworld", (int)a_Dimension);
LOGWARNING("Unknown dimension: \"%i\". Setting to Overworld", static_cast<int>(a_Dimension));
return "Overworld";
}
@ -386,7 +392,7 @@ AString DamageTypeToString(eDamageType a_DamageType)
// Unknown damage type:
ASSERT(!"Unknown DamageType");
return Printf("dtUnknown_%d", (int)a_DamageType);
return Printf("dtUnknown_%d", static_cast<int>(a_DamageType));
}
@ -397,11 +403,11 @@ AString DamageTypeToString(eDamageType a_DamageType)
eDamageType StringToDamageType(const AString & a_DamageTypeString)
{
// First try decoding as a number:
int res = atoi(a_DamageTypeString.c_str());
if ((res != 0) || (a_DamageTypeString == "0"))
int res;
if (!StringToInteger(a_DamageTypeString, res))
{
// It was a valid number
return (eDamageType)res;
return static_cast<eDamageType>(res);
}
// Decode using a built-in map:
@ -462,7 +468,7 @@ eDamageType StringToDamageType(const AString & a_DamageTypeString)
} // for i - DamageTypeMap[]
// Not found:
return (eDamageType)-1;
return static_cast<eDamageType>(-1);
}

View File

@ -19,7 +19,7 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info)
{
if (a_Info[i].m_Handler == nullptr)
{
a_Info[i].m_Handler = cBlockHandler::CreateBlockHandler((BLOCKTYPE) i);
a_Info[i].m_Handler = cBlockHandler::CreateBlockHandler(static_cast<BLOCKTYPE>(i));
}
}

View File

@ -46,10 +46,10 @@ public:
switch (Direction)
{
case 0: a_BlockMeta = 0x2 | Meta << 2; break;
case 1: a_BlockMeta = 0x3 | Meta << 2; break;
case 2: a_BlockMeta = 0x0 | Meta << 2; break;
case 3: a_BlockMeta = 0x1 | Meta << 2; break;
case 0: a_BlockMeta = static_cast<NIBBLETYPE>(0x2 | Meta << 2); break;
case 1: a_BlockMeta = static_cast<NIBBLETYPE>(0x3 | Meta << 2); break;
case 2: a_BlockMeta = static_cast<NIBBLETYPE>(0x0 | Meta << 2); break;
case 3: a_BlockMeta = static_cast<NIBBLETYPE>(0x1 | Meta << 2); break;
default:
{
return false;

View File

@ -53,7 +53,7 @@ public:
a_Rotation = (a_Rotation / 360) * 4;
return ((char)a_Rotation + 2) % 4;
return (static_cast<NIBBLETYPE>(a_Rotation + 2)) % 4;
}
static Vector3i MetaDataToDirection(NIBBLETYPE a_MetaData)

View File

@ -67,14 +67,19 @@ public:
case BLOCK_FACE_XM: return 0x2;
case BLOCK_FACE_XP: return 0x1;
case BLOCK_FACE_YM: return 0x0;
default:
case BLOCK_FACE_NONE:
{
ASSERT(!"Unhandled block face!");
return 0x0;
}
}
#if !defined(__clang__)
ASSERT(!"Unknown BLOCK_FACE");
return 0;
#endif
}
inline static eBlockFace BlockMetaDataToBlockFace(NIBBLETYPE a_Meta)
{
switch (a_Meta & 0x7)
@ -93,6 +98,7 @@ public:
}
}
virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override
{
NIBBLETYPE Meta;

View File

@ -81,12 +81,18 @@ public:
case BLOCK_FACE_XM: return 3;
case BLOCK_FACE_XP: return 1;
case BLOCK_FACE_ZP: return 2;
default:
case BLOCK_FACE_NONE:
case BLOCK_FACE_YM:
case BLOCK_FACE_YP:
{
ASSERT(!"Unknown face");
return 0;
}
}
#if !defined(__clang__)
ASSERT(!"Unknown BLOCK_FACE");
return 0;
#endif
}
} ;

View File

@ -245,10 +245,10 @@ public:
if (a_BlockX > 0)
{
NIBBLETYPE DownMeta = a_ChunkInterface.GetBlockMeta(a_BlockX, a_BlockY - 1, a_BlockZ);
return (NIBBLETYPE) ((DownMeta & 0x07) | 0x08 | (Meta << 4));
return static_cast<NIBBLETYPE>((DownMeta & 0x07) | 0x08 | (Meta << 4));
}
// This is the top part of the door at the bottommost layer of the world, there's no bottom:
return (NIBBLETYPE) (0x08 | (Meta << 4));
return static_cast<NIBBLETYPE>(0x08 | (Meta << 4));
}
else
{
@ -256,7 +256,7 @@ public:
if (a_BlockY < cChunkDef::Height - 1)
{
NIBBLETYPE UpMeta = a_ChunkInterface.GetBlockMeta(a_BlockX, a_BlockY + 1, a_BlockZ);
return (NIBBLETYPE) (Meta | (UpMeta << 4));
return static_cast<NIBBLETYPE>(Meta | (UpMeta << 4));
}
// This is the bottom part of the door at the topmost layer of the world, there's no top:
return Meta;

View File

@ -35,7 +35,7 @@ public:
case BLOCK_FACE_NORTH: a_BlockMeta = E_META_HOPPER_FACING_ZP; break;
case BLOCK_FACE_SOUTH: a_BlockMeta = E_META_HOPPER_FACING_ZM; break;
case BLOCK_FACE_WEST: a_BlockMeta = E_META_HOPPER_FACING_XP; break;
default: a_BlockMeta = E_META_HOPPER_UNATTACHED; break;
case BLOCK_FACE_NONE: a_BlockMeta = E_META_HOPPER_UNATTACHED; break;
}
return true;
}

View File

@ -57,9 +57,18 @@ public:
case BLOCK_FACE_ZP: return 0x3;
case BLOCK_FACE_XM: return 0x4;
case BLOCK_FACE_XP: return 0x5;
default: return 0x2;
case BLOCK_FACE_NONE:
case BLOCK_FACE_YM:
case BLOCK_FACE_YP:
{
return 0x2;
}
}
#if !defined(__clang__)
ASSERT(!"Unknown BLOCK_FACE");
return 0;
#endif
}
static eBlockFace MetaDataToDirection(NIBBLETYPE a_MetaData)

View File

@ -59,7 +59,7 @@ public:
cItem(
E_BLOCK_SAPLING,
1,
(m_BlockType == E_BLOCK_LEAVES) ? (a_BlockMeta & 0x03) : (4 + (a_BlockMeta & 0x01))
(m_BlockType == E_BLOCK_LEAVES) ? (a_BlockMeta & 0x03) : static_cast<short>(4 + (a_BlockMeta & 0x01))
)
);
}

View File

@ -65,8 +65,12 @@ public:
case BLOCK_FACE_ZP: return 0x3;
case BLOCK_FACE_ZM: return 0x4;
case BLOCK_FACE_YM: return 0x0;
default: return 0x6;
case BLOCK_FACE_NONE: return 0x6;
}
#if !defined(__clang__)
ASSERT(!"Unknown BLOCK_FACE");
return 0;
#endif
}

View File

@ -36,6 +36,7 @@ public:
return true;
}
inline static NIBBLETYPE BlockFaceToMetaData(eBlockFace a_BlockFace, NIBBLETYPE a_QuartzMeta)
{
switch (a_BlockFace)
@ -58,11 +59,15 @@ public:
return 0x3; // East or west
}
default:
case BLOCK_FACE_NONE:
{
ASSERT(!"Unhandled block face!");
return a_QuartzMeta; // No idea, give a special meta (all sides the same)
}
}
#if !defined(__clang__)
ASSERT(!"Unknown BLOCK_FACE");
return 0;
#endif
}
} ;

View File

@ -487,7 +487,12 @@ public:
}
break;
}
default: break;
case BLOCK_FACE_NONE:
case BLOCK_FACE_YM:
case BLOCK_FACE_YP:
{
break;
}
}
return true;
}

View File

@ -58,12 +58,16 @@ public:
return a_Meta | 0x4; // East or west
}
default:
case BLOCK_FACE_NONE:
{
ASSERT(!"Unhandled block face!");
return a_Meta | 0xC; // No idea, give a special meta
}
}
#if !defined(__clang__)
ASSERT(!"Unknown BLOCK_FACE");
return 0;
#endif
}
} ;

View File

@ -41,7 +41,7 @@ public:
) override
{
a_BlockType = m_BlockType;
NIBBLETYPE Meta = (NIBBLETYPE) a_Player->GetEquippedItem().m_ItemDamage;
NIBBLETYPE Meta = static_cast<NIBBLETYPE>(a_Player->GetEquippedItem().m_ItemDamage);
// Set the correct metadata based on player equipped item (i.e. a_BlockMeta not initialised yet)
switch (a_BlockFace)
@ -104,7 +104,7 @@ public:
virtual void OnCancelRightClick(cChunkInterface & a_ChunkInterface, cWorldInterface & a_WorldInterface, cPlayer * a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace) override
{
if ((a_BlockFace == BLOCK_FACE_NONE) || (a_Player->GetEquippedItem().m_ItemType != (short)m_BlockType))
if ((a_BlockFace == BLOCK_FACE_NONE) || (a_Player->GetEquippedItem().m_ItemType != static_cast<short>(m_BlockType)))
{
return;
}

View File

@ -59,7 +59,7 @@ public:
case BLOCK_FACE_WEST: return E_META_TORCH_WEST;
case BLOCK_FACE_NORTH: return E_META_TORCH_NORTH;
case BLOCK_FACE_SOUTH: return E_META_TORCH_SOUTH;
default:
case BLOCK_FACE_NONE:
{
ASSERT(!"Unhandled torch direction!");
break;

View File

@ -66,6 +66,7 @@ public:
return true;
}
inline static NIBBLETYPE BlockFaceToMetaData(eBlockFace a_BlockFace)
{
switch (a_BlockFace)
@ -74,14 +75,21 @@ public:
case BLOCK_FACE_ZM: return 0x0;
case BLOCK_FACE_XP: return 0x3;
case BLOCK_FACE_XM: return 0x2;
default:
case BLOCK_FACE_NONE:
case BLOCK_FACE_YM:
case BLOCK_FACE_YP:
{
ASSERT(!"Unhandled block face!");
return 0;
}
}
#if !defined(__clang__)
ASSERT(!"Unknown BLOCK_FACE");
return 0;
#endif
}
inline static eBlockFace BlockMetaDataToBlockFace(NIBBLETYPE a_Meta)
{
switch (a_Meta & 0x3)
@ -98,6 +106,7 @@ public:
}
}
virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override
{
NIBBLETYPE Meta;

View File

@ -16,6 +16,7 @@ public:
{
}
virtual bool GetPlacementBlockTypeMeta(
cChunkInterface & a_ChunkInterface, cPlayer * a_Player,
int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace,
@ -29,6 +30,7 @@ public:
return true;
}
inline static NIBBLETYPE DirectionToMetadata(eBlockFace a_Direction)
{
switch (a_Direction)
@ -37,9 +39,20 @@ public:
case BLOCK_FACE_XP: return 0x3;
case BLOCK_FACE_ZM: return 0x2;
case BLOCK_FACE_ZP: return 0x0;
default: ASSERT(!"Unhandled tripwire hook direction!"); return 0x0;
case BLOCK_FACE_NONE:
case BLOCK_FACE_YM:
case BLOCK_FACE_YP:
{
ASSERT(!"Unhandled tripwire hook direction!");
return 0x0;
}
}
#if !defined(__clang__)
ASSERT(!"Unknown BLOCK_FACE");
return 0;
#endif
}
inline static eBlockFace MetadataToDirection(NIBBLETYPE a_Meta)
{
@ -53,6 +66,7 @@ public:
}
}
virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override
{
// Reset meta to zero

View File

@ -55,11 +55,13 @@ public:
{
switch (a_Direction)
{
case 0x2: return 0x2;
case 0x3: return 0x3;
case 0x4: return 0x4;
case 0x5: return 0x5;
default:
case BLOCK_FACE_ZM: return 0x2;
case BLOCK_FACE_ZP: return 0x3;
case BLOCK_FACE_XM: return 0x4;
case BLOCK_FACE_XP: return 0x5;
case BLOCK_FACE_NONE:
case BLOCK_FACE_YP:
case BLOCK_FACE_YM:
{
break;
}

View File

@ -95,6 +95,11 @@ SET (HDRS
MetaRotator.h
WorldInterface.h)
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
set_source_files_properties(BlockHandler.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(BlockPiston.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
endif()
if(NOT MSVC)
add_library(Blocks ${SRCS} ${HDRS})
endif()

View File

@ -62,6 +62,7 @@ SET (SRCS
Scoreboard.cpp
Server.cpp
SetChunkData.cpp
SpawnPrepare.cpp
Statistics.cpp
StringCompression.cpp
StringUtils.cpp
@ -133,6 +134,7 @@ SET (HDRS
Server.h
SetChunkData.h
SettingsRepositoryInterface.h
SpawnPrepare.h
Statistics.h
StringCompression.h
StringUtils.h
@ -151,6 +153,38 @@ include_directories (SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/../lib/TCLAP/include")
configure_file("BuildInfo.h.cmake" "${CMAKE_CURRENT_SOURCE_DIR}/BuildInfo.h")
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
set_source_files_properties(BiomeDef.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=switch-enum")
set_source_files_properties(BlockArea.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion")
set_source_files_properties(BlockID.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors")
set_source_files_properties(BoundingBox.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors -Wno-error=float-equal")
set_source_files_properties(ByteBuffer.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion -Wno-error=old-style-cast -Wno-error=global-constructors")
set_source_files_properties(Chunk.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(ChunkData.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion -Wno-error=old-style-cast")
set_source_files_properties(ChunkMap.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=shadow -Wno-error=sign-conversion -Wno-error=old-style-cast")
set_source_files_properties(ClientHandle.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=conversion -Wno-error=sign-conversion -Wno-error=global-constructors -Wno-error=old-style-cast")
set_source_files_properties(CompositeChat.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors -Wno-error=missing-variable-declarations")
set_source_files_properties(Enchantments.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(IniFile.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion -Wno-error=old-style-cast")
set_source_files_properties(Inventory.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=conversion")
set_source_files_properties(Item.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=conversion -Wno-error=old-style-cast")
set_source_files_properties(ItemGrid.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=conversion")
set_source_files_properties(LightingThread.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=conversion -Wno-error=sign-conversion")
set_source_files_properties(LinearInterpolation.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(Map.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=conversion -Wno-error=old-style-cast")
set_source_files_properties(MobProximityCounter.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=float-equal")
set_source_files_properties(MobSpawner.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=switch-enum")
set_source_files_properties(RCONServer.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion")
set_source_files_properties(Root.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion -Wno-error=shadow -Wno-error=old-style-cast")
set_source_files_properties(Server.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(Statistics.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors")
set_source_files_properties(StringCompression.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(StringUtils.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=conversion -Wno-error=old-style-cast")
set_source_files_properties(Tracer.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion")
set_source_files_properties(World.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion -Wno-error=old-style-cast")
set_source_files_properties(main.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=missing-variable-declarations -Wno-error=missing-prototypes")
endif()
if (NOT MSVC)
# Bindings need to reference other folders, so they are done here instead
# lib dependencies are not included
@ -332,4 +366,9 @@ endif ()
if (WIN32)
target_link_libraries(${EXECUTABLE} expat tolualib ws2_32.lib Psapi.lib)
endif()
if (${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD")
add_flags_lnk(-L/usr/local/lib)
endif()
target_link_libraries(${EXECUTABLE} luaexpat jsoncpp mbedtls zlib sqlite lua SQLiteCpp event_core event_extra)

View File

@ -714,8 +714,8 @@ void cChunk::MoveEntityToNewChunk(cEntity * a_Entity)
cEntity * m_Entity;
public:
cMover(cEntity * a_Entity) :
m_Entity(a_Entity)
cMover(cEntity * a_CallbackEntity) :
m_Entity(a_CallbackEntity)
{}
} Mover(a_Entity);

View File

@ -190,7 +190,7 @@ public:
}
inline static int GetHeight(const HeightMap & a_HeightMap, int a_X, int a_Z)
inline static HEIGHTTYPE GetHeight(const HeightMap & a_HeightMap, int a_X, int a_Z)
{
ASSERT((a_X >= 0) && (a_X < Width));
ASSERT((a_Z >= 0) && (a_Z < Width));
@ -198,7 +198,7 @@ public:
}
inline static void SetHeight(HeightMap & a_HeightMap, int a_X, int a_Z, unsigned char a_Height)
inline static void SetHeight(HeightMap & a_HeightMap, int a_X, int a_Z, HEIGHTTYPE a_Height)
{
ASSERT((a_X >= 0) && (a_X < Width));
ASSERT((a_Z >= 0) && (a_Z < Width));

View File

@ -2401,7 +2401,7 @@ void cChunkMap::TouchChunk(int a_ChunkX, int a_ChunkZ)
void cChunkMap::PrepareChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_Callback)
void cChunkMap::PrepareChunk(int a_ChunkX, int a_ChunkZ, std::unique_ptr<cChunkCoordCallback> a_Callback)
{
cCSLock Lock(m_CSLayers);
cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ);
@ -2409,7 +2409,7 @@ void cChunkMap::PrepareChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a
// If the chunk is not prepared, queue it in the lighting thread, that will do all the needed processing:
if ((Chunk == nullptr) || !Chunk->IsValid() || !Chunk->IsLightValid())
{
m_World->GetLightingThread().QueueChunk(a_ChunkX, a_ChunkZ, a_Callback);
m_World->GetLightingThread().QueueChunk(a_ChunkX, a_ChunkZ, std::move(a_Callback));
return;
}

View File

@ -322,7 +322,7 @@ public:
The specified chunk is queued to be loaded or generated, and lit if needed.
The specified callback is called after the chunk has been prepared. If there's no preparation to do, only the callback is called.
It is legal to call without the callback. */
void PrepareChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_CallAfter = nullptr); // Lua-accessible
void PrepareChunk(int a_ChunkX, int a_ChunkZ, std::unique_ptr<cChunkCoordCallback> a_CallAfter = {}); // Lua-accessible
/** Queues the chunk for generating.
First attempts to load the chunk from the storage. If that fails, queues the chunk for generating.

View File

@ -21,10 +21,21 @@
////////////////////////////////////////////////////////////////////////////////
// cNotifyChunkSender:
void cNotifyChunkSender::Call(int a_ChunkX, int a_ChunkZ)
/// Callback that can be used to notify chunk sender upon another chunkcoord notification
class cNotifyChunkSender :
public cChunkCoordCallback
{
virtual void Call(int a_ChunkX, int a_ChunkZ) override
{
m_ChunkSender->ChunkReady(a_ChunkX, a_ChunkZ);
}
}
cChunkSender * m_ChunkSender;
public:
cNotifyChunkSender(cChunkSender * a_ChunkSender) : m_ChunkSender(a_ChunkSender) {}
};
@ -36,10 +47,8 @@ void cNotifyChunkSender::Call(int a_ChunkX, int a_ChunkZ)
cChunkSender::cChunkSender(void) :
super("ChunkSender"),
m_World(nullptr),
m_RemoveCount(0),
m_Notify(nullptr)
m_RemoveCount(0)
{
m_Notify.SetChunkSender(this);
}
@ -125,10 +134,6 @@ void cChunkSender::QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, eChunkPriority a
m_SendChunksHighPriority.push_back(Chunk);
break;
}
default:
{
ASSERT(!"Unknown chunk priority!");
}
}
}
m_evtQueue.Set();
@ -276,7 +281,7 @@ void cChunkSender::SendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Clien
// If the chunk is not lighted, queue it for relighting and get notified when it's ready:
if (!m_World->IsChunkLighted(a_ChunkX, a_ChunkZ))
{
m_World->QueueLightChunk(a_ChunkX, a_ChunkZ, &m_Notify);
m_World->QueueLightChunk(a_ChunkX, a_ChunkZ, cpp14::make_unique<cNotifyChunkSender>(this));
return;
}
@ -342,7 +347,7 @@ void cChunkSender::BiomeData(const cChunkDef::BiomeMap * a_BiomeMap)
if ((*a_BiomeMap)[i] < 255)
{
// Normal MC biome, copy as-is:
m_BiomeMap[i] = (unsigned char)((*a_BiomeMap)[i]);
m_BiomeMap[i] = static_cast<unsigned char>((*a_BiomeMap)[i]);
}
else
{

View File

@ -47,26 +47,6 @@ class cChunkSender;
/// Callback that can be used to notify chunk sender upon another chunkcoord notification
class cNotifyChunkSender :
public cChunkCoordCallback
{
virtual void Call(int a_ChunkX, int a_ChunkZ) override;
cChunkSender * m_ChunkSender;
public:
cNotifyChunkSender(cChunkSender * a_ChunkSender) : m_ChunkSender(a_ChunkSender) {}
void SetChunkSender(cChunkSender * a_ChunkSender)
{
m_ChunkSender = a_ChunkSender;
}
} ;
class cChunkSender:
public cIsThread,
public cChunkDataSeparateCollector
@ -150,8 +130,6 @@ protected:
cEvent m_evtRemoved; // Set when removed clients are safe to be deleted
int m_RemoveCount; // Number of threads waiting for a client removal (m_evtRemoved needs to be set this many times)
cNotifyChunkSender m_Notify; // Used for chunks that don't have a valid lighting - they will be re-queued after lightcalc
// Data about the chunk that is being sent:
// NOTE that m_BlockData[] is inherited from the cChunkDataCollector
unsigned char m_BiomeMap[cChunkDef::Width * cChunkDef::Width];

View File

@ -381,8 +381,8 @@ void cClientHandle::Authenticate(const AString & a_Name, const AString & a_UUID,
// Send player list items
SendPlayerListAddPlayer(*m_Player);
World->BroadcastPlayerListAddPlayer(*m_Player);
World->SendPlayerList(m_Player);
cRoot::Get()->BroadcastPlayerListsAddPlayer(*m_Player);
cRoot::Get()->SendPlayerLists(m_Player);
m_Player->Initialize(*World);
m_State = csAuthenticated;
@ -1475,7 +1475,7 @@ void cClientHandle::HandleChat(const AString & a_Message)
Msg.AddTextPart(AString("<") + m_Player->GetName() + "> ", Color);
Msg.ParseText(Message);
Msg.UnderlineUrls();
m_Player->GetWorld()->BroadcastChat(Msg);
cRoot::Get()->BroadcastChat(Msg);
}
@ -1902,7 +1902,7 @@ void cClientHandle::Tick(float a_Dt)
if (m_TicksSinceLastPacket > 600) // 30 seconds time-out
{
SendDisconnect("Nooooo!! You timed out! D: Come back!");
Destroy();
return;
}
if (m_Player == nullptr)
@ -2013,7 +2013,6 @@ void cClientHandle::ServerTick(float a_Dt)
if (m_TicksSinceLastPacket > 600) // 30 seconds
{
SendDisconnect("Nooooo!! You timed out! D: Come back!");
Destroy();
}
}
@ -2182,6 +2181,8 @@ void cClientHandle::SendDestroyEntity(const cEntity & a_Entity)
void cClientHandle::SendDisconnect(const AString & a_Reason)
{
// Destruction (Destroy()) is called when the client disconnects, not when a disconnect packet (or anything else) is sent
// Otherwise, the cClientHandle instance is can be unexpectedly removed from the associated player - Core/#142
if (!m_HasSentDC)
{
LOGD("Sending a DC: \"%s\"", StripColorCodes(a_Reason).c_str());
@ -2329,6 +2330,15 @@ void cClientHandle::SendHealth(void)
void cClientHandle::SendHideTitle(void)
{
m_Protocol->SendHideTitle();
}
void cClientHandle::SendInventorySlot(char a_WindowID, short a_SlotNum, const cItem & a_Item)
{
m_Protocol->SendInventorySlot(a_WindowID, a_SlotNum, a_Item);
@ -2532,6 +2542,15 @@ void cClientHandle::SendRemoveEntityEffect(const cEntity & a_Entity, int a_Effec
void cClientHandle::SendResetTitle()
{
m_Protocol->SendResetTitle();
}
void cClientHandle::SendRespawn(eDimension a_Dimension, bool a_ShouldIgnoreDimensionChecks)
{
m_Protocol->SendRespawn(a_Dimension, a_ShouldIgnoreDimensionChecks);
@ -2586,6 +2605,42 @@ void cClientHandle::SendDisplayObjective(const AString & a_Objective, cScoreboar
void cClientHandle::SendSetSubTitle(const cCompositeChat & a_SubTitle)
{
m_Protocol->SendSetSubTitle(a_SubTitle);
}
void cClientHandle::SendSetRawSubTitle(const AString & a_SubTitle)
{
m_Protocol->SendSetRawSubTitle(a_SubTitle);
}
void cClientHandle::SendSetTitle(const cCompositeChat & a_Title)
{
m_Protocol->SendSetTitle(a_Title);
}
void cClientHandle::SendSetRawTitle(const AString & a_Title)
{
m_Protocol->SendSetRawTitle(a_Title);
}
void cClientHandle::SendSoundEffect(const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch)
{
m_Protocol->SendSoundEffect(a_SoundName, a_X, a_Y, a_Z, a_Volume, a_Pitch);
@ -2676,6 +2731,15 @@ void cClientHandle::SendThunderbolt(int a_BlockX, int a_BlockY, int a_BlockZ)
void cClientHandle::SendTitleTimes(int a_FadeInTicks, int a_DisplayTicks, int a_FadeOutTicks)
{
m_Protocol->SendTitleTimes(a_FadeInTicks, a_DisplayTicks, a_FadeOutTicks);
}
void cClientHandle::SendTimeUpdate(Int64 a_WorldAge, Int64 a_TimeOfDay, bool a_DoDaylightCycle)
{
m_Protocol->SendTimeUpdate(a_WorldAge, a_TimeOfDay, a_DoDaylightCycle);
@ -2859,7 +2923,6 @@ void cClientHandle::PacketBufferFull(void)
// Too much data in the incoming queue, the server is probably too busy, kick the client:
LOGERROR("Too much data in queue for client \"%s\" @ %s, kicking them.", m_Username.c_str(), m_IPString.c_str());
SendDisconnect("Server busy");
Destroy();
}
@ -2873,7 +2936,6 @@ void cClientHandle::PacketUnknown(UInt32 a_PacketType)
AString Reason;
Printf(Reason, "Unknown [C->S] PacketType: 0x%x", a_PacketType);
SendDisconnect(Reason);
Destroy();
}
@ -2884,7 +2946,6 @@ void cClientHandle::PacketError(UInt32 a_PacketType)
{
LOGERROR("Protocol error while parsing packet type 0x%02x; disconnecting client \"%s\"", a_PacketType, m_Username.c_str());
SendDisconnect("Protocol error");
Destroy();
}
@ -2900,7 +2961,14 @@ void cClientHandle::SocketClosed(void)
LOGD("Client %s @ %s disconnected", m_Username.c_str(), m_IPString.c_str());
cRoot::Get()->GetPluginManager()->CallHookDisconnect(*this, "Player disconnected");
}
if ((m_State < csDestroying) && (m_Player != nullptr))
{
cWorld * World = m_Player->GetWorld();
if (World != nullptr)
{
World->RemovePlayer(m_Player, true); // Must be called before cPlayer::Destroy() as otherwise cChunk tries to delete the player, and then we do it again
}
}
Destroy();
}

View File

@ -172,6 +172,7 @@ public: // tolua_export
void SendExplosion (double a_BlockX, double a_BlockY, double a_BlockZ, float a_Radius, const cVector3iArray & a_BlocksAffected, const Vector3d & a_PlayerMotion);
void SendGameMode (eGameMode a_GameMode);
void SendHealth (void);
void SendHideTitle (void);
void SendInventorySlot (char a_WindowID, short a_SlotNum, const cItem & a_Item);
void SendMapColumn (int a_ID, int a_X, int a_Y, const Byte * a_Colors, unsigned int a_Length, unsigned int m_Scale);
void SendMapDecorators (int a_ID, const cMapDecoratorList & a_Decorators, unsigned int m_Scale);
@ -192,9 +193,14 @@ public: // tolua_export
void SendPlayerSpawn (const cPlayer & a_Player);
void SendPluginMessage (const AString & a_Channel, const AString & a_Message); // Exported in ManualBindings.cpp
void SendRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID);
void SendResetTitle (void);
void SendRespawn (eDimension a_Dimension, bool a_ShouldIgnoreDimensionChecks = false);
void SendScoreUpdate (const AString & a_Objective, const AString & a_Player, cObjective::Score a_Score, Byte a_Mode);
void SendScoreboardObjective (const AString & a_Name, const AString & a_DisplayName, Byte a_Mode);
void SendSetSubTitle (const cCompositeChat & a_SubTitle);
void SendSetRawSubTitle (const AString & a_SubTitle);
void SendSetTitle (const cCompositeChat & a_Title);
void SendSetRawTitle (const AString & a_Title);
void SendSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch); // tolua_export
void SendSoundParticleEffect (int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data);
void SendSpawnFallingBlock (const cFallingBlock & a_FallingBlock);
@ -205,6 +211,7 @@ public: // tolua_export
void SendTabCompletionResults (const AStringVector & a_Results);
void SendTeleportEntity (const cEntity & a_Entity);
void SendThunderbolt (int a_BlockX, int a_BlockY, int a_BlockZ);
void SendTitleTimes (int a_FadeInTicks, int a_DisplayTicks, int a_FadeOutTicks);
void SendTimeUpdate (Int64 a_WorldAge, Int64 a_TimeOfDay, bool a_DoDaylightCycle); // tolua_export
void SendUnloadChunk (int a_ChunkX, int a_ChunkZ);
void SendUpdateBlockEntity (cBlockEntity & a_BlockEntity);

View File

@ -342,7 +342,11 @@ AString cCompositeChat::ExtractText(void) const
}
case ptUrl:
{
Msg.append(((cUrlPart *)(*itr))->m_Url);
Msg.append((static_cast<cUrlPart *>(*itr))->m_Url);
break;
}
case ptShowAchievement:
{
break;
}
} // switch (PartType)
@ -419,7 +423,7 @@ AString cCompositeChat::CreateJsonString(bool a_ShouldUseChatPrefixes) const
case cCompositeChat::ptClientTranslated:
{
const cCompositeChat::cClientTranslatedPart & p = (const cCompositeChat::cClientTranslatedPart &)**itr;
const cCompositeChat::cClientTranslatedPart & p = static_cast<const cCompositeChat::cClientTranslatedPart &>(**itr);
Part["translate"] = p.m_Text;
Json::Value With;
for (AStringVector::const_iterator itrW = p.m_Parameters.begin(), endW = p.m_Parameters.end(); itrW != endW; ++itr)
@ -436,7 +440,7 @@ AString cCompositeChat::CreateJsonString(bool a_ShouldUseChatPrefixes) const
case cCompositeChat::ptUrl:
{
const cCompositeChat::cUrlPart & p = (const cCompositeChat::cUrlPart &)**itr;
const cCompositeChat::cUrlPart & p = static_cast<const cCompositeChat::cUrlPart &>(**itr);
Part["text"] = p.m_Text;
Json::Value Url;
Url["action"] = "open_url";
@ -449,7 +453,7 @@ AString cCompositeChat::CreateJsonString(bool a_ShouldUseChatPrefixes) const
case cCompositeChat::ptSuggestCommand:
case cCompositeChat::ptRunCommand:
{
const cCompositeChat::cCommandPart & p = (const cCompositeChat::cCommandPart &)**itr;
const cCompositeChat::cCommandPart & p = static_cast<const cCompositeChat::cCommandPart &>(**itr);
Part["text"] = p.m_Text;
Json::Value Cmd;
Cmd["action"] = (p.m_PartType == cCompositeChat::ptRunCommand) ? "run_command" : "suggest_command";
@ -461,7 +465,7 @@ AString cCompositeChat::CreateJsonString(bool a_ShouldUseChatPrefixes) const
case cCompositeChat::ptShowAchievement:
{
const cCompositeChat::cShowAchievementPart & p = (const cCompositeChat::cShowAchievementPart &)**itr;
const cCompositeChat::cShowAchievementPart & p = static_cast<const cCompositeChat::cShowAchievementPart &>(**itr);
Part["translate"] = "chat.type.achievement";
Json::Value Ach;

View File

@ -373,7 +373,7 @@ void cCraftingRecipes::AddRecipeLine(int a_LineNum, const AString & a_RecipeLine
AStringVector Sides = StringSplit(RecipeLine, "=");
if (Sides.size() != 2)
{
LOGWARNING("crafting.txt: line %d: A single '=' was expected, got %d", a_LineNum, (int)Sides.size() - 1);
LOGWARNING("crafting.txt: line %d: A single '=' was expected, got " SIZE_T_FMT, a_LineNum, Sides.size() - 1);
LOGINFO("Offending line: \"%s\"", a_RecipeLine.c_str());
return;
}
@ -771,9 +771,12 @@ cCraftingRecipes::cRecipe * cCraftingRecipes::MatchRecipe(const cItem * a_Crafti
continue;
}
Recipe->m_Ingredients.push_back(*itrS);
Recipe->m_Ingredients.back().x += a_OffsetX;
Recipe->m_Ingredients.back().y += a_OffsetY;
}
Recipe->m_Ingredients.insert(Recipe->m_Ingredients.end(), MatchedSlots.begin(), MatchedSlots.end());
// Handle the fireworks-related effects:
// We use Recipe instead of a_Recipe because we want the wildcard ingredients' slot numbers as well, which was just added previously
HandleFireworks(a_CraftingGrid, Recipe.get(), a_GridStride, a_OffsetX, a_OffsetY);
@ -833,7 +836,7 @@ void cCraftingRecipes::HandleFireworks(const cItem * a_CraftingGrid, cCraftingRe
case E_ITEM_DYE:
{
int GridID = (itr->x + a_OffsetX) + a_GridStride * (itr->y + a_OffsetY);
DyeColours.push_back(cFireworkItem::GetVanillaColourCodeFromDye((NIBBLETYPE)(a_CraftingGrid[GridID].m_ItemDamage & 0x0f)));
DyeColours.push_back(cFireworkItem::GetVanillaColourCodeFromDye(static_cast<NIBBLETYPE>(a_CraftingGrid[GridID].m_ItemDamage & 0x0f)));
break;
}
case E_ITEM_GUNPOWDER: break;

View File

@ -238,8 +238,17 @@ inline eBlockFace MirrorBlockFaceY(eBlockFace a_BlockFace)
case BLOCK_FACE_XP: return BLOCK_FACE_XM;
case BLOCK_FACE_ZM: return BLOCK_FACE_ZP;
case BLOCK_FACE_ZP: return BLOCK_FACE_ZM;
default: return a_BlockFace;
case BLOCK_FACE_NONE:
case BLOCK_FACE_YM:
case BLOCK_FACE_YP:
{
return a_BlockFace;
};
}
#if !defined(__clang__)
ASSERT(!"Unknown BLOCK_FACE");
return a_BlockFace;
#endif
}
@ -255,8 +264,17 @@ inline eBlockFace RotateBlockFaceCCW(eBlockFace a_BlockFace)
case BLOCK_FACE_XP: return BLOCK_FACE_ZM;
case BLOCK_FACE_ZM: return BLOCK_FACE_XM;
case BLOCK_FACE_ZP: return BLOCK_FACE_XP;
default: return a_BlockFace;
case BLOCK_FACE_NONE:
case BLOCK_FACE_YM:
case BLOCK_FACE_YP:
{
return a_BlockFace;
}
}
#if !defined(__clang__)
ASSERT(!"Unknown BLOCK_FACE");
return a_BlockFace;
#endif
}
@ -271,10 +289,23 @@ inline eBlockFace RotateBlockFaceCW(eBlockFace a_BlockFace)
case BLOCK_FACE_XP: return BLOCK_FACE_ZP;
case BLOCK_FACE_ZM: return BLOCK_FACE_XP;
case BLOCK_FACE_ZP: return BLOCK_FACE_XM;
default: return a_BlockFace;
case BLOCK_FACE_NONE:
case BLOCK_FACE_YM:
case BLOCK_FACE_YP:
{
return a_BlockFace;
};
}
#if !defined(__clang__)
ASSERT(!"Unknown BLOCK_FACE");
return a_BlockFace;
#endif
}
inline eBlockFace ReverseBlockFace(eBlockFace a_BlockFace)
{
switch (a_BlockFace)
@ -285,11 +316,18 @@ inline eBlockFace ReverseBlockFace(eBlockFace a_BlockFace)
case BLOCK_FACE_YM: return BLOCK_FACE_YP;
case BLOCK_FACE_XM: return BLOCK_FACE_XP;
case BLOCK_FACE_ZM: return BLOCK_FACE_ZP;
default: return a_BlockFace;
case BLOCK_FACE_NONE: return a_BlockFace;
}
#if !defined(__clang__)
ASSERT(!"Unknown BLOCK_FACE");
return a_BlockFace;
#endif
}
/** Returns the textual representation of the BlockFace constant. */
inline AString BlockFaceToString(eBlockFace a_BlockFace)
{
@ -436,7 +474,7 @@ inline void AddFaceDirection(int & a_BlockX, int & a_BlockY, int & a_BlockZ, eBl
case BLOCK_FACE_ZP: a_BlockZ++; break;
case BLOCK_FACE_XP: a_BlockX++; break;
case BLOCK_FACE_XM: a_BlockX--; break;
default:
case BLOCK_FACE_NONE:
{
LOGWARNING("%s: Unknown face: %d", __FUNCTION__, a_BlockFace);
ASSERT(!"AddFaceDirection(): Unknown face");
@ -454,7 +492,7 @@ inline void AddFaceDirection(int & a_BlockX, int & a_BlockY, int & a_BlockZ, eBl
case BLOCK_FACE_ZP: a_BlockZ--; break;
case BLOCK_FACE_XP: a_BlockX--; break;
case BLOCK_FACE_XM: a_BlockX++; break;
default:
case BLOCK_FACE_NONE:
{
LOGWARNING("%s: Unknown inv face: %d", __FUNCTION__, a_BlockFace);
ASSERT(!"AddFaceDirection(): Unknown face");

View File

@ -69,8 +69,8 @@ void cEnchantments::AddFromString(const AString & a_StringSpec)
LOG("%s: Failed to parse enchantment \"%s\", skipping.", __FUNCTION__, Split[0].c_str());
continue;
}
int lvl = atoi(Split[1].c_str());
if ((lvl == 0) && (Split[1] != "0"))
unsigned int lvl;
if (!StringToInteger(Split[1], lvl))
{
// Level failed to parse
LOG("%s: Failed to parse enchantment level \"%s\", skipping.", __FUNCTION__, Split[1].c_str());
@ -108,7 +108,7 @@ AString cEnchantments::ToString(void) const
int cEnchantments::GetLevel(int a_EnchantmentID) const
unsigned int cEnchantments::GetLevel(int a_EnchantmentID) const
{
// Return the level for the specified enchantment; 0 if not stored
cMap::const_iterator itr = m_Enchantments.find(a_EnchantmentID);
@ -125,7 +125,7 @@ int cEnchantments::GetLevel(int a_EnchantmentID) const
void cEnchantments::SetLevel(int a_EnchantmentID, int a_Level)
void cEnchantments::SetLevel(int a_EnchantmentID, unsigned int a_Level)
{
// Sets the level for the specified enchantment, adding it if not stored before or removing it if level <= 0
if (a_Level == 0)
@ -908,7 +908,7 @@ void cEnchantments::AddItemEnchantmentWeights(cWeightedEnchantments & a_Enchantm
void cEnchantments::AddEnchantmentWeightToVector(cWeightedEnchantments & a_Enchantments, int a_Weight, int a_EnchantmentID, int a_EnchantmentLevel)
void cEnchantments::AddEnchantmentWeightToVector(cWeightedEnchantments & a_Enchantments, int a_Weight, int a_EnchantmentID, unsigned int a_EnchantmentLevel)
{
cWeightedEnchantment weightedenchantment;
weightedenchantment.m_Weight = a_Weight;

View File

@ -92,10 +92,10 @@ public:
AString ToString(void) const;
/** Returns the level for the specified enchantment; 0 if not stored */
int GetLevel(int a_EnchantmentID) const;
unsigned int GetLevel(int a_EnchantmentID) const;
/** Sets the level for the specified enchantment, adding it if not stored before or removing it if level <= 0 */
void SetLevel(int a_EnchantmentID, int a_Level);
void SetLevel(int a_EnchantmentID, unsigned int a_Level);
/** Removes all enchantments */
void Clear(void);
@ -115,7 +115,7 @@ public:
static void AddItemEnchantmentWeights(cWeightedEnchantments & a_Enchantments, short a_ItemType, int a_EnchantmentLevel);
/** Add a enchantment with weight to the vector */
static void AddEnchantmentWeightToVector(cWeightedEnchantments & a_Enchantments, int a_Weight, int a_EnchantmentID, int a_EnchantmentLevel);
static void AddEnchantmentWeightToVector(cWeightedEnchantments & a_Enchantments, int a_Weight, int a_EnchantmentID, unsigned int a_EnchantmentLevel);
/** Remove the entire enchantment (with weight) from the vector */
static void RemoveEnchantmentWeightFromVector(cWeightedEnchantments & a_Enchantments, int a_EnchantmentID);
@ -145,7 +145,7 @@ public:
protected:
/** Maps enchantment ID -> enchantment level */
typedef std::map<int, int> cMap;
typedef std::map<int, unsigned int> cMap;
/** Currently stored enchantments */
cMap m_Enchantments;

View File

@ -108,15 +108,15 @@ void cArrowEntity::OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos)
Damage += m_World->GetTickRandomNumber(Damage / 2 + 2);
}
int PowerLevel = m_CreatorData.m_Enchantments.GetLevel(cEnchantments::enchPower);
unsigned int PowerLevel = m_CreatorData.m_Enchantments.GetLevel(cEnchantments::enchPower);
if (PowerLevel > 0)
{
int ExtraDamage = (int)ceil(0.25 * (PowerLevel + 1));
Damage += ExtraDamage;
}
int KnockbackAmount = 1;
int PunchLevel = m_CreatorData.m_Enchantments.GetLevel(cEnchantments::enchPunch);
// int KnockbackAmount = 1;
unsigned int PunchLevel = m_CreatorData.m_Enchantments.GetLevel(cEnchantments::enchPunch);
if (PunchLevel > 0)
{
Vector3d LookVector = GetLookVector();
@ -130,7 +130,8 @@ void cArrowEntity::OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos)
a_EntityHit.SetSpeed(FinalSpeed);
}
a_EntityHit.TakeDamage(dtRangedAttack, this, Damage, KnockbackAmount);
// a_EntityHit.TakeDamage(dtRangedAttack, this, Damage, KnockbackAmount); // TODO fix knockback.
a_EntityHit.TakeDamage(dtRangedAttack, this, Damage, 0); // Until knockback is fixed.
if (IsOnFire() && !a_EntityHit.IsSubmerged() && !a_EntityHit.IsSwimming())
{

View File

@ -60,6 +60,14 @@ SET (HDRS
ThrownSnowballEntity.h
WitherSkullEntity.h)
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
set_source_files_properties(ArrowEntity.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(Entity.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion -Wno-error=global-constructors -Wno-error=switch-enum -Wno-error=old-style-cast")
set_source_files_properties(EntityEffect.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=switch-enum -Wno-error=old-style-cast")
set_source_files_properties(Floater.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion -Wno-error=old-style-cast")
set_source_files_properties(Player.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=sign-conversion -Wno-error=switch-enum -Wno-error=conversion -Wno-error=old-style-cast")
endif()
if(NOT MSVC)
add_library(Entities ${SRCS} ${HDRS})

View File

@ -22,7 +22,7 @@ cEnderCrystal::cEnderCrystal(double a_X, double a_Y, double a_Z)
void cEnderCrystal::SpawnOn(cClientHandle & a_ClientHandle)
{
a_ClientHandle.SendSpawnObject(*this, 51, 0, (Byte)GetYaw(), (Byte)GetPitch());
a_ClientHandle.SendSpawnObject(*this, 51, 0, static_cast<Byte>(GetYaw()), static_cast<Byte>(GetPitch()));
}

View File

@ -396,7 +396,7 @@ bool cEntity::DoTakeDamage(TakeDamageInfo & a_TDI)
}
}
int ThornsLevel = 0;
unsigned int ThornsLevel = 0;
const cItem ArmorItems[] = { GetEquippedHelmet(), GetEquippedChestplate(), GetEquippedLeggings(), GetEquippedBoots() };
for (size_t i = 0; i < ARRAYCOUNT(ArmorItems); i++)
{

View File

@ -205,8 +205,8 @@ public:
double GetSpeedZ (void) const { return m_Speed.z; }
double GetWidth (void) const { return m_Width; }
int GetChunkX(void) const {return (int)floor(m_Pos.x / cChunkDef::Width); }
int GetChunkZ(void) const {return (int)floor(m_Pos.z / cChunkDef::Width); }
int GetChunkX(void) const {return static_cast<int>(floor(m_Pos.x / cChunkDef::Width)); }
int GetChunkZ(void) const {return static_cast<int>(floor(m_Pos.z / cChunkDef::Width)); }
void SetHeadYaw (double a_HeadYaw);
void SetHeight (double a_Height);

View File

@ -56,12 +56,12 @@ void cExpOrb::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
LOGD("Player %s picked up an ExpOrb. His reward is %i", a_ClosestPlayer->GetName().c_str(), m_Reward);
a_ClosestPlayer->DeltaExperience(m_Reward);
m_World->BroadcastSoundEffect("random.orb", GetPosX(), GetPosY(), GetPosZ(), 0.5f, (float)(0.75 + ((float)((GetUniqueID() * 23) % 32)) / 64));
m_World->BroadcastSoundEffect("random.orb", GetPosX(), GetPosY(), GetPosZ(), 0.5f, (0.75f + (static_cast<float>((GetUniqueID() * 23) % 32)) / 64));
Destroy();
}
a_Distance.Normalize();
a_Distance *= ((float) (5.5 - Distance));
a_Distance *= (static_cast<float>(5.5 - Distance));
SetSpeedX( a_Distance.x);
SetSpeedY( a_Distance.y);
SetSpeedZ( a_Distance.z);

View File

@ -38,7 +38,7 @@ void cFallingBlock::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
// GetWorld()->BroadcastTeleportEntity(*this); // Test position
int BlockX = POSX_TOINT;
int BlockY = (int)(GetPosY() - 0.5);
int BlockY = static_cast<int>(GetPosY() - 0.5);
int BlockZ = POSZ_TOINT;
if (BlockY < 0)

View File

@ -19,11 +19,11 @@ cFireChargeEntity::cFireChargeEntity(cEntity * a_Creator, double a_X, double a_Y
void cFireChargeEntity::Explode(int a_BlockX, int a_BlockY, int a_BlockZ)
void cFireChargeEntity::Explode(Vector3i a_Block)
{
if (m_World->GetBlock(a_BlockX, a_BlockY, a_BlockZ) == E_BLOCK_AIR)
if (m_World->GetBlock(a_Block) == E_BLOCK_AIR)
{
m_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_FIRE, 1);
m_World->SetBlock(a_Block.x, a_Block.y, a_Block.z, E_BLOCK_FIRE, 1);
}
}
@ -34,7 +34,7 @@ void cFireChargeEntity::Explode(int a_BlockX, int a_BlockY, int a_BlockZ)
void cFireChargeEntity::OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace)
{
Destroy();
Explode((int)floor(a_HitPos.x), (int)floor(a_HitPos.y), (int)floor(a_HitPos.z));
Explode(a_HitPos.Floor());
}
@ -44,7 +44,7 @@ void cFireChargeEntity::OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_
void cFireChargeEntity::OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos)
{
Destroy();
Explode((int)floor(a_HitPos.x), (int)floor(a_HitPos.y), (int)floor(a_HitPos.z));
Explode(a_HitPos.Floor());
// TODO: Some entities are immune to hits
a_EntityHit.StartBurning(5 * 20); // 5 seconds of burning

View File

@ -32,7 +32,7 @@ public:
protected:
void Explode(int a_BlockX, int a_BlockY, int a_BlockZ);
void Explode(Vector3i a_Block);
// cProjectileEntity overrides:
virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace) override;

View File

@ -19,9 +19,9 @@ cGhastFireballEntity::cGhastFireballEntity(cEntity * a_Creator, double a_X, doub
void cGhastFireballEntity::Explode(int a_BlockX, int a_BlockY, int a_BlockZ)
void cGhastFireballEntity::Explode(Vector3i a_Block)
{
m_World->DoExplosionAt(1, a_BlockX, a_BlockY, a_BlockZ, true, esGhastFireball, this);
m_World->DoExplosionAt(1, a_Block.x, a_Block.y, a_Block.z, true, esGhastFireball, this);
}
@ -31,7 +31,7 @@ void cGhastFireballEntity::Explode(int a_BlockX, int a_BlockY, int a_BlockZ)
void cGhastFireballEntity::OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace)
{
Destroy();
Explode((int)floor(a_HitPos.x), (int)floor(a_HitPos.y), (int)floor(a_HitPos.z));
Explode(a_HitPos.Floor());
}
@ -41,5 +41,5 @@ void cGhastFireballEntity::OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace
void cGhastFireballEntity::OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos)
{
Destroy();
Explode((int)floor(a_HitPos.x), (int)floor(a_HitPos.y), (int)floor(a_HitPos.z));
Explode(a_HitPos.Floor());
}

View File

@ -32,7 +32,7 @@ public:
protected:
void Explode(int a_BlockX, int a_BlockY, int a_BlockZ);
void Explode(Vector3i a_Block);
// cProjectileEntity overrides:
virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace) override;

View File

@ -46,6 +46,9 @@ public:
protected:
Byte m_Facing;
virtual void SpawnOn(cClientHandle & a_ClientHandle) override;
virtual void Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) override
{
@ -53,6 +56,7 @@ protected:
UNUSED(a_Chunk);
}
/** Converts protocol hanging item facing to eBlockFace values */
inline static eBlockFace ProtocolFaceToBlockFace(Byte a_ProtocolFace)
{
@ -77,6 +81,7 @@ protected:
return Dir;
}
/** Converts eBlockFace values to protocol hanging item faces */
inline static Byte BlockFaceToProtocolFace(eBlockFace a_BlockFace)
{
@ -89,7 +94,9 @@ protected:
case BLOCK_FACE_ZM: Dir = 2; break;
case BLOCK_FACE_XM: Dir = 1; break;
case BLOCK_FACE_XP: Dir = 3; break;
default:
case BLOCK_FACE_YP:
case BLOCK_FACE_YM:
case BLOCK_FACE_NONE:
{
// Uncomment when entities are initialised with their real data, instead of dummy values:
// LOGINFO("Invalid facing (%d) in a cHangingEntity, adjusting to BLOCK_FACE_XP.", a_BlockFace);
@ -97,13 +104,17 @@ protected:
Dir = cHangingEntity::BlockFaceToProtocolFace(BLOCK_FACE_XP);
}
#if !defined(__clang__)
default:
{
ASSERT(!"Unknown BLOCK_FACE");
return 0;
}
#endif
}
return Dir;
}
Byte m_Facing;
}; // tolua_export

View File

@ -62,7 +62,7 @@ void cItemFrame::KilledBy(TakeDamageInfo & a_TDI)
return;
}
if ((a_TDI.Attacker != nullptr) && a_TDI.Attacker->IsPlayer() && !((cPlayer *)a_TDI.Attacker)->IsGameModeCreative())
if ((a_TDI.Attacker != nullptr) && a_TDI.Attacker->IsPlayer() && !static_cast<cPlayer *>(a_TDI.Attacker)->IsGameModeCreative())
{
cItems Item;
Item.push_back(m_Item);
@ -83,7 +83,7 @@ void cItemFrame::KilledBy(TakeDamageInfo & a_TDI)
void cItemFrame::GetDrops(cItems & a_Items, cEntity * a_Killer)
{
if ((a_Killer != nullptr) && a_Killer->IsPlayer() && !((cPlayer *)a_Killer)->IsGameModeCreative())
if ((a_Killer != nullptr) && a_Killer->IsPlayer() && !static_cast<cPlayer *>(a_Killer)->IsGameModeCreative())
{
a_Items.push_back(cItem(E_ITEM_ITEM_FRAME));
}
@ -96,7 +96,7 @@ void cItemFrame::GetDrops(cItems & a_Items, cEntity * a_Killer)
void cItemFrame::SpawnOn(cClientHandle & a_ClientHandle)
{
super::SpawnOn(a_ClientHandle);
a_ClientHandle.SendSpawnObject(*this, 71, GetProtocolFacing(), (Byte)GetYaw(), (Byte)GetPitch());
a_ClientHandle.SendSpawnObject(*this, 71, GetProtocolFacing(), static_cast<Byte>(GetYaw()), static_cast<Byte>(GetPitch()));
a_ClientHandle.SendEntityMetadata(*this);
}

View File

@ -106,7 +106,7 @@ cMinecart::cMinecart(ePayload a_Payload, double a_X, double a_Y, double a_Z) :
void cMinecart::SpawnOn(cClientHandle & a_ClientHandle)
{
a_ClientHandle.SendSpawnVehicle(*this, 10, (char)m_Payload); // 10 = Minecarts
a_ClientHandle.SendSpawnVehicle(*this, 10, static_cast<char>(m_Payload)); // 10 = Minecarts
a_ClientHandle.SendEntityMetadata(*this);
}
@ -725,11 +725,11 @@ bool cMinecart::TestBlockCollision(NIBBLETYPE a_RailMeta)
{
if (GetSpeedZ() > 0)
{
BLOCKTYPE Block = m_World->GetBlock(POSX_TOINT, POSY_TOINT, (int)ceil(GetPosZ()));
BLOCKTYPE Block = m_World->GetBlock(POSX_TOINT, POSY_TOINT, static_cast<int>(ceil(GetPosZ())));
if (!IsBlockRail(Block) && cBlockInfo::IsSolid(Block))
{
// We could try to detect a block in front based purely on coordinates, but xoft made a bounding box system - why not use? :P
cBoundingBox bbBlock(Vector3d(POSX_TOINT, POSY_TOINT, (int)ceil(GetPosZ())), 0.5, 1);
cBoundingBox bbBlock(Vector3d(POSX_TOINT, POSY_TOINT, static_cast<int>(ceil(GetPosZ()))), 0.5, 1);
cBoundingBox bbMinecart(Vector3d(GetPosX(), floor(GetPosY()), GetPosZ()), GetWidth() / 2, GetHeight());
if (bbBlock.DoesIntersect(bbMinecart))
@ -762,10 +762,10 @@ bool cMinecart::TestBlockCollision(NIBBLETYPE a_RailMeta)
{
if (GetSpeedX() > 0)
{
BLOCKTYPE Block = m_World->GetBlock((int)ceil(GetPosX()), POSY_TOINT, POSZ_TOINT);
BLOCKTYPE Block = m_World->GetBlock(static_cast<int>(ceil(GetPosX())), POSY_TOINT, POSZ_TOINT);
if (!IsBlockRail(Block) && cBlockInfo::IsSolid(Block))
{
cBoundingBox bbBlock(Vector3d((int)ceil(GetPosX()), POSY_TOINT, POSZ_TOINT), 0.5, 1);
cBoundingBox bbBlock(Vector3d(static_cast<int>(ceil(GetPosX())), POSY_TOINT, POSZ_TOINT), 0.5, 1);
cBoundingBox bbMinecart(Vector3d(GetPosX(), floor(GetPosY()), GetPosZ()), GetWidth() / 2, GetHeight());
if (bbBlock.DoesIntersect(bbMinecart))
@ -1003,7 +1003,7 @@ bool cMinecart::TestEntityCollision(NIBBLETYPE a_RailMeta)
bool cMinecart::DoTakeDamage(TakeDamageInfo & TDI)
{
if ((TDI.Attacker != nullptr) && TDI.Attacker->IsPlayer() && ((cPlayer *)TDI.Attacker)->IsGameModeCreative())
if ((TDI.Attacker != nullptr) && TDI.Attacker->IsPlayer() && static_cast<cPlayer *>(TDI.Attacker)->IsGameModeCreative())
{
Destroy();
TDI.FinalDamage = GetMaxHealth(); // Instant hit for creative
@ -1051,11 +1051,6 @@ bool cMinecart::DoTakeDamage(TakeDamageInfo & TDI)
Drops.push_back(cItem(E_ITEM_MINECART_WITH_HOPPER, 1, 0));
break;
}
default:
{
ASSERT(!"Unhandled minecart type when spawning pickup!");
return true;
}
}
m_World->SpawnItemPickups(Drops, GetPosX(), GetPosY(), GetPosZ());

View File

@ -33,7 +33,7 @@ void cPainting::SpawnOn(cClientHandle & a_Client)
void cPainting::GetDrops(cItems & a_Items, cEntity * a_Killer)
{
if ((a_Killer != nullptr) && a_Killer->IsPlayer() && !((cPlayer *)a_Killer)->IsGameModeCreative())
if ((a_Killer != nullptr) && a_Killer->IsPlayer() && !static_cast<cPlayer *>(a_Killer)->IsGameModeCreative())
{
a_Items.push_back(cItem(E_ITEM_PAINTING));
}

View File

@ -75,10 +75,10 @@ void cPawn::AddEntityEffect(cEntityEffect::eType a_EffectType, int a_Duration, s
{
return;
}
a_Duration = (int)(a_Duration * a_DistanceModifier);
a_Duration = static_cast<int>(a_Duration * a_DistanceModifier);
m_EntityEffects[a_EffectType] = cEntityEffect::CreateEntityEffect(a_EffectType, a_Duration, a_Intensity, a_DistanceModifier);
m_World->BroadcastEntityEffect(*this, a_EffectType, a_Intensity, a_Duration);
m_World->BroadcastEntityEffect(*this, a_EffectType, a_Intensity, static_cast<short>(a_Duration));
m_EntityEffects[a_EffectType]->OnActivate(*this);
}

View File

@ -38,7 +38,7 @@ public:
Vector3d EntityPos = a_Entity->GetPosition();
double Distance = (EntityPos - m_Position).Length();
cItem & Item = ((cPickup *)a_Entity)->GetItem();
cItem & Item = static_cast<cPickup *>(a_Entity)->GetItem();
if ((Distance < 1.2) && Item.IsEqual(m_Pickup->GetItem()))
{
short CombineCount = Item.m_ItemCount;
@ -52,7 +52,7 @@ public:
return false;
}
m_Pickup->GetItem().AddCount((char)CombineCount);
m_Pickup->GetItem().AddCount(static_cast<char>(CombineCount));
Item.m_ItemCount -= CombineCount;
if (Item.m_ItemCount <= 0)
@ -228,8 +228,9 @@ bool cPickup::CollectedBy(cPlayer & a_Dest)
m_Item.m_ItemCount -= NumAdded;
m_World->BroadcastCollectEntity(*this, a_Dest);
// Also send the "pop" sound effect with a somewhat random pitch (fast-random using EntityID ;)
m_World->BroadcastSoundEffect("random.pop", GetPosX(), GetPosY(), GetPosZ(), 0.5, (float)(0.75 + ((float)((GetUniqueID() * 23) % 32)) / 64));
m_World->BroadcastSoundEffect("random.pop", GetPosX(), GetPosY(), GetPosZ(), 0.5, (0.75f + (static_cast<float>((GetUniqueID() * 23) % 32)) / 64));
if (m_Item.m_ItemCount <= 0)
{
// All of the pickup has been collected, schedule the pickup for destroying

View File

@ -1206,20 +1206,7 @@ void cPlayer::SetGameMode(eGameMode a_GameMode)
m_GameMode = a_GameMode;
m_ClientHandle->SendGameMode(a_GameMode);
if (!(IsGameModeCreative() || IsGameModeSpectator()))
{
SetFlying(false);
SetCanFly(false);
}
if (IsGameModeSpectator() && IsVisible())
{
SetVisible(false);
}
else if (!IsVisible())
{
SetVisible(true);
}
SetCapabilities();
m_World->BroadcastPlayerListUpdateGameMode(*this);
}
@ -1231,6 +1218,30 @@ void cPlayer::SetGameMode(eGameMode a_GameMode)
void cPlayer::LoginSetGameMode( eGameMode a_GameMode)
{
m_GameMode = a_GameMode;
SetCapabilities();
}
void cPlayer::SetCapabilities()
{
if (!IsGameModeCreative() || IsGameModeSpectator())
{
SetFlying(false);
SetCanFly(false);
}
if (IsGameModeSpectator())
{
SetVisible(false);
}
else
{
SetVisible(true);
}
}
@ -2372,7 +2383,3 @@ AString cPlayer::GetUUIDFileName(const AString & a_UUID)
res.append(".json");
return res;
}

View File

@ -162,6 +162,12 @@ public:
*/
void SetGameMode(eGameMode a_GameMode);
// Sets the current gamemode, doesn't check validity, doesn't send update packets to client
void LoginSetGameMode(eGameMode a_GameMode);
// Updates player's capabilities - flying, visibility, etc. from their gamemode.
void SetCapabilities();
/** Returns true if the player is in Creative mode, either explicitly, or by inheriting from current world */
bool IsGameModeCreative(void) const;
@ -198,9 +204,6 @@ public:
void SetIP(const AString & a_IP);
// Sets the current gamemode, doesn't check validity, doesn't send update packets to client
void LoginSetGameMode(eGameMode a_GameMode);
/** Forces the player to move in the given direction.
@deprecated Use SetSpeed instead. */
void ForceSetSpeed(const Vector3d & a_Speed); // tolua_export
@ -666,7 +669,3 @@ protected:
This can be used both for online and offline UUIDs. */
AString GetUUIDFileName(const AString & a_UUID);
} ; // tolua_export

View File

@ -30,7 +30,7 @@
/// Converts an angle in radians into a byte representation used by the network protocol
#define ANGLE_TO_PROTO(X) (Byte)(X * 255 / 360)
#define ANGLE_TO_PROTO(X) static_cast<Byte>(X * 255 / 360)
@ -222,7 +222,7 @@ cProjectileEntity::cProjectileEntity(eKind a_Kind, cEntity * a_Creator, double a
m_ProjectileKind(a_Kind),
m_CreatorData(
((a_Creator != nullptr) ? a_Creator->GetUniqueID() : cEntity::INVALID_ID),
((a_Creator != nullptr) ? (a_Creator->IsPlayer() ? ((cPlayer *)a_Creator)->GetName() : "") : ""),
((a_Creator != nullptr) ? (a_Creator->IsPlayer() ? static_cast<cPlayer *>(a_Creator)->GetName() : "") : ""),
((a_Creator != nullptr) ? a_Creator->GetEquippedWeapon().m_Enchantments : cEnchantments())
),
m_IsInGround(false)
@ -238,7 +238,7 @@ cProjectileEntity::cProjectileEntity(eKind a_Kind, cEntity * a_Creator, double a
cProjectileEntity::cProjectileEntity(eKind a_Kind, cEntity * a_Creator, const Vector3d & a_Pos, const Vector3d & a_Speed, double a_Width, double a_Height) :
super(etProjectile, a_Pos.x, a_Pos.y, a_Pos.z, a_Width, a_Height),
m_ProjectileKind(a_Kind),
m_CreatorData(a_Creator->GetUniqueID(), a_Creator->IsPlayer() ? ((cPlayer *)a_Creator)->GetName() : "", a_Creator->GetEquippedWeapon().m_Enchantments),
m_CreatorData(a_Creator->GetUniqueID(), a_Creator->IsPlayer() ? static_cast<cPlayer *>(a_Creator)->GetName() : "", a_Creator->GetEquippedWeapon().m_Enchantments),
m_IsInGround(false)
{
SetSpeed(a_Speed);
@ -281,6 +281,7 @@ cProjectileEntity * cProjectileEntity::Create(eKind a_Kind, cEntity * a_Creator,
return new cFireworkEntity(a_Creator, a_X, a_Y, a_Z, *a_Item);
}
case pkFishingFloat: break;
}
LOGWARNING("%s: Unknown projectile kind: %d", __FUNCTION__, a_Kind);

View File

@ -9,7 +9,7 @@
/// Converts an angle in radians into a byte representation used by the network protocol
#define ANGLE_TO_PROTO(X) (Byte)(X * 255 / 360)
#define ANGLE_TO_PROTO(X) static_cast<Byte>(X * 255 / 360)
////////////////////////////////////////////////////////////////////////////////
// cSplashPotionEntityCallback:
@ -51,7 +51,7 @@ public:
double Reduction = -0.25 * SplashDistance + 1.0;
Reduction = std::max(Reduction, 0.0);
((cPawn *) a_Entity)->AddEntityEffect(m_EntityEffectType, m_EntityEffect.GetDuration(), m_EntityEffect.GetIntensity(), Reduction);
static_cast<cPawn *>(a_Entity)->AddEntityEffect(m_EntityEffectType, m_EntityEffect.GetDuration(), m_EntityEffect.GetIntensity(), Reduction);
return false;
}
@ -116,7 +116,13 @@ void cSplashPotionEntity::Splash(const Vector3d & a_HitPos)
cSplashPotionCallback Callback(a_HitPos, m_EntityEffectType, m_EntityEffect);
m_World->ForEachEntity(Callback);
m_World->BroadcastSoundParticleEffect(2002, (int)floor(a_HitPos.x), (int)floor(a_HitPos.y), (int)floor(a_HitPos.z), m_PotionColor);
m_World->BroadcastSoundParticleEffect(
2002,
FloorC(a_HitPos.x),
FloorC(a_HitPos.y),
FloorC(a_HitPos.z),
m_PotionColor
);
}

View File

@ -77,9 +77,9 @@ void cThrownEnderPearlEntity::TeleportCreator(const Vector3d & a_HitPos)
class cProjectileCreatorCallbackForPlayers : public cPlayerListCallback
{
public:
cProjectileCreatorCallbackForPlayers(cEntity * a_Attacker, Vector3i a_HitPos) :
cProjectileCreatorCallbackForPlayers(cEntity * a_Attacker, Vector3i a_CallbackHitPos) :
m_Attacker(a_Attacker),
m_HitPos(a_HitPos)
m_HitPos(a_CallbackHitPos)
{
}

View File

@ -32,7 +32,7 @@ void cThrownSnowballEntity::OnHitEntity(cEntity & a_EntityHit, const Vector3d &
int TotalDamage = 0;
if (a_EntityHit.IsMob())
{
eMonsterType MobType = ((cMonster &) a_EntityHit).GetMobType();
eMonsterType MobType = static_cast<cMonster &>(a_EntityHit).GetMobType();
if (MobType == mtBlaze)
{
TotalDamage = 3;

View File

@ -77,7 +77,7 @@ void cFurnaceRecipe::ReloadRecipes(void)
size_t FirstCommentSymbol = ParsingLine.find('#');
if ((FirstCommentSymbol != AString::npos) && (FirstCommentSymbol != 0))
{
ParsingLine.erase(ParsingLine.begin() + (const long)FirstCommentSymbol, ParsingLine.end());
ParsingLine.erase(ParsingLine.begin() + static_cast<const long>(FirstCommentSymbol), ParsingLine.end());
}
switch (ParsingLine[0])
@ -121,7 +121,7 @@ void cFurnaceRecipe::AddFuelFromLine(const AString & a_Line, unsigned int a_Line
const AStringVector & Sides = StringSplit(Line, "=");
if (Sides.size() != 2)
{
LOGWARNING("furnace.txt: line %d: A single '=' was expected, got %d", a_LineNum, (int)Sides.size() - 1);
LOGWARNING("furnace.txt: line %d: A single '=' was expected, got " SIZE_T_FMT, a_LineNum, Sides.size() - 1);
LOGINFO("Offending line: \"%s\"", a_Line.c_str());
return;
}
@ -163,7 +163,7 @@ void cFurnaceRecipe::AddRecipeFromLine(const AString & a_Line, unsigned int a_Li
const AStringVector & Sides = StringSplit(Line, "=");
if (Sides.size() != 2)
{
LOGWARNING("furnace.txt: line %d: A single '=' was expected, got %d", a_LineNum, (int)Sides.size() - 1);
LOGWARNING("furnace.txt: line %d: A single '=' was expected, got " SIZE_T_FMT, a_LineNum, Sides.size() - 1);
LOGINFO("Offending line: \"%s\"", a_Line.c_str());
return;
}

View File

@ -49,16 +49,16 @@ void cBioGenConstant::InitializeBiomeGen(cIniFile & a_IniFile)
////////////////////////////////////////////////////////////////////////////////
// cBioGenCache:
cBioGenCache::cBioGenCache(cBiomeGenPtr a_BioGenToCache, int a_CacheSize) :
cBioGenCache::cBioGenCache(cBiomeGenPtr a_BioGenToCache, size_t a_CacheSize) :
m_BioGenToCache(a_BioGenToCache),
m_CacheSize(a_CacheSize),
m_CacheOrder(new int[a_CacheSize]),
m_CacheOrder(new size_t[a_CacheSize]),
m_CacheData(new sCacheData[a_CacheSize]),
m_NumHits(0),
m_NumMisses(0),
m_TotalChain(0)
{
for (int i = 0; i < m_CacheSize; i++)
for (size_t i = 0; i < m_CacheSize; i++)
{
m_CacheOrder[i] = i;
m_CacheData[i].m_ChunkX = 0x7fffffff;
@ -90,7 +90,7 @@ void cBioGenCache::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a
LOGD("BioGenCache: Avg cache chain length: %.2f", (float)m_TotalChain / m_NumHits);
}
for (int i = 0; i < m_CacheSize; i++)
for (size_t i = 0; i < m_CacheSize; i++)
{
if (
(m_CacheData[m_CacheOrder[i]].m_ChunkX != a_ChunkX) ||
@ -100,10 +100,10 @@ void cBioGenCache::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a
continue;
}
// Found it in the cache
int Idx = m_CacheOrder[i];
size_t Idx = m_CacheOrder[i];
// Move to front:
for (int j = i; j > 0; j--)
for (size_t j = i; j > 0; j--)
{
m_CacheOrder[j] = m_CacheOrder[j - 1];
}
@ -122,8 +122,8 @@ void cBioGenCache::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a
m_BioGenToCache->GenBiomes(a_ChunkX, a_ChunkZ, a_BiomeMap);
// Insert it as the first item in the MRU order:
int Idx = m_CacheOrder[m_CacheSize - 1];
for (int i = m_CacheSize - 1; i > 0; i--)
size_t Idx = m_CacheOrder[m_CacheSize - 1];
for (size_t i = m_CacheSize - 1; i > 0; i--)
{
m_CacheOrder[i] = m_CacheOrder[i - 1];
} // for i - m_CacheOrder[]
@ -278,7 +278,7 @@ void cBioGenCheckerboard::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::Biome
for (int x = 0; x < cChunkDef::Width; x++)
{
int Add = cChunkDef::Width * a_ChunkX + x;
int BiomeIdx = (((Base + Add / m_BiomeSize) % m_BiomesCount) + m_BiomesCount) % m_BiomesCount; // Need to add and modulo twice because of negative numbers
size_t BiomeIdx = static_cast<size_t>((((Base + Add / m_BiomeSize) % m_BiomesCount) + m_BiomesCount) % m_BiomesCount); // Need to add and modulo twice because of negative numbers
a_BiomeMap[x + cChunkDef::Width * z] = m_Biomes[BiomeIdx];
}
}
@ -314,7 +314,7 @@ void cBioGenVoronoi::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap &
for (int x = 0; x < cChunkDef::Width; x++)
{
int VoronoiCellValue = m_Voronoi.GetValueAt(BaseX + x, AbsoluteZ) / 8;
cChunkDef::SetBiome(a_BiomeMap, x, z, m_Biomes[VoronoiCellValue % m_BiomesCount]);
cChunkDef::SetBiome(a_BiomeMap, x, z, m_Biomes[static_cast<size_t>(VoronoiCellValue % m_BiomesCount)]);
} // for x
} // for z
}
@ -363,7 +363,7 @@ void cBioGenDistortedVoronoi::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::B
for (int x = 0; x < cChunkDef::Width; x++)
{
int VoronoiCellValue = m_Voronoi.GetValueAt(DistortX[x][z], DistortZ[x][z]) / 8;
cChunkDef::SetBiome(a_BiomeMap, x, z, m_Biomes[VoronoiCellValue % m_BiomesCount]);
cChunkDef::SetBiome(a_BiomeMap, x, z, m_Biomes[static_cast<size_t>(VoronoiCellValue % m_BiomesCount)]);
} // for x
} // for z
}
@ -785,7 +785,7 @@ void cBioGenTwoLevel::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap
{
int SeedX, SeedZ, MinDist2;
int BiomeGroup = m_VoronoiLarge.GetValueAt(DistortX[x][z], DistortZ[x][z], SeedX, SeedZ, MinDist2) / 7;
int BiomeIdx = m_VoronoiSmall.GetValueAt(DistortX[x][z], DistortZ[x][z], SeedX, SeedZ, MinDist2) / 11;
size_t BiomeIdx = static_cast<size_t>(m_VoronoiSmall.GetValueAt(DistortX[x][z], DistortZ[x][z], SeedX, SeedZ, MinDist2) / 11);
int MinDist1 = (DistortX[x][z] - SeedX) * (DistortX[x][z] - SeedX) + (DistortZ[x][z] - SeedZ) * (DistortZ[x][z] - SeedZ);
cChunkDef::SetBiome(a_BiomeMap, x, z, SelectBiome(BiomeGroup, BiomeIdx, (MinDist1 < MinDist2 / 4) ? 1 : 0));
}
@ -796,7 +796,7 @@ void cBioGenTwoLevel::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap
EMCSBiome cBioGenTwoLevel::SelectBiome(int a_BiomeGroup, int a_BiomeIdx, int a_DistLevel)
EMCSBiome cBioGenTwoLevel::SelectBiome(int a_BiomeGroup, size_t a_BiomeIdx, int a_DistLevel)
{
// TODO: Move this into settings
struct BiomeLevels
@ -900,7 +900,7 @@ EMCSBiome cBioGenTwoLevel::SelectBiome(int a_BiomeGroup, int a_BiomeIdx, int a_D
{ bgMesa, ARRAYCOUNT(bgMesa), },
{ bgDenseTrees, ARRAYCOUNT(bgDenseTrees), },
} ;
size_t Group = a_BiomeGroup % ARRAYCOUNT(BiomeGroups);
size_t Group = static_cast<size_t>(a_BiomeGroup) % ARRAYCOUNT(BiomeGroups);
size_t Index = a_BiomeIdx % BiomeGroups[Group].Count;
return (a_DistLevel > 0) ? BiomeGroups[Group].Biomes[Index].InnerBiome : BiomeGroups[Group].Biomes[Index].OuterBiome;
}

View File

@ -48,7 +48,7 @@ class cBioGenCache :
typedef cBiomeGen super;
public:
cBioGenCache(cBiomeGenPtr a_BioGenToCache, int a_CacheSize);
cBioGenCache(cBiomeGenPtr a_BioGenToCache, size_t a_CacheSize);
virtual ~cBioGenCache();
protected:
@ -63,8 +63,8 @@ protected:
} ;
// To avoid moving large amounts of data for the MRU behavior, we MRU-ize indices to an array of the actual data
int m_CacheSize;
int * m_CacheOrder; // MRU-ized order, indices into m_CacheData array
size_t m_CacheSize;
size_t * m_CacheOrder; // MRU-ized order, indices into m_CacheData array
sCacheData * m_CacheData; // m_CacheData[m_CacheOrder[0]] is the most recently used
// Cache statistics
@ -311,7 +311,7 @@ protected:
/// Selects biome from the specified biome group, based on the specified index.
/// Note that both params may overflow
/// a_DistLevel is either 0 or 1; zero when it is at the edge of the small Voronoi cell, 1 near the center
EMCSBiome SelectBiome(int a_BiomeGroup, int a_BiomeIdx, int a_DistLevel);
EMCSBiome SelectBiome(int a_BiomeGroup, size_t a_BiomeIdx, int a_DistLevel);
} ;

View File

@ -72,6 +72,32 @@ SET (HDRS
VillageGen.h
)
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
set_source_files_properties(BioGen.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=switch-enum -Wno-error=old-style-cast")
set_source_files_properties(Caves.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(ChunkGenerator.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(CompoGen.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(CompoGenBiomal.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors -Wno-error=old-style-cast")
set_source_files_properties(ComposableGenerator.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=switch-enum -Wno-error=old-style-cast")
set_source_files_properties(DistortedHeightmap.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(EndGen.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(FinishGen.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=switch-enum -Wno-error=switch")
set_source_files_properties(HeiGen.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(NetherFortGen.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors")
set_source_files_properties(Noise3DGenerator.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(PieceGenerator.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors")
set_source_files_properties(Prefab.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors")
set_source_files_properties(RainbowRoadsGen.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors")
set_source_files_properties(Ravines.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(RoughRavines.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=float-equal -Wno-error=old-style-cast")
set_source_files_properties(StructGen.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=switch-enum -Wno-error=switch -Wno-error=old-style-cast")
set_source_files_properties(ShapeGen.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(TestRailsGen.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors")
set_source_files_properties(TwoHeights.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=old-style-cast")
set_source_files_properties(UnderwaterBaseGen.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors -Wno-error=switch-enum")
set_source_files_properties(VillageGen.cpp PROPERTIES COMPILE_FLAGS "-Wno-error=global-constructors -Wno-error=switch-enum")
endif()
if(NOT MSVC)
add_library(Generating ${SRCS} ${HDRS})

View File

@ -134,7 +134,7 @@ EMCSBiome cChunkDesc::GetBiome(int a_RelX, int a_RelZ)
void cChunkDesc::SetHeight(int a_RelX, int a_RelZ, int a_Height)
void cChunkDesc::SetHeight(int a_RelX, int a_RelZ, HEIGHTTYPE a_Height)
{
cChunkDef::SetHeight(m_HeightMap, a_RelX, a_RelZ, a_Height);
}
@ -143,7 +143,7 @@ void cChunkDesc::SetHeight(int a_RelX, int a_RelZ, int a_Height)
int cChunkDesc::GetHeight(int a_RelX, int a_RelZ)
HEIGHTTYPE cChunkDesc::GetHeight(int a_RelX, int a_RelZ)
{
return cChunkDef::GetHeight(m_HeightMap, a_RelX, a_RelZ);
}
@ -158,7 +158,7 @@ void cChunkDesc::SetHeightFromShape(const Shape & a_Shape)
{
for (int x = 0; x < cChunkDef::Width; x++)
{
for (int y = cChunkDef::Height - 1; y > 0; y--)
for (HEIGHTTYPE y = cChunkDef::Height - 1; y > 0; y--)
{
if (a_Shape[y + x * 256 + z * 16 * 256] != 0)
{
@ -612,8 +612,8 @@ void cChunkDesc::UpdateHeightmap(void)
{
for (int z = 0; z < cChunkDef::Width; z++)
{
int Height = 0;
for (int y = cChunkDef::Height - 1; y > 0; y--)
HEIGHTTYPE Height = 0;
for (HEIGHTTYPE y = cChunkDef::Height - 1; y > 0; y--)
{
BLOCKTYPE BlockType = GetBlockType(x, y, z);
if (BlockType != E_BLOCK_AIR)
@ -636,7 +636,7 @@ void cChunkDesc::CompressBlockMetas(cChunkDef::BlockNibbles & a_DestMetas)
const NIBBLETYPE * AreaMetas = m_BlockArea.GetBlockMetas();
for (size_t i = 0; i < ARRAYCOUNT(a_DestMetas); i++)
{
a_DestMetas[i] = AreaMetas[2 * i] | (AreaMetas[2 * i + 1] << 4);
a_DestMetas[i] = static_cast<NIBBLETYPE>(AreaMetas[2 * i] | (AreaMetas[2 * i + 1] << 4));
}
}

View File

@ -65,8 +65,8 @@ public:
// These operate on the heightmap, so they could get out of sync with the data
// Use UpdateHeightmap() to re-calculate heightmap from the block data
void SetHeight(int a_RelX, int a_RelZ, int a_Height);
int GetHeight(int a_RelX, int a_RelZ);
void SetHeight(int a_RelX, int a_RelZ, HEIGHTTYPE a_Height);
HEIGHTTYPE GetHeight(int a_RelX, int a_RelZ);
// tolua_end
@ -204,10 +204,10 @@ public:
// Accessors used by cChunkGenerator::Generator descendants:
inline cChunkDef::BiomeMap & GetBiomeMap (void) { return m_BiomeMap; }
inline cChunkDef::BlockTypes & GetBlockTypes (void) { return *((cChunkDef::BlockTypes *)m_BlockArea.GetBlockTypes()); }
inline cChunkDef::BlockTypes & GetBlockTypes (void) { return *(reinterpret_cast<cChunkDef::BlockTypes *>(m_BlockArea.GetBlockTypes())); }
// CANNOT, different compression!
// inline cChunkDef::BlockNibbles & GetBlockMetas (void) { return *((cChunkDef::BlockNibbles *)m_BlockArea.GetBlockMetas()); }
inline BlockNibbleBytes & GetBlockMetasUncompressed(void) { return *((BlockNibbleBytes *)m_BlockArea.GetBlockMetas()); }
inline BlockNibbleBytes & GetBlockMetasUncompressed(void) { return *(reinterpret_cast<BlockNibbleBytes *>(m_BlockArea.GetBlockMetas())); }
inline cChunkDef::HeightMap & GetHeightMap (void) { return m_HeightMap; }
inline cEntityList & GetEntities (void) { return m_Entities; }
inline cBlockEntityList & GetBlockEntities (void) { return m_BlockEntities; }

View File

@ -4,6 +4,9 @@
// Implements the cCompoGenBiomal class representing the biome-aware composition generator
#include "Globals.h"
#include "CompoGenBiomal.h"
#include "ComposableGenerator.h"
#include "../IniFile.h"
#include "../Noise/Noise.h"
@ -192,7 +195,7 @@ public:
protected:
/** The block height at which water is generated instead of air. */
int m_SeaLevel;
HEIGHTTYPE m_SeaLevel;
/** The pattern used for mesa biomes. Initialized by seed on generator creation. */
cPattern::BlockInfo m_MesaPattern[2 * cChunkDef::Height];
@ -221,7 +224,7 @@ protected:
virtual void InitializeCompoGen(cIniFile & a_IniFile) override
{
m_SeaLevel = a_IniFile.GetValueSetI("Generator", "SeaLevel", m_SeaLevel);
m_SeaLevel = static_cast<HEIGHTTYPE>(a_IniFile.GetValueSetI("Generator", "SeaLevel", m_SeaLevel));
}
@ -231,7 +234,7 @@ protected:
{
// In a loop, choose whether to use one, two or three layers of stained clay, then choose a color and width for each layer
// Separate each group with another layer of hardened clay
cNoise patternNoise((unsigned)a_Seed);
cNoise patternNoise(a_Seed);
static NIBBLETYPE allowedColors[] =
{
E_META_STAINED_CLAY_YELLOW,
@ -265,8 +268,8 @@ protected:
rnd /= 2;
for (int lay = 0; lay < numLayers; lay++)
{
int numBlocks = layerSizes[(rnd % ARRAYCOUNT(layerSizes))];
NIBBLETYPE Color = allowedColors[(rnd / 4) % ARRAYCOUNT(allowedColors)];
int numBlocks = layerSizes[(static_cast<size_t>(rnd) % ARRAYCOUNT(layerSizes))];
NIBBLETYPE Color = allowedColors[static_cast<size_t>(rnd / 4) % ARRAYCOUNT(allowedColors)];
if (
((numBlocks == 3) && (numLayers == 2)) || // In two-layer mode disallow the 3-high layers:
(Color == E_META_STAINED_CLAY_WHITE)) // White stained clay can ever be only 1 block high
@ -411,7 +414,12 @@ protected:
FillColumnPattern(a_ChunkDesc, a_RelX, a_RelZ, Pattern, a_ShapeColumn);
return;
}
default:
case biInvalidBiome:
case biHell:
case biSky:
case biNumBiomes:
case biVariant:
case biNumVariantBiomes:
{
ASSERT(!"Unhandled biome");
return;
@ -427,7 +435,7 @@ protected:
{
bool HasHadWater = false;
int PatternIdx = 0;
int top = std::max(m_SeaLevel, a_ChunkDesc.GetHeight(a_RelX, a_RelZ));
HEIGHTTYPE top = std::max(m_SeaLevel, a_ChunkDesc.GetHeight(a_RelX, a_RelZ));
for (int y = top; y > 0; y--)
{
if (a_ShapeColumn[y] > 0)

View File

@ -221,11 +221,11 @@ void cComposableGenerator::InitBiomeGen(cIniFile & a_IniFile)
if (MultiCacheLength > 0)
{
LOGD("Enabling multicache for biomegen of length %d.", MultiCacheLength);
m_BiomeGen = cBiomeGenPtr(new cBioGenMulticache(m_BiomeGen, CacheSize, MultiCacheLength));
m_BiomeGen = cBiomeGenPtr(new cBioGenMulticache(m_BiomeGen, static_cast<size_t>(CacheSize), static_cast<size_t>(MultiCacheLength)));
}
else
{
m_BiomeGen = cBiomeGenPtr(new cBioGenCache(m_BiomeGen, CacheSize));
m_BiomeGen = cBiomeGenPtr(new cBioGenCache(m_BiomeGen, static_cast<size_t>(CacheSize)));
}
}

Some files were not shown because too many files have changed in this diff Show More