Infinite world, LuaJIT mod API, WorldEdit port, skins and music
- Infinite world: streamed chunk cache, multi-region storage (old chunks.dat still loads), per-chunk entity/tile entity persistence, client chunk streaming, protocol version 10, view-distance server property - LuaJIT mod host (mods/, lua/prelude.lua) with events, commands, world and player API; WorldEdit command set ported to it (mods/worldedit) - /skin command, SetSkinPacket and bundled skins - OGG music player (data/music is ignored, tools/convert-music.ps1) - package-windows.ps1 builds client and dedicated server for Windows Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
7
.gitignore
vendored
|
|
@ -200,3 +200,10 @@ games/
|
|||
vcpkg_installed/
|
||||
.cache/
|
||||
conan/
|
||||
|
||||
# Local build output and test scratch
|
||||
dist/
|
||||
_test/
|
||||
|
||||
# Music (converted from your own FLAC files with tools/convert-music.ps1)
|
||||
data/music/*.ogg
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
|
|||
set(CMAKE_POLICY_VERSION_MINIMUM 3.10)
|
||||
|
||||
include(cmake/EnumOption.cmake)
|
||||
include(cmake/LuaJIT.cmake)
|
||||
|
||||
if(EMSCRIPTEN)
|
||||
# When configuring web builds with "emcmake cmake -B build -S .", set PLATFORM to Web by default
|
||||
|
|
@ -99,6 +100,16 @@ else()
|
|||
)
|
||||
endif()
|
||||
|
||||
if(NOT ${PLATFORM} MATCHES "Web")
|
||||
# single file OGG Vorbis decoder used by the music player
|
||||
CPMAddPackage(
|
||||
NAME "stb"
|
||||
GIT_REPOSITORY "https://github.com/nothings/stb.git"
|
||||
GIT_TAG "a7d4c2175630e1ea5b6f8dd00ab96fed0b97b96d"
|
||||
DOWNLOAD_ONLY YES
|
||||
)
|
||||
endif()
|
||||
|
||||
CPMAddPackage(
|
||||
NAME "openal"
|
||||
GIT_REPOSITORY "https://github.com/kcat/openal-soft.git"
|
||||
|
|
@ -196,6 +207,7 @@ file(GLOB SERVER_SOURCES
|
|||
"src/world/level/biome/Biome.cpp"
|
||||
"src/world/level/biome/BiomeSource.cpp"
|
||||
|
||||
"src/world/level/chunk/ChunkCache.cpp"
|
||||
"src/world/level/chunk/LevelChunk.cpp"
|
||||
|
||||
"src/world/level/dimension/Dimension.cpp"
|
||||
|
|
@ -217,6 +229,7 @@ file(GLOB SERVER_SOURCES
|
|||
|
||||
"src/world/phys/HitResult.cpp"
|
||||
"src/commands/*.cpp"
|
||||
"src/lua/*.cpp"
|
||||
)
|
||||
|
||||
file(GLOB CLIENT_SOURCES
|
||||
|
|
@ -302,10 +315,11 @@ file(GLOB CLIENT_SOURCES
|
|||
"src/main.cpp"
|
||||
|
||||
"src/commands/*.cpp"
|
||||
"src/lua/*.cpp"
|
||||
)
|
||||
|
||||
if (${PLATFORM} STREQUAL "Desktop")
|
||||
list(APPEND CLIENT_SOURCES glad/src/glad.c)
|
||||
list(APPEND CLIENT_SOURCES glad/src/glad.c "${stb_SOURCE_DIR}/stb_vorbis.c")
|
||||
endif()
|
||||
|
||||
# Server
|
||||
|
|
@ -318,7 +332,13 @@ target_include_directories("${PROJECT_NAME}-server" PUBLIC
|
|||
"project/lib_projects/raknet/jni/RaknetSources"
|
||||
)
|
||||
|
||||
target_link_libraries("${PROJECT_NAME}-server" ${CMAKE_THREAD_LIBS_INIT} ${EXTRA_LIBS})
|
||||
target_link_libraries("${PROJECT_NAME}-server" ${CMAKE_THREAD_LIBS_INIT} ${EXTRA_LIBS} luajit)
|
||||
|
||||
# Lua API (prelude) and bundled mods are shipped next to the executables
|
||||
add_custom_command(TARGET "${PROJECT_NAME}-server" POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/lua" "$<TARGET_FILE_DIR:${PROJECT_NAME}-server>/lua"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/mods" "$<TARGET_FILE_DIR:${PROJECT_NAME}-server>/mods"
|
||||
)
|
||||
|
||||
add_executable(${PROJECT_NAME} ${CLIENT_SOURCES})
|
||||
|
||||
|
|
@ -333,6 +353,7 @@ target_include_directories(${PROJECT_NAME} PUBLIC
|
|||
"${CMAKE_SOURCE_DIR}/src"
|
||||
"${openal_SOURCE_DIR}/include"
|
||||
"${glfw_SOURCE_DIR}/include"
|
||||
"${stb_SOURCE_DIR}"
|
||||
"lib/include"
|
||||
)
|
||||
|
||||
|
|
@ -381,7 +402,7 @@ endif()
|
|||
|
||||
# Client
|
||||
target_compile_definitions(${PROJECT_NAME} PUBLIC "OPENGL_ES" "NO_EGL" ${PLATFORM})
|
||||
target_link_libraries(${PROJECT_NAME} zlib ${PNG_LIB} OpenAL::OpenAL glfw ${EXTRA_LIBS})
|
||||
target_link_libraries(${PROJECT_NAME} zlib ${PNG_LIB} OpenAL::OpenAL glfw ${EXTRA_LIBS} luajit)
|
||||
|
||||
if (OpenSSL_FOUND)
|
||||
target_link_libraries(${PROJECT_NAME} OpenSSL::SSL OpenSSL::Crypto)
|
||||
|
|
@ -402,6 +423,8 @@ if(NOT ${PLATFORM} MATCHES "Web")
|
|||
TARGET ${PROJECT_NAME}
|
||||
POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/data" $<TARGET_FILE_DIR:${PROJECT_NAME}>/data
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/lua" $<TARGET_FILE_DIR:${PROJECT_NAME}>/lua
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/mods" $<TARGET_FILE_DIR:${PROJECT_NAME}>/mods
|
||||
)
|
||||
else()
|
||||
add_custom_command(
|
||||
|
|
|
|||
19
README.md
|
|
@ -24,6 +24,25 @@ This project aims to preserve and improve this early version of Minecraft PE.
|
|||
|
||||
</p>
|
||||
|
||||
|
||||
# This fork: infinite world, Lua mods, WorldEdit, skins, music
|
||||
|
||||
- **Infinite world** - chunks are generated, saved (region files `r.<x>.<z>.dat`, old `chunks.dat` worlds still load) and unloaded around the players. Dedicated server: `view-distance=<chunks>` in `server.properties` (the old `world-size` is ignored). Multiplayer protocol version is now 10.
|
||||
- **Lua mods (LuaJIT)** - drop mods into `mods/`, see [mods/README.md](mods/README.md) for the API (events, commands, world/player access, scheduler).
|
||||
- **WorldEdit** - [mods/worldedit](mods/worldedit) is a port of EngineHub's WorldEdit command set to that API (`//wand`, `//set`, `//sphere`, `//copy`, `//paste`, `/undo`, brushes, ...).
|
||||
- **Skins** - `data/images/skins/*.png` (64x32 or 64x64). `/skin list`, `/skin <name>` in the chat console; other players see the skin you pick. Drop a `<username>.png` there to override the skin of that player.
|
||||
- **Music** - the `.ogg` files in `data/music` are played in random order (volume: Music slider). Use `tools/convert-music.ps1` to convert your own FLAC/MP3 files.
|
||||
|
||||
## Windows build (client + server)
|
||||
|
||||
```powershell
|
||||
.\package-windows.ps1 # needs Visual Studio 2022 (C++) and CMake
|
||||
```
|
||||
|
||||
Result: `dist\MinecraftPE-win64` (client) and `dist\MinecraftPE-server-win64` (dedicated server, `start-server.bat`).
|
||||
The script limits the compiler parallelism because OpenAL Soft needs a lot of memory (`-Jobs 2` for small machines), and
|
||||
trusts the dependency checkouts for git ("dubious ownership" on drives that do not store file owners).
|
||||
|
||||
# Build
|
||||
|
||||
## CMake
|
||||
|
|
|
|||
70
cmake/LuaJIT.cmake
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
# Builds LuaJIT (static) from source and exposes it as the imported target "luajit".
|
||||
#
|
||||
# * MSVC: runs LuaJIT's own msvcbuild.bat inside the matching Visual Studio environment
|
||||
# * others: runs LuaJIT's Makefile (make / mingw32-make)
|
||||
|
||||
CPMAddPackage(
|
||||
NAME "luajit"
|
||||
GIT_REPOSITORY "https://github.com/LuaJIT/LuaJIT.git"
|
||||
GIT_TAG "dd3b24369ddfaa83c78cd6fdd91d157c8968ec8d"
|
||||
DOWNLOAD_ONLY YES
|
||||
)
|
||||
|
||||
set(LUAJIT_SRC "${luajit_SOURCE_DIR}/src")
|
||||
|
||||
if (MSVC)
|
||||
set(LUAJIT_LIB "${LUAJIT_SRC}/lua51.lib")
|
||||
|
||||
# <VS>/VC/Tools/MSVC/<ver>/bin/Hostx64/x64/cl.exe -> <VS>/VC/Auxiliary/Build/vcvarsall.bat
|
||||
get_filename_component(_cl_dir "${CMAKE_C_COMPILER}" DIRECTORY)
|
||||
get_filename_component(_vc_root "${_cl_dir}/../../../../../.." ABSOLUTE)
|
||||
set(_vcvars "${_vc_root}/Auxiliary/Build/vcvarsall.bat")
|
||||
if (NOT EXISTS "${_vcvars}")
|
||||
message(FATAL_ERROR "vcvarsall.bat not found at ${_vcvars}")
|
||||
endif()
|
||||
|
||||
if (CMAKE_SIZEOF_VOID_P EQUAL 8)
|
||||
set(_vcarch x64)
|
||||
else()
|
||||
set(_vcarch x86)
|
||||
endif()
|
||||
|
||||
file(TO_NATIVE_PATH "${_vcvars}" _vcvars_native)
|
||||
file(TO_NATIVE_PATH "${LUAJIT_SRC}" _src_native)
|
||||
file(TO_NATIVE_PATH "${CMAKE_BINARY_DIR}/build_luajit.bat" _bat_native)
|
||||
|
||||
# LuaJIT needs the Visual Studio command line environment, so run it from a batch file
|
||||
# (msvcbuild.bat runs the tools it just built by bare name, which needs the current directory in the search path)
|
||||
set(_bat "@echo off\r\nset NoDefaultCurrentDirectoryInExePath=\r\n")
|
||||
string(APPEND _bat "call \"${_vcvars_native}\" ${_vcarch} || exit /b 1\r\n")
|
||||
string(APPEND _bat "cd /d \"${_src_native}\" || exit /b 1\r\n")
|
||||
string(APPEND _bat "call .\\msvcbuild.bat static || exit /b 1\r\n")
|
||||
file(WRITE "${CMAKE_BINARY_DIR}/build_luajit.bat" "${_bat}")
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT "${LUAJIT_LIB}"
|
||||
COMMAND cmd /c "${_bat_native}"
|
||||
WORKING_DIRECTORY "${LUAJIT_SRC}"
|
||||
COMMENT "Building LuaJIT"
|
||||
VERBATIM
|
||||
)
|
||||
else()
|
||||
set(LUAJIT_LIB "${LUAJIT_SRC}/libluajit.a")
|
||||
find_program(_make NAMES make gmake mingw32-make REQUIRED)
|
||||
add_custom_command(
|
||||
OUTPUT "${LUAJIT_LIB}"
|
||||
COMMAND "${_make}" BUILDMODE=static
|
||||
WORKING_DIRECTORY "${LUAJIT_SRC}"
|
||||
COMMENT "Building LuaJIT"
|
||||
VERBATIM
|
||||
)
|
||||
endif()
|
||||
|
||||
add_custom_target(luajit_build DEPENDS "${LUAJIT_LIB}")
|
||||
|
||||
add_library(luajit STATIC IMPORTED GLOBAL)
|
||||
set_target_properties(luajit PROPERTIES
|
||||
IMPORTED_LOCATION "${LUAJIT_LIB}"
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${LUAJIT_SRC}"
|
||||
)
|
||||
add_dependencies(luajit luajit_build)
|
||||
BIN
data/images/skins/blonde.png
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
BIN
data/images/skins/green.png
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
BIN
data/images/skins/ninja.png
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
BIN
data/images/skins/orange.png
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
BIN
data/images/skins/pink.png
Normal file
|
After Width: | Height: | Size: 1.7 KiB |
BIN
data/images/skins/purple.png
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
BIN
data/images/skins/red.png
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
BIN
data/images/skins/snow.png
Normal file
|
After Width: | Height: | Size: 1.7 KiB |
BIN
data/images/skins/steve.png
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
BIN
data/images/skins/yellow.png
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
404
lua/prelude.lua
Normal file
|
|
@ -0,0 +1,404 @@
|
|||
-- ============================================================================
|
||||
-- MinecraftPE Lua API (LuaJIT)
|
||||
-- This file is loaded by the game before any mod. It builds the friendly
|
||||
-- `mc` API on top of the native primitives (mc._*) that the game provides.
|
||||
-- Documentation: mods/README.md
|
||||
-- ============================================================================
|
||||
|
||||
local mc = mc
|
||||
mc.VERSION = "1.0"
|
||||
|
||||
local floor, max, min = math.floor, math.max, math.min
|
||||
|
||||
-- ---------------------------------------------------------------- utilities
|
||||
mc.util = {}
|
||||
|
||||
function mc.util.split(s, sep)
|
||||
local out = {}
|
||||
sep = sep or "%s+"
|
||||
for piece in string.gmatch(s, "([^" .. (sep == "%s+" and "%s" or sep) .. "]+)") do
|
||||
out[#out + 1] = piece
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function mc.util.copy(t)
|
||||
local c = {}
|
||||
for k, v in pairs(t) do c[k] = v end
|
||||
return c
|
||||
end
|
||||
|
||||
local function serialize(v, indent)
|
||||
local t = type(v)
|
||||
if t == "number" or t == "boolean" then return tostring(v) end
|
||||
if t == "string" then return string.format("%q", v) end
|
||||
if t == "table" then
|
||||
local parts = {}
|
||||
for k, val in pairs(v) do
|
||||
parts[#parts + 1] = "[" .. serialize(k) .. "]=" .. serialize(val)
|
||||
end
|
||||
return "{" .. table.concat(parts, ",") .. "}"
|
||||
end
|
||||
return "nil"
|
||||
end
|
||||
|
||||
--- Saves a plain Lua table (numbers, strings, booleans, tables) to a file.
|
||||
function mc.save_table(path, tbl)
|
||||
local f, err = io.open(path, "w")
|
||||
if not f then return false, err end
|
||||
f:write("return ", serialize(tbl))
|
||||
f:close()
|
||||
return true
|
||||
end
|
||||
|
||||
--- Loads a table written by mc.save_table, or returns `default`.
|
||||
function mc.load_table(path, default)
|
||||
local chunk = loadfile(path)
|
||||
if not chunk then return default end
|
||||
setfenv(chunk, {})
|
||||
local ok, res = pcall(chunk)
|
||||
if ok then return res end
|
||||
return default
|
||||
end
|
||||
|
||||
function mc.log(...)
|
||||
local parts = {}
|
||||
for i = 1, select("#", ...) do parts[i] = tostring((select(i, ...))) end
|
||||
mc._log(table.concat(parts, " "))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------ blocks
|
||||
local BLOCKS = {
|
||||
[0] = "air", [1] = "stone", [2] = "grass", [3] = "dirt", [4] = "cobblestone", [5] = "planks",
|
||||
[6] = "sapling", [7] = "bedrock", [8] = "flowing_water", [9] = "water", [10] = "flowing_lava",
|
||||
[11] = "lava", [12] = "sand", [13] = "gravel", [14] = "gold_ore", [15] = "iron_ore",
|
||||
[16] = "coal_ore", [17] = "log", [18] = "leaves", [20] = "glass", [21] = "lapis_ore",
|
||||
[22] = "lapis_block", [24] = "sandstone", [26] = "bed", [30] = "cobweb", [31] = "tallgrass",
|
||||
[35] = "wool", [37] = "dandelion", [38] = "rose", [39] = "brown_mushroom", [40] = "red_mushroom",
|
||||
[41] = "gold_block", [42] = "iron_block", [43] = "double_slab", [44] = "slab", [45] = "bricks",
|
||||
[46] = "tnt", [47] = "bookshelf", [48] = "mossy_cobblestone", [49] = "obsidian", [50] = "torch",
|
||||
[51] = "fire", [53] = "oak_stairs", [54] = "chest", [56] = "diamond_ore", [57] = "diamond_block",
|
||||
[58] = "crafting_table", [59] = "wheat", [60] = "farmland", [61] = "furnace", [62] = "lit_furnace",
|
||||
[63] = "sign", [64] = "wooden_door", [65] = "ladder", [67] = "stone_stairs", [68] = "wall_sign",
|
||||
[71] = "iron_door", [73] = "redstone_ore", [74] = "lit_redstone_ore", [78] = "snow_layer",
|
||||
[79] = "ice", [80] = "snow", [81] = "cactus", [82] = "clay", [83] = "reeds", [85] = "fence",
|
||||
[86] = "pumpkin", [87] = "netherrack", [89] = "glowstone", [91] = "jack_o_lantern",
|
||||
[96] = "trapdoor", [98] = "stonebrick", [102] = "glass_pane", [103] = "melon", [105] = "melon_stem",
|
||||
[107] = "fence_gate", [108] = "brick_stairs", [109] = "stonebrick_stairs", [112] = "nether_brick",
|
||||
[114] = "nether_brick_stairs", [128] = "sandstone_stairs", [129] = "emerald_ore",
|
||||
[133] = "emerald_block", [155] = "quartz_block", [156] = "quartz_stairs", [245] = "stonecutter",
|
||||
[246] = "glowing_obsidian", [247] = "nether_reactor",
|
||||
}
|
||||
|
||||
local ALIASES = {
|
||||
rock = 1, smooth_stone = 1, grass_block = 2, cobble = 4, wood = 5, wood_planks = 5, oak_planks = 5,
|
||||
planks = 5, sapling = 6, adminium = 7, bed_rock = 7, water = 9, still_water = 9, stationary_water = 9,
|
||||
lava = 11, still_lava = 11, stationary_lava = 11, flowing_water = 8, flowing_lava = 10,
|
||||
gold = 14, iron = 15, coal = 16, trunk = 17, tree = 17, wood_log = 17, oak_log = 17, leaf = 18,
|
||||
leaves = 18, lapis = 21, sandstone = 24, web = 30, grass_plant = 31, cloth = 35, flower = 37,
|
||||
yellow_flower = 37, red_flower = 38, goldblock = 41, ironblock = 42, brick = 45, bricks = 45,
|
||||
mossy = 48, mossy_cobble = 48, moss = 48, obsidian = 49, torch = 50, fire = 51, chest = 54,
|
||||
diamond = 56, workbench = 58, crafting = 58, table = 58, furnace = 61, ladder = 65, ice = 79,
|
||||
snowblock = 80, snow_block = 80, cactus = 81, clay = 82, sugarcane = 83, fence = 85, glowstone = 89,
|
||||
lightstone = 89, netherrack = 87, hell = 87, stonebricks = 98, stone_brick = 98, stone_bricks = 98,
|
||||
melon = 103, quartz = 155, door = 64, iron_door = 71, tnt = 46, bookshelf = 47, books = 47,
|
||||
glass = 20, sand = 12, gravel = 13, dirt = 3, stone = 1, grass = 2, bedrock = 7,
|
||||
pane = 102, trap_door = 96, pumpkin = 86, lantern = 91, stair = 53, stairs = 53, double_step = 43,
|
||||
step = 44, half_slab = 44, slab = 44, double_slab = 43, farmland = 60, soil = 60,
|
||||
}
|
||||
|
||||
local WOOL = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray",
|
||||
"light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" }
|
||||
local WOOL_DATA = {}
|
||||
for i, name in ipairs(WOOL) do
|
||||
WOOL_DATA[name] = i - 1
|
||||
ALIASES[name .. "_wool"] = { 35, i - 1 }
|
||||
end
|
||||
|
||||
local NAME_TO_ID = {}
|
||||
for id, name in pairs(BLOCKS) do NAME_TO_ID[name] = id end
|
||||
|
||||
mc.block = { ids = NAME_TO_ID, names = BLOCKS }
|
||||
|
||||
--- Name of a block id ("stone"), or the number as a string.
|
||||
function mc.block.name(id)
|
||||
return BLOCKS[id] or tostring(id)
|
||||
end
|
||||
|
||||
--- Parses "stone", "35:14", "red_wool", "log:1" -> id, data (data is nil when not given)
|
||||
function mc.block.parse(text)
|
||||
text = string.lower(text)
|
||||
local nameOrId, data = string.match(text, "^([%w_]+):(%d+)$")
|
||||
if nameOrId then data = tonumber(data) else nameOrId = text end
|
||||
local id = tonumber(nameOrId)
|
||||
if not id then
|
||||
local alias = ALIASES[nameOrId]
|
||||
if type(alias) == "table" then
|
||||
id, data = alias[1], data or alias[2]
|
||||
else
|
||||
id = alias or NAME_TO_ID[nameOrId]
|
||||
end
|
||||
end
|
||||
if not id or id < 0 or id > 255 then return nil end
|
||||
return id, data
|
||||
end
|
||||
|
||||
-- Blocks that are not solid ground (used by e.g. //green, //naturalize, //ascend)
|
||||
mc.block.AIR = 0
|
||||
|
||||
-- ------------------------------------------------------------------- items
|
||||
mc.item = {
|
||||
stick = 280, compass = 345, wooden_axe = 271, wooden_pickaxe = 270, wooden_shovel = 269,
|
||||
wooden_sword = 268, stone_axe = 275, iron_axe = 258, diamond_axe = 279, flint_and_steel = 259,
|
||||
apple = 260, bow = 261, arrow = 262, coal = 263, diamond = 264, iron_ingot = 265, gold_ingot = 266,
|
||||
bucket = 325, water_bucket = 326, lava_bucket = 327, clock = 347, paper = 339, book = 340,
|
||||
}
|
||||
|
||||
mc.mob = { chicken = 10, cow = 11, pig = 12, sheep = 13, zombie = 32, creeper = 33,
|
||||
skeleton = 34, spider = 35, pig_zombie = 36 }
|
||||
|
||||
-- ------------------------------------------------------------------ players
|
||||
local Player = {}
|
||||
Player.__index = Player
|
||||
local playerCache = {}
|
||||
|
||||
local function getPlayer(id)
|
||||
if not id then return nil end
|
||||
local p = playerCache[id]
|
||||
if not p then
|
||||
local name = mc._pname(id)
|
||||
if not name then return nil end
|
||||
p = setmetatable({ id = id, name = name, data = {} }, Player)
|
||||
playerCache[id] = p
|
||||
end
|
||||
return p
|
||||
end
|
||||
mc._player = getPlayer
|
||||
|
||||
function Player:__tostring() return "Player(" .. self.name .. ")" end
|
||||
|
||||
--- Feet position: x, y, z
|
||||
function Player:pos() local x, y, z = mc._ppos(self.id); return x, y, z end
|
||||
--- Block the feet are in
|
||||
function Player:block_pos()
|
||||
local x, y, z = mc._ppos(self.id)
|
||||
return floor(x), floor(y), floor(z)
|
||||
end
|
||||
--- yaw, pitch in degrees
|
||||
function Player:look() local _, _, _, yaw, pitch = mc._ppos(self.id); return yaw, pitch end
|
||||
--- Horizontal facing as 0..3 (south, west, north, east) and its unit vector
|
||||
function Player:facing()
|
||||
local yaw = self:look()
|
||||
local dir = floor(((yaw % 360) + 45) / 90) % 4
|
||||
local vec = { [0] = { 0, 1 }, [1] = { -1, 0 }, [2] = { 0, -1 }, [3] = { 1, 0 } }
|
||||
return dir, vec[dir][1], vec[dir][2]
|
||||
end
|
||||
function Player:teleport(x, y, z, yaw, pitch) mc._pteleport(self.id, x, y, z, yaw, pitch) end
|
||||
function Player:say(...)
|
||||
local parts = {}
|
||||
for i = 1, select("#", ...) do parts[i] = tostring((select(i, ...))) end
|
||||
local text = table.concat(parts, " ")
|
||||
for line in string.gmatch(text .. "\n", "(.-)\n") do
|
||||
if line ~= "" then mc._pmsg(self.id, line) end
|
||||
end
|
||||
end
|
||||
function Player:is_op() return mc._pop(self.id) end
|
||||
--- id, data, count of the held item (0,0,0 when empty)
|
||||
function Player:held() return mc._pheld(self.id) end
|
||||
function Player:give(id, count, data) mc._pgive(self.id, id, count or 1, data or 0) end
|
||||
--- 0 = survival, 1 = creative
|
||||
function Player:gamemode() return mc._pgamemode() end
|
||||
--- x, y, z, face of the block the player is looking at, or nil
|
||||
function Player:target(distance) return mc._ptrace(self.id, distance or 128) end
|
||||
function Player:is_online() return mc._pname(self.id) ~= nil end
|
||||
|
||||
mc.Player = Player
|
||||
|
||||
function mc.players()
|
||||
local list = {}
|
||||
for i, id in ipairs(mc._players()) do list[i] = getPlayer(id) end
|
||||
return list
|
||||
end
|
||||
|
||||
function mc.player(name)
|
||||
name = string.lower(name)
|
||||
for _, id in ipairs(mc._players()) do
|
||||
local p = getPlayer(id)
|
||||
if p and string.lower(p.name) == name then return p end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function mc.broadcast(text) mc._broadcast(text) end
|
||||
|
||||
-- -------------------------------------------------------------------- world
|
||||
mc.world = {}
|
||||
local W = mc.world
|
||||
|
||||
W.get_block = mc._get_block
|
||||
W.set_block = mc._set_block
|
||||
--- Re-sends/relights everything written with silent set_block calls
|
||||
W.flush = mc._flush
|
||||
W.is_loaded = mc._loaded
|
||||
W.ensure_loaded = mc._ensure
|
||||
W.seed = mc._seed
|
||||
W.explode = mc._explode
|
||||
W.spawn_mob = mc._spawn_mob
|
||||
W.drop_item = mc._drop_item
|
||||
W.butcher = mc._butcher
|
||||
W.height = mc._solid_height
|
||||
W.get_time = mc._get_time
|
||||
W.set_time = mc._set_time
|
||||
|
||||
-- ---------------------------------------------------------------- scheduler
|
||||
local tasks, nextTask, tickCount = {}, 1, 0
|
||||
mc.tick_count = 0
|
||||
|
||||
function mc.after(ticks, fn)
|
||||
local id = nextTask; nextTask = nextTask + 1
|
||||
tasks[id] = { at = tickCount + max(1, ticks), fn = fn }
|
||||
return id
|
||||
end
|
||||
|
||||
function mc.every(ticks, fn)
|
||||
local id = nextTask; nextTask = nextTask + 1
|
||||
tasks[id] = { at = tickCount + max(1, ticks), fn = fn, period = max(1, ticks) }
|
||||
return id
|
||||
end
|
||||
|
||||
function mc.cancel(id) tasks[id] = nil end
|
||||
|
||||
-- ------------------------------------------------------------------- events
|
||||
local handlers = {}
|
||||
|
||||
--- mc.on("block_break", function(player, x, y, z, tile) return false end)
|
||||
--- Events: start, stop, tick, join, leave, chat, block_break, use_item
|
||||
--- Returning false from a cancellable event (chat, block_break, use_item) cancels it.
|
||||
function mc.on(event, fn)
|
||||
handlers[event] = handlers[event] or {}
|
||||
table.insert(handlers[event], fn)
|
||||
end
|
||||
|
||||
local function report(modName, err)
|
||||
mc._log("error in handler: " .. tostring(err))
|
||||
end
|
||||
|
||||
function mc._fire(event, pid, ...)
|
||||
local list = handlers[event]
|
||||
if not list then return true end
|
||||
local first = pid
|
||||
if pid ~= nil then first = getPlayer(pid) end
|
||||
local result = true
|
||||
for i = 1, #list do
|
||||
local ok, res = xpcall(list[i], debug.traceback, first, ...)
|
||||
if not ok then
|
||||
report(nil, res)
|
||||
elseif res == false then
|
||||
result = false
|
||||
end
|
||||
end
|
||||
if event == "leave" and pid then playerCache[pid] = nil end
|
||||
return result
|
||||
end
|
||||
|
||||
function mc._tick()
|
||||
tickCount = tickCount + 1
|
||||
mc.tick_count = tickCount
|
||||
for id, task in pairs(tasks) do
|
||||
if task.at <= tickCount then
|
||||
if task.period then task.at = tickCount + task.period else tasks[id] = nil end
|
||||
local ok, err = xpcall(task.fn, debug.traceback)
|
||||
if not ok then report(nil, err) end
|
||||
end
|
||||
end
|
||||
if handlers.tick then mc._fire("tick") end
|
||||
end
|
||||
|
||||
-- ----------------------------------------------------------------- commands
|
||||
local commands = {}
|
||||
|
||||
--- mc.command("home", { description = "...", usage = "/home", op = false }, function(ctx) ... end)
|
||||
--- Names are what the player types after the first slash, so WorldEdit's "//set" is "/set".
|
||||
function mc.command(name, opts, fn)
|
||||
if type(opts) == "function" then fn, opts = opts, {} end
|
||||
commands[string.lower(name)] = { fn = fn, opts = opts or {}, name = name }
|
||||
end
|
||||
|
||||
function mc._command_names()
|
||||
local names = {}
|
||||
for name in pairs(commands) do names[#names + 1] = name end
|
||||
table.sort(names)
|
||||
return names
|
||||
end
|
||||
|
||||
function mc._run_command(pid, name, args)
|
||||
local cmd = commands[string.lower(name)]
|
||||
if not cmd then return false end
|
||||
local player = getPlayer(pid)
|
||||
if cmd.opts.op and not player:is_op() then
|
||||
return true, "You are not allowed to use this command."
|
||||
end
|
||||
local replies = {}
|
||||
local ctx = {
|
||||
player = player, args = args, name = name,
|
||||
reply = function(_, ...) player:say(...) end,
|
||||
}
|
||||
setmetatable(ctx, { __index = function(_, k) return nil end })
|
||||
local ok, res = xpcall(cmd.fn, debug.traceback, ctx)
|
||||
if not ok then
|
||||
mc._log("command /" .. name .. " failed: " .. tostring(res))
|
||||
return true, "Command failed: " .. tostring(res):match("^[^\n]*")
|
||||
end
|
||||
if type(res) == "string" then return true, res end
|
||||
return true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------- mods
|
||||
mc.mods = {}
|
||||
|
||||
local function listDir(dir)
|
||||
return mc._listdir and mc._listdir(dir) or {}
|
||||
end
|
||||
|
||||
local function loadMod(name, dir, file)
|
||||
local env = setmetatable({}, { __index = _G })
|
||||
env.MOD = { name = name, dir = dir }
|
||||
env.require = function(m)
|
||||
local path = dir .. "/" .. m:gsub("%.", "/") .. ".lua"
|
||||
local chunk = loadfile(path)
|
||||
if chunk then
|
||||
setfenv(chunk, env)
|
||||
return chunk()
|
||||
end
|
||||
return require(m)
|
||||
end
|
||||
local chunk, err = loadfile(file)
|
||||
if not chunk then
|
||||
mc._log("cannot load mod '" .. name .. "': " .. tostring(err))
|
||||
return
|
||||
end
|
||||
setfenv(chunk, env)
|
||||
local ok, res = xpcall(chunk, debug.traceback)
|
||||
if not ok then
|
||||
mc._log("mod '" .. name .. "' failed: " .. tostring(res))
|
||||
return
|
||||
end
|
||||
mc.mods[name] = env.MOD
|
||||
mc._log("loaded mod '" .. name .. "'")
|
||||
end
|
||||
|
||||
function mc._load_mods()
|
||||
local entries = listDir("mods")
|
||||
table.sort(entries, function(a, b) return a.name < b.name end)
|
||||
for _, e in ipairs(entries) do
|
||||
if e.dir then
|
||||
local main = "mods/" .. e.name .. "/main.lua"
|
||||
local f = io.open(main, "r")
|
||||
if f then f:close(); loadMod(e.name, "mods/" .. e.name, main) end
|
||||
elseif e.name:match("%.lua$") then
|
||||
loadMod((e.name:gsub("%.lua$", "")), "mods", "mods/" .. e.name)
|
||||
end
|
||||
end
|
||||
mc._fire("start")
|
||||
for _, id in ipairs(mc._players()) do mc._fire("join", id) end
|
||||
end
|
||||
120
mods/README.md
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
# Lua mods (LuaJIT)
|
||||
|
||||
The game embeds **LuaJIT 2.1**. Mods run on the machine that hosts the world:
|
||||
the dedicated server (`MinecraftPE-server.exe`), a single player world, or a
|
||||
client that hosts a LAN game. A client that only joins a server runs no mods.
|
||||
|
||||
```
|
||||
mods/
|
||||
my_mod/
|
||||
main.lua <- loaded at startup (alphabetical order)
|
||||
other.lua <- require("other")
|
||||
tiny.lua <- a single file mod works too
|
||||
```
|
||||
|
||||
Every mod runs in its own environment (`MOD.name`, `MOD.dir` describe it), so
|
||||
globals do not leak between mods. `require("x")` loads `mods/<mod>/x.lua` first.
|
||||
The full Lua 5.1 standard library, `io`, `os`, `bit` and `ffi` are available –
|
||||
mods are trusted code, only install mods you trust.
|
||||
|
||||
## Events
|
||||
|
||||
```lua
|
||||
mc.on("start", function() end) -- all mods loaded, world is up
|
||||
mc.on("stop", function() end)
|
||||
mc.on("tick", function() end) -- 20 times per second
|
||||
mc.on("join", function(player) end)
|
||||
mc.on("leave", function(player) end)
|
||||
mc.on("chat", function(player, message) end) -- return false to cancel
|
||||
mc.on("block_break", function(player, x, y, z, tile) end)-- return false to cancel
|
||||
mc.on("use_item", function(player, x, y, z, face, itemId, itemData) end) -- right click on a block, false cancels
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
```lua
|
||||
mc.command("home", { description = "Go home", op = false }, function(ctx)
|
||||
ctx.player:teleport(0, 70, 0)
|
||||
return "Welcome home!" -- a returned string is sent to the player
|
||||
end)
|
||||
```
|
||||
|
||||
`ctx` has `player`, `args` (array of strings) and `name`. Names are what is typed
|
||||
after the first slash: `mc.command("/set", ...)` is `//set` in game. `op = true`
|
||||
restricts the command to operators (`ops.txt`).
|
||||
|
||||
## Players
|
||||
|
||||
`mc.players()`, `mc.player("name")`, `mc.broadcast(text)`
|
||||
|
||||
| method | |
|
||||
|---|---|
|
||||
| `p.name`, `p.id`, `p.data` | `data` is a free table for your mod |
|
||||
| `p:pos()` → x, y, z | feet position |
|
||||
| `p:block_pos()` → x, y, z | integer block of the feet |
|
||||
| `p:look()` → yaw, pitch | |
|
||||
| `p:facing()` → 0..3, dx, dz | south, west, north, east |
|
||||
| `p:teleport(x, y, z [, yaw, pitch])` | |
|
||||
| `p:say(text)` | private message |
|
||||
| `p:is_op()` | |
|
||||
| `p:held()` → id, data, count | |
|
||||
| `p:give(id [, count [, data]])` | |
|
||||
| `p:target([distance])` → x, y, z, face | block in the crosshair |
|
||||
| `p:gamemode()` | 0 survival, 1 creative |
|
||||
|
||||
## World
|
||||
|
||||
```lua
|
||||
mc.world.get_block(x, y, z) -- id, data
|
||||
mc.world.set_block(x, y, z, id, data) -- normal change (updates neighbours, notifies clients)
|
||||
mc.world.set_block(x, y, z, id, data, true) -- "silent": no updates; call mc.world.flush() afterwards
|
||||
mc.world.flush() -- relight + resend every chunk touched by silent writes
|
||||
mc.world.height(x, z) -- highest solid block, -1 if none
|
||||
mc.world.is_loaded(x, z) -- block coordinates
|
||||
mc.world.ensure_loaded(x, z, radiusInChunks)
|
||||
mc.world.spawn_mob(mc.mob.pig, x, y, z) -- returns entity id
|
||||
mc.world.drop_item(id, count, data, x, y, z)
|
||||
mc.world.explode(x, y, z, radius)
|
||||
mc.world.butcher(x, y, z, radius, includeFriendly) -- radius 0 = everywhere, returns count
|
||||
mc.world.get_time() / set_time(t) / seed()
|
||||
```
|
||||
|
||||
The world is infinite: chunks around players are generated, saved and unloaded
|
||||
on demand. Use `ensure_loaded` before touching far-away coordinates.
|
||||
|
||||
## Names and ids
|
||||
|
||||
`mc.block.parse("stone")`, `mc.block.parse("35:14")`, `mc.block.parse("red_wool")` → id, data
|
||||
`mc.block.name(id)`, `mc.item.wooden_axe`, `mc.mob.zombie`, …
|
||||
|
||||
## Scheduler and utilities
|
||||
|
||||
```lua
|
||||
local id = mc.after(40, function() ... end) -- ticks
|
||||
mc.every(20, function() ... end)
|
||||
mc.cancel(id)
|
||||
mc.log("text")
|
||||
mc.save_table("mods/data/x.lua", tbl) / mc.load_table(path, default)
|
||||
```
|
||||
|
||||
# Bundled mods
|
||||
|
||||
* **worldedit** – a port of EngineHub's WorldEdit command set (see below).
|
||||
* **hello** – the smallest possible example.
|
||||
|
||||
## WorldEdit
|
||||
|
||||
Give yourself the wand with `//wand` (a wooden axe): left click = position 1,
|
||||
right click = position 2. Operators only. Implemented commands:
|
||||
|
||||
`//wand //pos1 //pos2 //hpos1 //hpos2 //chunk //sel //expand //contract //shift //outset //inset //trim //size //count //distr`
|
||||
`//set //replace //overlay //center //naturalize //walls //faces //hollow //smooth //move //stack //line`
|
||||
`//sphere //hsphere //cyl //hcyl //cone //pyramid //hpyramid`
|
||||
`//copy //cut //paste //rotate //flip /clearclipboard /schematic save|load|list|delete`
|
||||
`/undo /redo /clearhistory //fill //fillr //drain /fixwater /fixlava /removeabove /removebelow /removenear /replacenear`
|
||||
`/snow /thaw /green /extinguish /butcher //limit /toggleplace /we`
|
||||
`/unstuck /ascend /descend /ceil /thru /jumpto /up`
|
||||
`/tool (repl, info, farwand, navwand, selwand, deltree, floodfill, none) /brush (sphere, cylinder, set, smooth, raise, lower, gravity, extinguish, butcher) /mask /material /range /size // /sp`
|
||||
|
||||
Patterns: `stone`, `35:14`, `red_wool`, `50%stone,50%dirt`. Masks: `stone,dirt`, `!air`,
|
||||
`#existing`, `#solid`. Flags work like in the original (`//sphere -h stone 5`).
|
||||
22
mods/hello.lua
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
-- The smallest mod: greets players and adds /hello and /where.
|
||||
|
||||
mc.on("join", function(player)
|
||||
player:say("Welcome, " .. player.name .. "! Lua mods are running on this world.")
|
||||
end)
|
||||
|
||||
mc.command("hello", { description = "Say hello" }, function(ctx)
|
||||
return "Hello, " .. ctx.player.name .. "!"
|
||||
end)
|
||||
|
||||
mc.command("where", { description = "Show your coordinates" }, function(ctx)
|
||||
local x, y, z = ctx.player:block_pos()
|
||||
return string.format("You are at %d, %d, %d", x, y, z)
|
||||
end)
|
||||
|
||||
mc.command("tp", { description = "Teleport: /tp <x> <y> <z>", usage = "/tp <x> <y> <z>", op = true }, function(ctx)
|
||||
local x, y, z = tonumber(ctx.args[1]), tonumber(ctx.args[2]), tonumber(ctx.args[3])
|
||||
if not (x and y and z) then return "Usage: /tp <x> <y> <z> (y = 0 puts you on the ground)" end
|
||||
if y <= 0 then mc.world.ensure_loaded(x, z, 1); y = mc.world.height(math.floor(x), math.floor(z)) + 1 end
|
||||
ctx.player:teleport(x + 0.5, y, z + 0.5)
|
||||
return string.format("Teleported to %d, %d, %d", x, y, z)
|
||||
end)
|
||||
450
mods/worldedit/lib.lua
Normal file
|
|
@ -0,0 +1,450 @@
|
|||
-- WorldEdit for MinecraftPE: core library
|
||||
-- (edit sessions, patterns, masks, region helpers, shapes, history)
|
||||
|
||||
local L = {}
|
||||
|
||||
local floor, ceil, abs, min, max, sqrt = math.floor, math.ceil, math.abs, math.min, math.max, math.sqrt
|
||||
local get_block, set_block = mc.world.get_block, mc.world.set_block
|
||||
|
||||
L.DEFAULT_LIMIT = 5000000
|
||||
|
||||
-- =========================================================== player sessions
|
||||
local sessions = {}
|
||||
|
||||
function L.session(player)
|
||||
local s = sessions[player.name]
|
||||
if not s then
|
||||
s = {
|
||||
pos1 = nil, pos2 = nil,
|
||||
clipboard = nil,
|
||||
undo = {}, redo = {},
|
||||
limit = L.DEFAULT_LIMIT,
|
||||
tools = {}, -- item id -> { type = "repl"/"info"/"brush"/..., ... }
|
||||
superpick = nil, -- nil | "single" | "area" | "recursive"
|
||||
superpick_range = 3,
|
||||
brush_size = 5, brush_mask = nil, brush_material = nil, brush_range = 200,
|
||||
selector = "cuboid",
|
||||
}
|
||||
sessions[player.name] = s
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
-- ================================================================== helpers
|
||||
function L.region(s)
|
||||
if not s.pos1 or not s.pos2 then return nil end
|
||||
local a, b = s.pos1, s.pos2
|
||||
return {
|
||||
x0 = min(a[1], b[1]), y0 = min(a[2], b[2]), z0 = min(a[3], b[3]),
|
||||
x1 = max(a[1], b[1]), y1 = max(a[2], b[2]), z1 = max(a[3], b[3]),
|
||||
}
|
||||
end
|
||||
|
||||
function L.volume(r)
|
||||
return (r.x1 - r.x0 + 1) * (r.y1 - r.y0 + 1) * (r.z1 - r.z0 + 1)
|
||||
end
|
||||
|
||||
local function clampY(y) return max(0, min(127, y)) end
|
||||
L.clampY = clampY
|
||||
|
||||
--- Loads every chunk the region touches.
|
||||
function L.load_region(r)
|
||||
for cx = floor(r.x0 / 16), floor(r.x1 / 16) do
|
||||
for cz = floor(r.z0 / 16), floor(r.z1 / 16) do
|
||||
mc.world.ensure_loaded(cx * 16 + 8, cz * 16 + 8, 0)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local DIRS = {
|
||||
up = { 0, 1, 0 }, u = { 0, 1, 0 }, down = { 0, -1, 0 }, d = { 0, -1, 0 },
|
||||
north = { 0, 0, -1 }, n = { 0, 0, -1 }, south = { 0, 0, 1 }, s = { 0, 0, 1 },
|
||||
east = { 1, 0, 0 }, e = { 1, 0, 0 }, west = { -1, 0, 0 }, w = { -1, 0, 0 },
|
||||
}
|
||||
|
||||
--- Direction word -> unit vector. "me"/nil = where the player looks (incl. up/down)
|
||||
function L.direction(player, word)
|
||||
word = word and string.lower(word)
|
||||
if word and DIRS[word] then return DIRS[word] end
|
||||
local yaw, pitch = player:look()
|
||||
if pitch < -50 then return DIRS.up end
|
||||
if pitch > 50 then return DIRS.down end
|
||||
local _, dx, dz = player:facing()
|
||||
return { dx, 0, dz }
|
||||
end
|
||||
|
||||
--- Splits "-abc foo 5 -p 2" into flags and positional arguments.
|
||||
--- `valued` is a set of flags that take a value: { p = true }
|
||||
function L.parse(args, valued)
|
||||
local flags, pos = {}, {}
|
||||
local i = 1
|
||||
while i <= #args do
|
||||
local a = args[i]
|
||||
if a:match("^%-%a+$") and not tonumber(a) then
|
||||
for ch in a:sub(2):gmatch(".") do
|
||||
if valued and valued[ch] then
|
||||
i = i + 1
|
||||
flags[ch] = args[i]
|
||||
else
|
||||
flags[ch] = true
|
||||
end
|
||||
end
|
||||
else
|
||||
pos[#pos + 1] = a
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
return flags, pos
|
||||
end
|
||||
|
||||
-- ================================================================== patterns
|
||||
-- "stone" "5%stone,5%dirt:1,air" "35:14"
|
||||
function L.pattern(text)
|
||||
if not text or text == "" then return nil, "No pattern given." end
|
||||
local entries, total = {}, 0
|
||||
for part in text:gmatch("[^,]+") do
|
||||
local weight, spec = part:match("^([%d%.]+)%%(.+)$")
|
||||
weight = tonumber(weight) or 1
|
||||
spec = spec or part
|
||||
local id, data = mc.block.parse(spec)
|
||||
if not id then return nil, "Unknown block: " .. spec end
|
||||
entries[#entries + 1] = { id = id, data = data, w = weight }
|
||||
total = total + weight
|
||||
end
|
||||
if #entries == 1 then
|
||||
local e = entries[1]
|
||||
return function() return e.id, e.data end, entries[1]
|
||||
end
|
||||
return function()
|
||||
local r = math.random() * total
|
||||
for _, e in ipairs(entries) do
|
||||
r = r - e.w
|
||||
if r <= 0 then return e.id, e.data end
|
||||
end
|
||||
local e = entries[#entries]
|
||||
return e.id, e.data
|
||||
end
|
||||
end
|
||||
|
||||
-- masks: "stone" "stone,dirt" "!air" "#existing" "#solid"
|
||||
function L.mask(text)
|
||||
if not text or text == "" then return nil end
|
||||
local negate = false
|
||||
if text:sub(1, 1) == "!" then negate = true; text = text:sub(2) end
|
||||
local test
|
||||
if text == "#existing" then
|
||||
test = function(id) return id ~= 0 end
|
||||
elseif text == "#solid" then
|
||||
test = function(id) return id ~= 0 and id ~= 8 and id ~= 9 and id ~= 10 and id ~= 11 end
|
||||
elseif text == "#air" then
|
||||
test = function(id) return id == 0 end
|
||||
else
|
||||
local set = {}
|
||||
for part in text:gmatch("[^,]+") do
|
||||
local id, data = mc.block.parse(part)
|
||||
if not id then return nil, "Unknown block: " .. part end
|
||||
set[#set + 1] = { id, data }
|
||||
end
|
||||
test = function(id, data)
|
||||
for _, e in ipairs(set) do
|
||||
if e[1] == id and (e[2] == nil or e[2] == data) then return true end
|
||||
end
|
||||
return false
|
||||
end
|
||||
end
|
||||
if negate then return function(id, data) return not test(id, data) end end
|
||||
return test
|
||||
end
|
||||
|
||||
-- ============================================================== edit sessions
|
||||
local Edit = {}
|
||||
Edit.__index = Edit
|
||||
|
||||
function L.new_edit(session)
|
||||
return setmetatable({ s = session, entries = {}, index = {}, count = 0, limit = session.limit }, Edit)
|
||||
end
|
||||
|
||||
local OFFSET = 1000000
|
||||
|
||||
--- Sets a block (recording the old one for undo). Returns true when something changed.
|
||||
function Edit:set(x, y, z, id, data)
|
||||
if y < 0 or y > 127 then return false end
|
||||
data = data or 0
|
||||
local oid, od = get_block(x, y, z)
|
||||
if oid == id and od == data then return false end
|
||||
if self.limit >= 0 and self.count >= self.limit then
|
||||
self.overflow = true
|
||||
return false
|
||||
end
|
||||
if not self.bx then self.bx, self.bz = x, z end
|
||||
local key = ((x - self.bx + OFFSET) * 4000000 + (z - self.bz + OFFSET)) * 128 + y
|
||||
local e = self.index[key]
|
||||
if not e then
|
||||
e = { x, y, z, oid, od, id, data }
|
||||
self.index[key] = e
|
||||
self.entries[#self.entries + 1] = e
|
||||
else
|
||||
e[6], e[7] = id, data
|
||||
end
|
||||
self.count = self.count + 1
|
||||
set_block(x, y, z, id, data, true)
|
||||
return true
|
||||
end
|
||||
|
||||
function Edit:get(x, y, z)
|
||||
return get_block(x, y, z)
|
||||
end
|
||||
|
||||
--- Writes the pattern into the block
|
||||
function Edit:place(x, y, z, pattern)
|
||||
local id, data = pattern()
|
||||
return self:set(x, y, z, id, data)
|
||||
end
|
||||
|
||||
--- Finishes the edit: relights/resends the touched chunks and stores it in the history
|
||||
function Edit:commit()
|
||||
mc.world.flush()
|
||||
if #self.entries > 0 then
|
||||
local undo = self.s.undo
|
||||
undo[#undo + 1] = self.entries
|
||||
if #undo > 40 then table.remove(undo, 1) end
|
||||
self.s.redo = {}
|
||||
end
|
||||
return #self.entries
|
||||
end
|
||||
|
||||
local function apply_history(entries, reverse)
|
||||
local changed = 0
|
||||
if reverse then
|
||||
for i = #entries, 1, -1 do
|
||||
local e = entries[i]
|
||||
set_block(e[1], e[2], e[3], e[4], e[5], true)
|
||||
changed = changed + 1
|
||||
end
|
||||
else
|
||||
for i = 1, #entries do
|
||||
local e = entries[i]
|
||||
set_block(e[1], e[2], e[3], e[6], e[7], true)
|
||||
changed = changed + 1
|
||||
end
|
||||
end
|
||||
mc.world.flush()
|
||||
return changed
|
||||
end
|
||||
|
||||
function L.undo(s)
|
||||
local e = table.remove(s.undo)
|
||||
if not e then return nil end
|
||||
s.redo[#s.redo + 1] = e
|
||||
return apply_history(e, true)
|
||||
end
|
||||
|
||||
function L.redo(s)
|
||||
local e = table.remove(s.redo)
|
||||
if not e then return nil end
|
||||
s.undo[#s.undo + 1] = e
|
||||
return apply_history(e, false)
|
||||
end
|
||||
|
||||
-- ============================================================ region iteration
|
||||
function L.each(r, fn)
|
||||
for x = r.x0, r.x1 do
|
||||
for z = r.z0, r.z1 do
|
||||
for y = r.y0, r.y1 do
|
||||
fn(x, y, z)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function L.walls_and_faces(r, edit, pattern, floorAndCeil)
|
||||
L.each(r, function(x, y, z)
|
||||
local wall = x == r.x0 or x == r.x1 or z == r.z0 or z == r.z1
|
||||
local cap = y == r.y0 or y == r.y1
|
||||
if wall or (floorAndCeil and cap) then edit:place(x, y, z, pattern) end
|
||||
end)
|
||||
end
|
||||
|
||||
-- ================================================================== shapes
|
||||
local function lsq(x, y, z) return x * x + y * y + z * z end
|
||||
|
||||
--- WorldEdit's ellipsoid. (cx,cy,cz) is the centre block.
|
||||
function L.sphere(edit, cx, cy, cz, pattern, rx, ry, rz, filled)
|
||||
rx, ry, rz = rx + 0.5, ry + 0.5, rz + 0.5
|
||||
local irx, iry, irz = 1 / rx, 1 / ry, 1 / rz
|
||||
local crx, cry, crz = ceil(rx), ceil(ry), ceil(rz)
|
||||
local nextXn = 0
|
||||
for x = 0, crx do
|
||||
local xn = nextXn
|
||||
nextXn = (x + 1) * irx
|
||||
local nextYn = 0
|
||||
for y = 0, cry do
|
||||
local yn = nextYn
|
||||
nextYn = (y + 1) * iry
|
||||
local nextZn = 0
|
||||
for z = 0, crz do
|
||||
local zn = nextZn
|
||||
nextZn = (z + 1) * irz
|
||||
if lsq(xn, yn, zn) > 1 then break end
|
||||
local skip = false
|
||||
if not filled then
|
||||
if lsq(nextXn, yn, zn) <= 1 and lsq(xn, nextYn, zn) <= 1 and lsq(xn, yn, nextZn) <= 1 then
|
||||
skip = true
|
||||
end
|
||||
end
|
||||
if not skip then
|
||||
for sx = -1, 1, 2 do
|
||||
for sy = -1, 1, 2 do
|
||||
for sz = -1, 1, 2 do
|
||||
if (x ~= 0 or sx == 1) and (y ~= 0 or sy == 1) and (z ~= 0 or sz == 1) then
|
||||
edit:place(cx + sx * x, cy + sy * y, cz + sz * z, pattern)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function L.cylinder(edit, cx, cy, cz, pattern, rx, rz, height, filled)
|
||||
rx, rz = rx + 0.5, rz + 0.5
|
||||
if height == 0 then return end
|
||||
local irx, irz = 1 / rx, 1 / rz
|
||||
local crx, crz = ceil(rx), ceil(rz)
|
||||
local ys, ye = cy, cy + height - 1
|
||||
if height < 0 then ys, ye = cy + height + 1, cy end
|
||||
local nextXn = 0
|
||||
for x = 0, crx do
|
||||
local xn = nextXn
|
||||
nextXn = (x + 1) * irx
|
||||
local nextZn = 0
|
||||
for z = 0, crz do
|
||||
local zn = nextZn
|
||||
nextZn = (z + 1) * irz
|
||||
if lsq(xn, 0, zn) > 1 then break end
|
||||
local skip = false
|
||||
if not filled then
|
||||
if lsq(nextXn, 0, zn) <= 1 and lsq(xn, 0, nextZn) <= 1 then skip = true end
|
||||
end
|
||||
if not skip then
|
||||
for sx = -1, 1, 2 do
|
||||
for sz = -1, 1, 2 do
|
||||
if (x ~= 0 or sx == 1) and (z ~= 0 or sz == 1) then
|
||||
for y = ys, ye do
|
||||
edit:place(cx + sx * x, y, cz + sz * z, pattern)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function L.cone(edit, cx, cy, cz, pattern, rx, rz, height, filled)
|
||||
for h = 0, height - 1 do
|
||||
local f = 1 - h / height
|
||||
L.cylinder(edit, cx, cy + h, cz, pattern, max(0, rx * f), max(0, rz * f), 1, filled)
|
||||
end
|
||||
end
|
||||
|
||||
function L.pyramid(edit, cx, cy, cz, pattern, size, filled)
|
||||
local height = size
|
||||
for y = 0, height do
|
||||
size = size - 1
|
||||
for x = 0, size do
|
||||
for z = 0, size do
|
||||
if (filled and z <= size and x <= size) or z == size or x == size then
|
||||
edit:place(cx + x, cy + y, cz + z, pattern)
|
||||
edit:place(cx - x, cy + y, cz + z, pattern)
|
||||
edit:place(cx + x, cy + y, cz - z, pattern)
|
||||
edit:place(cx - x, cy + y, cz - z, pattern)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Line through block space; thickness > 0 puts a sphere of that radius on every point.
|
||||
function L.line(edit, a, b, pattern, radius, filled)
|
||||
local dx, dy, dz = b[1] - a[1], b[2] - a[2], b[3] - a[3]
|
||||
local steps = max(abs(dx), abs(dy), abs(dz))
|
||||
local seen = {}
|
||||
for i = 0, steps do
|
||||
local t = steps == 0 and 0 or i / steps
|
||||
local x = floor(a[1] + dx * t + 0.5)
|
||||
local y = floor(a[2] + dy * t + 0.5)
|
||||
local z = floor(a[3] + dz * t + 0.5)
|
||||
if radius and radius > 0 then
|
||||
L.sphere(edit, x, y, z, pattern, radius, radius, radius, filled ~= false)
|
||||
else
|
||||
edit:place(x, y, z, pattern)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ============================================================== block helpers
|
||||
local function is_air(id) return id == 0 end
|
||||
local LIQUID = { [8] = true, [9] = true, [10] = true, [11] = true }
|
||||
function L.is_liquid(id) return LIQUID[id] == true end
|
||||
function L.is_air(id) return is_air(id) end
|
||||
|
||||
--- Top block (y) that is not air within [y0, y1] for the column, or nil
|
||||
function L.top_existing(x, z, y0, y1)
|
||||
for y = y1, y0, -1 do
|
||||
if get_block(x, y, z) ~= 0 then return y end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
--- Top solid (non liquid/plant) block y in the column
|
||||
local PLANTS = { [6] = true, [31] = true, [37] = true, [38] = true, [39] = true, [40] = true, [50] = true,
|
||||
[51] = true, [59] = true, [83] = true, [78] = true, [81] = false, [18] = false }
|
||||
function L.top_ground(x, z, y0, y1)
|
||||
for y = y1, y0, -1 do
|
||||
local id = get_block(x, y, z)
|
||||
if id ~= 0 and not LIQUID[id] and not PLANTS[id] and id ~= 17 and id ~= 18 then return y end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- ======================================================== rotation of block data
|
||||
-- data values that point in a direction, rotated 90 degrees clockwise (y axis)
|
||||
local ROT = {
|
||||
stairs = { [0] = 2, [1] = 3, [2] = 1, [3] = 0 }, -- east,west,south,north
|
||||
torch = { [1] = 3, [2] = 4, [3] = 2, [4] = 1 },
|
||||
ladder = { [2] = 5, [3] = 4, [4] = 2, [5] = 3 }, -- chest, furnace, ladder, signs
|
||||
door = { [0] = 1, [1] = 2, [2] = 3, [3] = 0 },
|
||||
trapdoor = { [0] = 3, [1] = 2, [2] = 0, [3] = 1 },
|
||||
}
|
||||
local KIND = {
|
||||
[53] = "stairs", [67] = "stairs", [108] = "stairs", [109] = "stairs", [114] = "stairs", [128] = "stairs",
|
||||
[156] = "stairs",
|
||||
[50] = "torch", [75] = "torch", [76] = "torch",
|
||||
[65] = "ladder", [54] = "ladder", [61] = "ladder", [62] = "ladder", [68] = "ladder", [86] = "ladder",
|
||||
[91] = "ladder",
|
||||
[64] = "door", [71] = "door", [107] = "door",
|
||||
[96] = "trapdoor",
|
||||
}
|
||||
|
||||
function L.rotate_data(id, data, turns)
|
||||
local kind = KIND[id]
|
||||
if not kind then return data end
|
||||
local map = ROT[kind]
|
||||
turns = turns % 4
|
||||
for _ = 1, turns do
|
||||
local flags, d = 0, data
|
||||
if kind == "stairs" then
|
||||
flags = bit.band(d, 4); d = bit.band(d, 3)
|
||||
elseif kind == "door" or kind == "trapdoor" then
|
||||
flags = bit.band(d, bit.bnot(3)); d = bit.band(d, 3)
|
||||
end
|
||||
d = map[d] or d
|
||||
data = bit.bor(d, flags)
|
||||
end
|
||||
return data
|
||||
end
|
||||
|
||||
return L
|
||||
1574
mods/worldedit/main.lua
Normal file
76
package-windows.ps1
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
<#
|
||||
Builds the Windows client and dedicated server (Release, x64) and assembles
|
||||
ready to run folders:
|
||||
|
||||
dist\MinecraftPE-win64\ client (MinecraftPE.exe, data\, lua\, mods\)
|
||||
dist\MinecraftPE-server-win64\ server (MinecraftPE-server.exe, lua\, mods\)
|
||||
|
||||
Requirements: Visual Studio 2022 (C++ workload) and CMake. The first run downloads
|
||||
the dependencies (zlib, libpng, glfw, OpenAL Soft, LuaJIT, stb) with git.
|
||||
|
||||
.\package-windows.ps1 full build + package
|
||||
.\package-windows.ps1 -NoBuild only (re)assemble dist from an existing build
|
||||
.\package-windows.ps1 -Jobs 2 fewer parallel compiler jobs (low memory machines)
|
||||
#>
|
||||
param(
|
||||
[switch]$NoBuild,
|
||||
[int]$Jobs = 4
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = $PSScriptRoot
|
||||
$build = Join-Path $root 'build'
|
||||
$dist = Join-Path $root 'dist'
|
||||
|
||||
# The dependencies are cloned with git; drives that do not record file ownership make git refuse
|
||||
# that ("dubious ownership"). Tell git to trust directories for this process only.
|
||||
$env:GIT_CONFIG_COUNT = '1'
|
||||
$env:GIT_CONFIG_KEY_0 = 'safe.directory'
|
||||
$env:GIT_CONFIG_VALUE_0 = '*'
|
||||
|
||||
if (-not $NoBuild) {
|
||||
cmake -S $root -B $build -G 'Visual Studio 17 2022' -A x64
|
||||
if ($LASTEXITCODE -ne 0) { throw 'CMake configure failed' }
|
||||
|
||||
# OpenAL Soft needs a lot of memory per compiler process, so the compiler parallelism is limited
|
||||
cmake --build $build --config Release --parallel $Jobs -- /p:CL_MPCount=2
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Build failed' }
|
||||
}
|
||||
|
||||
$rel = Join-Path $build 'Release'
|
||||
foreach ($f in 'MinecraftPE.exe', 'MinecraftPE-server.exe') {
|
||||
if (-not (Test-Path (Join-Path $rel $f))) { throw "$f not found in $rel" }
|
||||
}
|
||||
|
||||
if (Test-Path $dist) { Remove-Item $dist -Recurse -Force }
|
||||
|
||||
# ---- client
|
||||
$client = Join-Path $dist 'MinecraftPE-win64'
|
||||
New-Item -ItemType Directory -Force $client | Out-Null
|
||||
Copy-Item (Join-Path $rel 'MinecraftPE.exe') $client
|
||||
Get-ChildItem $rel -Filter *.dll | Copy-Item -Destination $client
|
||||
Copy-Item (Join-Path $root 'data') $client -Recurse
|
||||
Copy-Item (Join-Path $root 'lua') $client -Recurse
|
||||
Copy-Item (Join-Path $root 'mods') $client -Recurse
|
||||
|
||||
# ---- server
|
||||
$server = Join-Path $dist 'MinecraftPE-server-win64'
|
||||
New-Item -ItemType Directory -Force $server | Out-Null
|
||||
Copy-Item (Join-Path $rel 'MinecraftPE-server.exe') $server
|
||||
Copy-Item (Join-Path $root 'lua') $server -Recurse
|
||||
Copy-Item (Join-Path $root 'mods') $server -Recurse
|
||||
@"
|
||||
port=19132
|
||||
level-dir=level
|
||||
level-cachepath=.
|
||||
level-externalpath=.
|
||||
gamemode=creative
|
||||
level-name=level
|
||||
view-distance=10
|
||||
"@ | Set-Content (Join-Path $server 'server.properties') -Encoding ascii
|
||||
Set-Content (Join-Path $server 'start-server.bat') "@echo off`r`nMinecraftPE-server.exe`r`npause" -Encoding ascii
|
||||
|
||||
Write-Host ''
|
||||
Write-Host 'Done:'
|
||||
Write-Host " $client"
|
||||
Write-Host " $server"
|
||||
|
|
@ -16,8 +16,8 @@ namespace SharedConstants
|
|||
{
|
||||
// 0.5.0 uses NPv8
|
||||
// 0.6.0 uses NPv9
|
||||
const int NetworkProtocolVersion = 9;
|
||||
const int NetworkProtocolLowestSupportedVersion = 9;
|
||||
const int NetworkProtocolVersion = 10;
|
||||
const int NetworkProtocolLowestSupportedVersion = 10;
|
||||
const int GameProtocolVersion = 1;
|
||||
const int GameProtocolLowestSupportedVersion = 1;
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
#include "client/Options.h"
|
||||
#include "client/player/input/IBuildInput.h"
|
||||
#include "commands/CommandManager.hpp"
|
||||
#include "lua/LuaEngine.h"
|
||||
#include "platform/input/Keyboard.h"
|
||||
#include "world/item/Item.h"
|
||||
#include "world/item/ItemInstance.h"
|
||||
|
|
@ -223,6 +224,7 @@ Minecraft::~Minecraft()
|
|||
screen = NULL;
|
||||
}
|
||||
#endif
|
||||
LuaEngine::get().stop();
|
||||
if (level != NULL) {
|
||||
level->saveGame();
|
||||
if (level->getChunkSource())
|
||||
|
|
@ -330,6 +332,8 @@ void Minecraft::leaveGame(bool renameLevel /*=false*/)
|
|||
level->getChunkSource()->saveAll(true);
|
||||
}
|
||||
|
||||
LuaEngine::get().stop();
|
||||
|
||||
LOGI("Clearing levels\n");
|
||||
|
||||
cameraTargetPlayer = NULL;
|
||||
|
|
@ -375,14 +379,22 @@ void Minecraft::prepareLevel(const std::string& title) {
|
|||
if (!level->isNew())
|
||||
level->setUpdateLights(false);
|
||||
|
||||
int Max = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH;
|
||||
// The world is infinite: only the area around the spawn point is generated
|
||||
// up front, everything else is streamed in around the players while playing.
|
||||
if (level->isNew() && !level->isClientSide) {
|
||||
level->setInitialSpawn(); // @note: should obviously be called from Level itself
|
||||
}
|
||||
const Pos spawn = level->getSharedSpawnPos();
|
||||
const int spawnCx = spawn.x >> 4;
|
||||
const int spawnCz = spawn.z >> 4;
|
||||
const int PrepareRadius = level->isClientSide ? -1 : 4; // a client gets its chunks from the server
|
||||
const int Max = (2 * PrepareRadius + 1) * (2 * PrepareRadius + 1);
|
||||
int pp = 0;
|
||||
for (int x = 8; x < (LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH); x += LevelConstants::CHUNK_WIDTH) {
|
||||
for (int z = 8; z < (LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH); z += LevelConstants::CHUNK_WIDTH) {
|
||||
progressStagePercentage = 100 * pp++ / Max;
|
||||
//printf("level generation progress %d\n", progressStagePercentage);
|
||||
for (int cx = spawnCx - PrepareRadius; cx <= spawnCx + PrepareRadius; cx++) {
|
||||
for (int cz = spawnCz - PrepareRadius; cz <= spawnCz + PrepareRadius; cz++) {
|
||||
progressStagePercentage = 100 * pp++ / Max;
|
||||
B.start();
|
||||
level->getTile(x, 64, z);
|
||||
level->getChunk(cx, cz);
|
||||
B.stop();
|
||||
L.start();
|
||||
if (level->isNew())
|
||||
|
|
@ -395,11 +407,12 @@ void Minecraft::prepareLevel(const std::string& title) {
|
|||
level->setUpdateLights(true);
|
||||
|
||||
C.start();
|
||||
for (int x = 0; x < LevelConstants::CHUNK_CACHE_WIDTH; x++)
|
||||
{
|
||||
for (int z = 0; z < LevelConstants::CHUNK_CACHE_WIDTH; z++)
|
||||
std::vector<LevelChunk*> loadedChunks;
|
||||
level->getChunkSource()->getLoadedChunks(loadedChunks);
|
||||
for (unsigned int i = 0; i < loadedChunks.size(); i++)
|
||||
{
|
||||
LevelChunk* chunk = level->getChunk(x, z);
|
||||
LevelChunk* chunk = loadedChunks[i];
|
||||
if (chunk && !chunk->createdFromSave)
|
||||
{
|
||||
chunk->unsaved = false;
|
||||
|
|
@ -412,7 +425,6 @@ void Minecraft::prepareLevel(const std::string& title) {
|
|||
LOGI("status: 3\n");
|
||||
progressStageStatusId = 3;
|
||||
if (level->isNew()) {
|
||||
level->setInitialSpawn(); // @note: should obviously be called from Level itself
|
||||
level->saveLevelData();
|
||||
level->getChunkSource()->saveAll(false);
|
||||
level->saveGame();
|
||||
|
|
@ -570,6 +582,10 @@ void Minecraft::tick(int nTick, int maxTick) {
|
|||
TIMER_POP_PUSH("level");
|
||||
level->tickEntities();
|
||||
level->tick();
|
||||
if (!level->isClientSide) LuaEngine::get().tick();
|
||||
if (level->isClientSide && netCallback && !raknetInstance->isServer()) {
|
||||
((ClientSideNetworkHandler*)netCallback)->updateChunks();
|
||||
}
|
||||
#ifndef STANDALONE_SERVER
|
||||
TIMER_POP_PUSH("animateTick");
|
||||
if (player) {
|
||||
|
|
@ -1473,6 +1489,8 @@ void Minecraft::_levelGenerated()
|
|||
level->loadPlayer(player, true);
|
||||
// if we are client side, we trust the server to have given us a correct position
|
||||
if (player && !level->isClientSide) {
|
||||
// the saved position can be anywhere in the (infinite) world
|
||||
level->ensureChunksAround((int)player->x, (int)player->z, 3);
|
||||
player->resetPos(false);
|
||||
}
|
||||
|
||||
|
|
@ -1493,6 +1511,11 @@ void Minecraft::_levelGenerated()
|
|||
netCallback->levelGenerated(level);
|
||||
}
|
||||
|
||||
// Lua mods run where the world is hosted
|
||||
if (!level->isClientSide) {
|
||||
LuaEngine::get().start(this);
|
||||
}
|
||||
|
||||
#if defined(WIN32) || defined(RPI)
|
||||
if (_commandServer) {
|
||||
delete _commandServer;
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@
|
|||
#include "../renderer/LevelRenderer.h"
|
||||
#endif
|
||||
#include "../../world/level/material/Material.h"
|
||||
#include "../../lua/LuaEngine.h"
|
||||
|
||||
GameMode::GameMode( Minecraft* minecraft)
|
||||
: minecraft(minecraft),
|
||||
|
|
@ -59,6 +60,9 @@ bool GameMode::destroyBlock(int x, int y, int z, int face) {
|
|||
if (!oldTile)
|
||||
return false;
|
||||
|
||||
if (!level->isClientSide && minecraft->player && LuaEngine::get().onBlockBreak(minecraft->player, x, y, z))
|
||||
return false; // cancelled by a Lua mod
|
||||
|
||||
if (level->adventureSettings.immutableWorld) {
|
||||
if (oldTile != (Tile*)Tile::leaves
|
||||
&& oldTile->material != Material::plant) {
|
||||
|
|
@ -89,6 +93,8 @@ bool GameMode::useItemOn(Player* player, Level* level, ItemInstance* item, int x
|
|||
float clickX = hit.x - x;
|
||||
float clickY = hit.y - y;
|
||||
float clickZ = hit.z - z;
|
||||
if (!level->isClientSide && player == minecraft->player && LuaEngine::get().onUseItem(player, x, y, z, face, item))
|
||||
return true; // cancelled by a Lua mod
|
||||
if (level->isClientSide) {
|
||||
LOGI("%f %f %f \n", player->x, player->y, player->z);
|
||||
|
||||
|
|
|
|||
|
|
@ -9,6 +9,17 @@
|
|||
#include "../../../network/packet/MessagePacket.h"
|
||||
#include "../../../platform/log.h"
|
||||
#include "util/StringUtils.h"
|
||||
#include "../../../network/packet/SetSkinPacket.h"
|
||||
#include <vector>
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
#include <sstream>
|
||||
#include <cstdlib>
|
||||
|
|
@ -63,6 +74,11 @@ void ConsoleScreen::execute()
|
|||
return minecraft->setScreen(NULL);
|
||||
}
|
||||
|
||||
if (_input == "/skin" || _input.compare(0, 6, "/skin ") == 0) {
|
||||
executeSkinCommand(_input.size() > 6 ? Util::stringTrim(_input.substr(6)) : "");
|
||||
return minecraft->setScreen(NULL);
|
||||
}
|
||||
|
||||
if (minecraft->netCallback && !minecraft->raknetInstance->isServer()) {
|
||||
MessagePacket packet(_input.c_str());
|
||||
minecraft->raknetInstance->send(packet);
|
||||
|
|
@ -89,6 +105,62 @@ void ConsoleScreen::execute()
|
|||
minecraft->setScreen(NULL);
|
||||
}
|
||||
|
||||
// /skin [list|auto|<name>]: purely client side, the choice is announced to the server
|
||||
void ConsoleScreen::executeSkinCommand(const std::string& arg)
|
||||
{
|
||||
const std::string dir = "data/images/skins/";
|
||||
std::vector<std::string> names;
|
||||
#ifdef _WIN32
|
||||
WIN32_FIND_DATAA fd;
|
||||
HANDLE h = FindFirstFileA((dir + "*.png").c_str(), &fd);
|
||||
if (h != INVALID_HANDLE_VALUE) {
|
||||
do {
|
||||
std::string n = fd.cFileName;
|
||||
names.push_back(n.substr(0, n.size() - 4));
|
||||
} while (FindNextFileA(h, &fd));
|
||||
FindClose(h);
|
||||
}
|
||||
#endif
|
||||
|
||||
if (arg.empty() || arg == "list") {
|
||||
std::string line = "Skins:";
|
||||
for (size_t i = 0; i < names.size(); ++i) line += " " + names[i];
|
||||
minecraft->gui.addMessage(line);
|
||||
minecraft->gui.addMessage("Use /skin <name>, or /skin auto for the one of your account.");
|
||||
return;
|
||||
}
|
||||
|
||||
LocalPlayer* player = minecraft->player;
|
||||
if (!player) return;
|
||||
|
||||
if (arg == "auto") {
|
||||
minecraft->options.set(OPTIONS_SKIN, std::string("Default"));
|
||||
minecraft->options.save();
|
||||
player->skinName.clear();
|
||||
player->setTextureName("skins/" + player->name + ".png");
|
||||
minecraft->gui.addMessage("Skin reset, it is picked from your username after a restart.");
|
||||
return;
|
||||
}
|
||||
|
||||
bool found = false;
|
||||
for (size_t i = 0; i < names.size(); ++i) if (names[i] == arg) found = true;
|
||||
if (!found) {
|
||||
minecraft->gui.addMessage("No skin named '" + arg + "'. Try /skin list");
|
||||
return;
|
||||
}
|
||||
|
||||
minecraft->options.set(OPTIONS_SKIN, arg);
|
||||
minecraft->options.save();
|
||||
player->skinName = arg;
|
||||
player->setTextureName("skins/" + arg + ".png");
|
||||
minecraft->gui.addMessage("You now wear the '" + arg + "' skin.");
|
||||
|
||||
if (minecraft->level && (minecraft->level->isClientSide || minecraft->raknetInstance->isServer())) {
|
||||
SetSkinPacket packet(player->entityId, arg);
|
||||
minecraft->raknetInstance->send(packet);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// render
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ public:
|
|||
|
||||
private:
|
||||
void execute();
|
||||
void executeSkinCommand(const std::string& arg);
|
||||
|
||||
std::string _input;
|
||||
int _cursorBlink; // tick counter for cursor blink
|
||||
|
|
|
|||
|
|
@ -370,9 +370,18 @@ LocalPlayer::LocalPlayer(Minecraft* minecraft, Level* level, const std::string&
|
|||
|
||||
this->name = minecraft->options.getStringValue(OPTIONS_USERNAME);
|
||||
printf("test \n");
|
||||
// A skin picked with /skin wins over the one from the Mojang servers
|
||||
const std::string chosenSkin = minecraft->options.getStringValue(OPTIONS_SKIN);
|
||||
const bool hasChosenSkin = !chosenSkin.empty() && chosenSkin != "Default"
|
||||
&& fileExists("data/images/skins/" + chosenSkin + ".png");
|
||||
if (hasChosenSkin) {
|
||||
textureName = "skins/" + chosenSkin + ".png";
|
||||
skinName = chosenSkin;
|
||||
}
|
||||
|
||||
// Fetch user skin and cape from Mojang servers in the background (avoids blocking the main thread)
|
||||
// TODO: Fix this memory leak
|
||||
new CThread(fetchSkinForPlayer, this);
|
||||
if (!hasChosenSkin) new CThread(fetchSkinForPlayer, this);
|
||||
new CThread(fetchCapeForPlayer, this);
|
||||
}
|
||||
#endif
|
||||
|
|
|
|||
|
|
@ -99,6 +99,14 @@ void Chunk::rebuild()
|
|||
|
||||
LevelChunk::touchedSky = false;
|
||||
|
||||
// The world is streamed in: wait until this part and its surroundings exist.
|
||||
// (the chunk cache marks the area dirty again once more chunks arrive)
|
||||
if (!level->hasChunksAt(x0 - 1, 0, z0 - 1, x1 + 1, 1, z1 + 1)) {
|
||||
skyLit = false;
|
||||
compiled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
int r = 1;
|
||||
Region region(level, x0 - r, y0 - r, z0 - r, x1 + r, y1 + r, z1 + r);
|
||||
TileRenderer tileRenderer(®ion);
|
||||
|
|
|
|||
|
|
@ -69,7 +69,8 @@ LevelRenderer::LevelRenderer( Minecraft* mc)
|
|||
destroyProgress(0)
|
||||
{
|
||||
#ifdef OPENGL_ES
|
||||
int maxChunksWidth = 2 * LevelConstants::LEVEL_WIDTH / CHUNK_SIZE + 1;
|
||||
// enough render chunks for the largest possible view distance (400 blocks, see allChanged)
|
||||
int maxChunksWidth = 400 / CHUNK_SIZE + 1;
|
||||
numListsOrBuffers = maxChunksWidth * maxChunksWidth * (128/CHUNK_SIZE) * 3;
|
||||
chunkBuffers = new GLuint[numListsOrBuffers];
|
||||
glGenBuffers2(numListsOrBuffers, chunkBuffers);
|
||||
|
|
@ -209,6 +210,14 @@ void LevelRenderer::allChanged()
|
|||
/*
|
||||
* if (Minecraft.FLYBY_MODE) { dist = 512 - CHUNK_SIZE * 2; }
|
||||
*/
|
||||
|
||||
// The world is infinite: keep as many chunks around the player as can be seen
|
||||
{
|
||||
int chunkRadius = dist / 16 + 2;
|
||||
if (chunkRadius < 4) chunkRadius = 4;
|
||||
if (chunkRadius > 16) chunkRadius = 16;
|
||||
LevelConstants::VIEW_DISTANCE_CHUNKS = chunkRadius;
|
||||
}
|
||||
xChunks = (dist / LevelRenderer::CHUNK_SIZE) + 1;
|
||||
yChunks = (128 / LevelRenderer::CHUNK_SIZE);
|
||||
zChunks = (dist / LevelRenderer::CHUNK_SIZE) + 1;
|
||||
|
|
|
|||
228
src/client/sound/MusicPlayer.cpp
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
#include "MusicPlayer.h"
|
||||
|
||||
#if defined(PLATFORM_DESKTOP) && !defined(NO_SOUND)
|
||||
|
||||
#include <AL/al.h>
|
||||
#include <AL/alc.h>
|
||||
|
||||
#define STB_VORBIS_HEADER_ONLY
|
||||
#include "stb_vorbis.c"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
#include <chrono>
|
||||
|
||||
#include "../../platform/log.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <dirent.h>
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
const char* MUSIC_DIR = "data/music";
|
||||
const int BUFFER_COUNT = 4;
|
||||
const int FRAMES_PER_BUFFER = 32768;
|
||||
|
||||
double now() {
|
||||
using namespace std::chrono;
|
||||
return duration_cast<duration<double> >(steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
bool endsWith(const std::string& s, const char* suffix) {
|
||||
std::string suf(suffix);
|
||||
if (s.size() < suf.size()) return false;
|
||||
for (size_t i = 0; i < suf.size(); ++i)
|
||||
if (tolower((unsigned char)s[s.size() - suf.size() + i]) != suf[i]) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
MusicPlayer::MusicPlayer()
|
||||
: scanned(false),
|
||||
alReady(false),
|
||||
state(Waiting),
|
||||
nextStart(0),
|
||||
lastTrack(-1),
|
||||
source(0),
|
||||
decoder(NULL),
|
||||
channels(2),
|
||||
sampleRate(44100),
|
||||
decoderDone(false)
|
||||
{
|
||||
for (int i = 0; i < BUFFER_COUNT; ++i) buffers[i] = 0;
|
||||
srand((unsigned int)time(NULL));
|
||||
}
|
||||
|
||||
MusicPlayer::~MusicPlayer()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
void MusicPlayer::scan()
|
||||
{
|
||||
scanned = true;
|
||||
tracks.clear();
|
||||
#ifdef _WIN32
|
||||
WIN32_FIND_DATAA fd;
|
||||
HANDLE h = FindFirstFileA((std::string(MUSIC_DIR) + "/*").c_str(), &fd);
|
||||
if (h != INVALID_HANDLE_VALUE) {
|
||||
do {
|
||||
std::string name = fd.cFileName;
|
||||
if (endsWith(name, ".ogg")) tracks.push_back(std::string(MUSIC_DIR) + "/" + name);
|
||||
} while (FindNextFileA(h, &fd));
|
||||
FindClose(h);
|
||||
}
|
||||
#else
|
||||
if (DIR* d = opendir(MUSIC_DIR)) {
|
||||
while (dirent* e = readdir(d)) {
|
||||
std::string name = e->d_name;
|
||||
if (endsWith(name, ".ogg")) tracks.push_back(std::string(MUSIC_DIR) + "/" + name);
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
#endif
|
||||
LOGI("MusicPlayer: %d tracks found in %s\n", (int)tracks.size(), MUSIC_DIR);
|
||||
nextStart = now() + 8.0; // let the world appear before the first track
|
||||
}
|
||||
|
||||
void MusicPlayer::closeTrack()
|
||||
{
|
||||
if (source) {
|
||||
alSourceStop(source);
|
||||
ALint queued = 0;
|
||||
alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
|
||||
while (queued-- > 0) {
|
||||
ALuint b;
|
||||
alSourceUnqueueBuffers(source, 1, &b);
|
||||
}
|
||||
}
|
||||
if (decoder) {
|
||||
stb_vorbis_close(decoder);
|
||||
decoder = NULL;
|
||||
}
|
||||
state = Waiting;
|
||||
trackName.clear();
|
||||
}
|
||||
|
||||
void MusicPlayer::stop()
|
||||
{
|
||||
if (!alReady) return;
|
||||
closeTrack();
|
||||
if (source) alDeleteSources(1, &source);
|
||||
alDeleteBuffers(BUFFER_COUNT, buffers);
|
||||
source = 0;
|
||||
alReady = false;
|
||||
}
|
||||
|
||||
bool MusicPlayer::fillBuffer(unsigned int buffer)
|
||||
{
|
||||
if (decoderDone || !decoder) return false;
|
||||
pcm.resize((size_t)FRAMES_PER_BUFFER * channels);
|
||||
int frames = stb_vorbis_get_samples_short_interleaved(decoder, channels, &pcm[0], FRAMES_PER_BUFFER * channels);
|
||||
if (frames <= 0) {
|
||||
decoderDone = true;
|
||||
return false;
|
||||
}
|
||||
alBufferData(buffer, channels == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16, &pcm[0],
|
||||
frames * channels * (int)sizeof(short), sampleRate);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MusicPlayer::startTrack(const std::string& path)
|
||||
{
|
||||
int error = 0;
|
||||
decoder = stb_vorbis_open_filename(path.c_str(), &error, NULL);
|
||||
if (!decoder) {
|
||||
LOGE("MusicPlayer: cannot open %s (%d)\n", path.c_str(), error);
|
||||
return false;
|
||||
}
|
||||
stb_vorbis_info info = stb_vorbis_get_info(decoder);
|
||||
channels = info.channels > 1 ? 2 : 1;
|
||||
sampleRate = (int)info.sample_rate;
|
||||
decoderDone = false;
|
||||
|
||||
int queued = 0;
|
||||
for (int i = 0; i < BUFFER_COUNT; ++i) {
|
||||
if (!fillBuffer(buffers[i])) break;
|
||||
alSourceQueueBuffers(source, 1, &buffers[i]);
|
||||
++queued;
|
||||
}
|
||||
if (queued == 0) {
|
||||
stb_vorbis_close(decoder);
|
||||
decoder = NULL;
|
||||
return false;
|
||||
}
|
||||
alSourcePlay(source);
|
||||
state = Playing;
|
||||
|
||||
size_t slash = path.find_last_of('/');
|
||||
trackName = path.substr(slash == std::string::npos ? 0 : slash + 1);
|
||||
LOGI("MusicPlayer: now playing %s\n", trackName.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
void MusicPlayer::update(float volume)
|
||||
{
|
||||
if (!scanned) scan();
|
||||
if (tracks.empty()) return;
|
||||
|
||||
// the OpenAL context is created by the sound system
|
||||
if (!alReady) {
|
||||
if (!alcGetCurrentContext()) return;
|
||||
alGenSources(1, &source);
|
||||
alGenBuffers(BUFFER_COUNT, buffers);
|
||||
alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE);
|
||||
alSource3f(source, AL_POSITION, 0, 0, 0);
|
||||
alSourcef(source, AL_ROLLOFF_FACTOR, 0);
|
||||
alReady = true;
|
||||
}
|
||||
|
||||
if (volume <= 0.0f) {
|
||||
if (state == Playing) closeTrack();
|
||||
return;
|
||||
}
|
||||
|
||||
if (state == Waiting) {
|
||||
if (now() < nextStart) return;
|
||||
int pick = rand() % (int)tracks.size();
|
||||
if (tracks.size() > 1 && pick == lastTrack) pick = (pick + 1) % (int)tracks.size();
|
||||
lastTrack = pick;
|
||||
if (!startTrack(tracks[pick])) nextStart = now() + 20.0;
|
||||
else alSourcef(source, AL_GAIN, volume * 0.6f);
|
||||
return;
|
||||
}
|
||||
|
||||
// Playing: keep the queue filled
|
||||
alSourcef(source, AL_GAIN, volume * 0.6f);
|
||||
|
||||
ALint processed = 0;
|
||||
alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
|
||||
while (processed-- > 0) {
|
||||
ALuint b;
|
||||
alSourceUnqueueBuffers(source, 1, &b);
|
||||
if (fillBuffer(b)) alSourceQueueBuffers(source, 1, &b);
|
||||
}
|
||||
|
||||
ALint queued = 0, srcState = 0;
|
||||
alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
|
||||
alGetSourcei(source, AL_SOURCE_STATE, &srcState);
|
||||
if (queued == 0) {
|
||||
// finished: pause for a while before the next track
|
||||
closeTrack();
|
||||
nextStart = now() + 45.0 + (rand() % 120);
|
||||
} else if (srcState != AL_PLAYING) {
|
||||
alSourcePlay(source); // underrun
|
||||
}
|
||||
}
|
||||
|
||||
#endif // PLATFORM_DESKTOP
|
||||
48
src/client/sound/MusicPlayer.h
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct stb_vorbis;
|
||||
|
||||
/**
|
||||
* Plays the OGG tracks found in "data/music" in random order with pauses in
|
||||
* between, streamed through OpenAL. Volume comes from the music volume option.
|
||||
* Needs the OpenAL context created by SoundSystemAL.
|
||||
*/
|
||||
class MusicPlayer {
|
||||
public:
|
||||
MusicPlayer();
|
||||
~MusicPlayer();
|
||||
|
||||
// Call once per frame. `volume` is 0..1.
|
||||
void update(float volume);
|
||||
|
||||
void stop();
|
||||
const std::string& currentTrack() const { return trackName; }
|
||||
|
||||
private:
|
||||
void scan();
|
||||
bool startTrack(const std::string& path);
|
||||
bool fillBuffer(unsigned int buffer);
|
||||
void closeTrack();
|
||||
|
||||
enum State { Waiting, Playing };
|
||||
|
||||
bool scanned;
|
||||
bool alReady;
|
||||
State state;
|
||||
double nextStart;
|
||||
int lastTrack;
|
||||
|
||||
std::vector<std::string> tracks;
|
||||
std::string trackName;
|
||||
|
||||
unsigned int source;
|
||||
unsigned int buffers[4];
|
||||
stb_vorbis* decoder;
|
||||
int channels;
|
||||
int sampleRate;
|
||||
std::vector<short> pcm;
|
||||
bool decoderDone;
|
||||
};
|
||||
|
|
@ -169,6 +169,9 @@ void SoundEngine::destroy()
|
|||
|
||||
void SoundEngine::update( Mob* player, float a )
|
||||
{
|
||||
#if defined(PLATFORM_DESKTOP) && !defined(NO_SOUND)
|
||||
music.update(options ? options->getProgressValue(OPTIONS_MUSIC_VOLUME) : 0.0f);
|
||||
#endif
|
||||
if (/*!loaded || */options->getProgressValue(OPTIONS_SOUND_VOLUME) == 0) return;
|
||||
if (player == NULL) return;
|
||||
|
||||
|
|
|
|||
|
|
@ -17,6 +17,10 @@ class Minecraft;
|
|||
class Mob;
|
||||
class Options;
|
||||
|
||||
#if defined(PLATFORM_DESKTOP) && !defined(NO_SOUND)
|
||||
#include "MusicPlayer.h"
|
||||
#endif
|
||||
|
||||
class SoundEngine
|
||||
{
|
||||
static const int SOUND_DISTANCE = 16;
|
||||
|
|
@ -29,6 +33,10 @@ class SoundEngine
|
|||
SoundSystem soundSystem;
|
||||
#endif
|
||||
|
||||
#if defined(PLATFORM_DESKTOP) && !defined(NO_SOUND)
|
||||
MusicPlayer music;
|
||||
#endif
|
||||
|
||||
Options* options;
|
||||
int idCounter;
|
||||
//static bool loaded;
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@
|
|||
#include "network/packet/ChatPacket.h"
|
||||
#include "network/RakNetInstance.h"
|
||||
#include "world/level/Level.h"
|
||||
#include "lua/LuaEngine.h"
|
||||
|
||||
CommandManager::CommandManager() {
|
||||
registerAllCommands();
|
||||
|
|
@ -31,6 +32,9 @@ std::vector<std::string> CommandManager::getListAllCommands() {
|
|||
for (auto& cmd : m_commands) {
|
||||
ret.push_back(cmd->getName());
|
||||
}
|
||||
for (auto& name : LuaEngine::get().commandNames()) {
|
||||
ret.push_back(name);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
|
@ -45,15 +49,20 @@ std::string CommandManager::execute(Minecraft& mc, Player& player, const std::st
|
|||
return it->getName() == cmd;
|
||||
});
|
||||
|
||||
if (it == m_commands.end()) {
|
||||
return "Command /" + cmd + " not found";
|
||||
}
|
||||
|
||||
std::vector<std::string> args;
|
||||
|
||||
std::string tok;
|
||||
while (ss >> tok) args.push_back(tok);
|
||||
|
||||
if (it == m_commands.end()) {
|
||||
// maybe a command registered by a Lua mod
|
||||
std::string reply;
|
||||
if (LuaEngine::get().runCommand(&player, cmd, args, reply)) {
|
||||
return reply;
|
||||
}
|
||||
return "Command /" + cmd + " not found";
|
||||
}
|
||||
|
||||
return (*it)->execute(mc, player, args);
|
||||
}
|
||||
|
||||
|
|
|
|||
628
src/lua/LuaEngine.cpp
Normal file
|
|
@ -0,0 +1,628 @@
|
|||
#include "LuaEngine.h"
|
||||
|
||||
extern "C" {
|
||||
#include "lua.h"
|
||||
#include "lauxlib.h"
|
||||
#include "lualib.h"
|
||||
}
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <algorithm>
|
||||
|
||||
#include "client/Minecraft.h"
|
||||
#include "network/RakNetInstance.h"
|
||||
#include "network/ServerSideNetworkHandler.h"
|
||||
#include "network/packet/ChatPacket.h"
|
||||
#include "network/packet/ChunkDataPacket.h"
|
||||
#include "network/packet/MovePlayerPacket.h"
|
||||
#include "network/packet/SendInventoryPacket.h"
|
||||
#include "network/packet/UpdateBlockPacket.h"
|
||||
#include "platform/log.h"
|
||||
#include "raknet/RakPeerInterface.h"
|
||||
#include "raknet/PacketPriority.h"
|
||||
#include "world/entity/EntityTypes.h"
|
||||
#include "world/entity/MobFactory.h"
|
||||
#include "world/entity/item/ItemEntity.h"
|
||||
#include "world/entity/player/Inventory.h"
|
||||
#include "world/entity/player/Player.h"
|
||||
#include "world/item/Item.h"
|
||||
#include "world/item/ItemInstance.h"
|
||||
#include "world/level/Level.h"
|
||||
#include "world/level/LightLayer.h"
|
||||
#include "world/level/LevelConstants.h"
|
||||
#include "world/level/chunk/LevelChunk.h"
|
||||
#include "world/level/material/Material.h"
|
||||
#include "world/level/tile/Tile.h"
|
||||
#include "world/phys/HitResult.h"
|
||||
#include "util/Mth.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <direct.h>
|
||||
#define MKDIR(p) _mkdir(p)
|
||||
#else
|
||||
#include <dirent.h>
|
||||
#include <sys/stat.h>
|
||||
#define MKDIR(p) mkdir(p, 0755)
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
Minecraft* MC() { return LuaEngine::get().minecraft(); }
|
||||
Level* LV() { Minecraft* m = MC(); return m ? m->level : NULL; }
|
||||
|
||||
Player* findPlayer(int id) {
|
||||
Level* level = LV();
|
||||
if (!level) return NULL;
|
||||
for (unsigned int i = 0; i < level->players.size(); ++i)
|
||||
if (level->players[i]->entityId == id) return level->players[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
ServerSideNetworkHandler* server() {
|
||||
Minecraft* m = MC();
|
||||
if (m && m->raknetInstance && m->raknetInstance->isServer() && m->netCallback)
|
||||
return (ServerSideNetworkHandler*)m->netCallback;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
bool isLocalPlayer(Player* p) {
|
||||
return (Entity*)p == (Entity*)MC()->player;
|
||||
}
|
||||
|
||||
void sendChat(Player* p, const std::string& text) {
|
||||
if (!p) return;
|
||||
if (isLocalPlayer(p)) {
|
||||
#ifndef STANDALONE_SERVER
|
||||
MC()->gui.addMessage(text);
|
||||
#else
|
||||
LOGI("%s\n", text.c_str());
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
if (ServerSideNetworkHandler* s = server()) {
|
||||
ChatPacket packet(text);
|
||||
RakNet::BitStream bs;
|
||||
packet.write(&bs);
|
||||
MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, p->owner, false);
|
||||
}
|
||||
}
|
||||
|
||||
void broadcastChat(const std::string& text) {
|
||||
#ifndef STANDALONE_SERVER
|
||||
if (MC()->player) MC()->gui.addMessage(text);
|
||||
#else
|
||||
LOGI("%s\n", text.c_str());
|
||||
#endif
|
||||
if (server()) {
|
||||
ChatPacket packet(text);
|
||||
RakNet::BitStream bs;
|
||||
packet.write(&bs);
|
||||
MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- bulk edits: blocks are written silently and the touched chunks are re-sent once at the end
|
||||
struct DirtyBox { int x0, y0, z0, x1, y1, z1; };
|
||||
std::map<long long, DirtyBox> g_dirty;
|
||||
|
||||
void markDirty(int x, int y, int z) {
|
||||
const long long key = LevelConstants::chunkKey(x >> 4, z >> 4);
|
||||
std::map<long long, DirtyBox>::iterator it = g_dirty.find(key);
|
||||
if (it == g_dirty.end()) {
|
||||
DirtyBox b = { x, y, z, x, y, z };
|
||||
g_dirty[key] = b;
|
||||
} else {
|
||||
DirtyBox& b = it->second;
|
||||
if (x < b.x0) b.x0 = x; if (x > b.x1) b.x1 = x;
|
||||
if (y < b.y0) b.y0 = y; if (y > b.y1) b.y1 = y;
|
||||
if (z < b.z0) b.z0 = z; if (z > b.z1) b.z1 = z;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- lua helpers
|
||||
int argInt(lua_State* L, int i) { return (int)lua_tointeger(L, i); }
|
||||
float argNum(lua_State* L, int i) { return (float)lua_tonumber(L, i); }
|
||||
|
||||
// ================================================================== world
|
||||
int l_get_block(lua_State* L) {
|
||||
Level* level = LV();
|
||||
int x = argInt(L, 1), y = argInt(L, 2), z = argInt(L, 3);
|
||||
lua_pushinteger(L, level->getTile(x, y, z));
|
||||
lua_pushinteger(L, level->getData(x, y, z));
|
||||
return 2;
|
||||
}
|
||||
|
||||
int l_set_block(lua_State* L) {
|
||||
Level* level = LV();
|
||||
int x = argInt(L, 1), y = argInt(L, 2), z = argInt(L, 3);
|
||||
int id = argInt(L, 4), data = argInt(L, 5);
|
||||
bool silent = lua_toboolean(L, 6) != 0;
|
||||
if (y < 0 || y >= LevelConstants::LEVEL_HEIGHT || id < 0 || id > 255 || (id > 0 && !Tile::tiles[id])) {
|
||||
lua_pushboolean(L, 0);
|
||||
return 1;
|
||||
}
|
||||
bool changed;
|
||||
if (silent) {
|
||||
changed = level->setTileAndDataNoUpdate(x, y, z, id, data & 15);
|
||||
if (changed) markDirty(x, y, z);
|
||||
} else {
|
||||
changed = level->setTileAndData(x, y, z, id, data & 15);
|
||||
}
|
||||
lua_pushboolean(L, changed);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int l_flush(lua_State* L) {
|
||||
Level* level = LV();
|
||||
ServerSideNetworkHandler* srv = server();
|
||||
int count = 0;
|
||||
for (std::map<long long, DirtyBox>::iterator it = g_dirty.begin(); it != g_dirty.end(); ++it) {
|
||||
DirtyBox& b = it->second;
|
||||
const int cx = b.x0 >> 4, cz = b.z0 >> 4;
|
||||
|
||||
// lighting of the touched volume
|
||||
const int y0 = (b.y0 - 1 < 0) ? 0 : b.y0 - 1;
|
||||
const int y1 = (b.y1 + 1 > LevelConstants::LEVEL_HEIGHT - 1) ? LevelConstants::LEVEL_HEIGHT - 1 : b.y1 + 1;
|
||||
level->updateLight(LightLayer::Sky, b.x0 - 1, y0, b.z0 - 1, b.x1 + 1, y1, b.z1 + 1);
|
||||
level->updateLight(LightLayer::Block, b.x0 - 1, y0, b.z0 - 1, b.x1 + 1, y1, b.z1 + 1);
|
||||
level->setTilesDirty(b.x0 - 1, y0, b.z0 - 1, b.x1 + 1, y1, b.z1 + 1);
|
||||
|
||||
if (srv) {
|
||||
LevelChunk* chunk = level->getChunk(cx, cz);
|
||||
ChunkDataPacket packet(cx, cz, chunk);
|
||||
RakNet::BitStream bs;
|
||||
packet.write(&bs);
|
||||
MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
|
||||
}
|
||||
++count;
|
||||
}
|
||||
g_dirty.clear();
|
||||
lua_pushinteger(L, count);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int l_solid_height(lua_State* L) {
|
||||
Level* level = LV();
|
||||
int x = argInt(L, 1), z = argInt(L, 2);
|
||||
for (int y = LevelConstants::LEVEL_HEIGHT - 1; y >= 0; --y) {
|
||||
int id = level->getTile(x, y, z);
|
||||
if (id > 0 && Tile::tiles[id] && Tile::tiles[id]->material->blocksMotion()) {
|
||||
lua_pushinteger(L, y);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
lua_pushinteger(L, -1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int l_loaded(lua_State* L) {
|
||||
lua_pushboolean(L, LV()->hasChunkAt(argInt(L, 1), 64, argInt(L, 2)));
|
||||
return 1;
|
||||
}
|
||||
|
||||
int l_ensure(lua_State* L) {
|
||||
LV()->ensureChunksAround(argInt(L, 1), argInt(L, 2), argInt(L, 3));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int l_get_time(lua_State* L) { lua_pushinteger(L, LV()->getTime()); return 1; }
|
||||
int l_set_time(lua_State* L) { LV()->setTime(argInt(L, 1)); return 0; }
|
||||
int l_seed(lua_State* L) { lua_pushnumber(L, (double)LV()->getSeed()); return 1; }
|
||||
|
||||
int l_explode(lua_State* L) {
|
||||
LV()->explode(NULL, argNum(L, 1), argNum(L, 2), argNum(L, 3), argNum(L, 4));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int l_spawn_mob(lua_State* L) {
|
||||
Level* level = LV();
|
||||
Mob* mob = MobFactory::CreateMob(argInt(L, 1), level);
|
||||
if (!mob) { lua_pushnil(L); return 1; }
|
||||
mob->moveTo(argNum(L, 2), argNum(L, 3), argNum(L, 4), 0, 0);
|
||||
level->addEntity(mob);
|
||||
lua_pushinteger(L, mob->entityId);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int l_drop_item(lua_State* L) {
|
||||
Level* level = LV();
|
||||
ItemInstance item(argInt(L, 1), argInt(L, 2), argInt(L, 3));
|
||||
level->addEntity(new ItemEntity(level, argNum(L, 4), argNum(L, 5), argNum(L, 6), item));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// butcher(x, y, z, radius, includeFriendly) -> count
|
||||
int l_butcher(lua_State* L) {
|
||||
Level* level = LV();
|
||||
float x = argNum(L, 1), y = argNum(L, 2), z = argNum(L, 3), r = argNum(L, 4);
|
||||
bool friendly = lua_toboolean(L, 5) != 0;
|
||||
int n = 0;
|
||||
for (unsigned int i = 0; i < level->entities.size(); ++i) {
|
||||
Entity* e = level->entities[i];
|
||||
if (e->removed || !e->isMob() || e->isPlayer()) continue;
|
||||
if (!friendly && e->getCreatureBaseType() != MobTypes::BaseEnemy) continue;
|
||||
float dx = e->x - x, dy = e->y - y, dz = e->z - z;
|
||||
if (r > 0 && dx * dx + dy * dy + dz * dz > r * r) continue;
|
||||
e->remove();
|
||||
++n;
|
||||
}
|
||||
lua_pushinteger(L, n);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ================================================================== players
|
||||
int l_players(lua_State* L) {
|
||||
Level* level = LV();
|
||||
lua_newtable(L);
|
||||
int n = 0;
|
||||
for (unsigned int i = 0; i < level->players.size(); ++i) {
|
||||
lua_pushinteger(L, level->players[i]->entityId);
|
||||
lua_rawseti(L, -2, ++n);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
int l_pname(lua_State* L) {
|
||||
Player* p = findPlayer(argInt(L, 1));
|
||||
if (!p) { lua_pushnil(L); return 1; }
|
||||
lua_pushstring(L, p->name.c_str());
|
||||
return 1;
|
||||
}
|
||||
|
||||
int l_ppos(lua_State* L) {
|
||||
Player* p = findPlayer(argInt(L, 1));
|
||||
if (!p) return 0;
|
||||
lua_pushnumber(L, p->x);
|
||||
lua_pushnumber(L, p->y - p->heightOffset); // feet
|
||||
lua_pushnumber(L, p->z);
|
||||
lua_pushnumber(L, p->yRot);
|
||||
lua_pushnumber(L, p->xRot);
|
||||
return 5;
|
||||
}
|
||||
|
||||
int l_pteleport(lua_State* L) {
|
||||
Player* p = findPlayer(argInt(L, 1));
|
||||
if (!p) return 0;
|
||||
float x = argNum(L, 2), y = argNum(L, 3), z = argNum(L, 4);
|
||||
float yaw = lua_isnumber(L, 5) ? argNum(L, 5) : p->yRot;
|
||||
float pitch = lua_isnumber(L, 6) ? argNum(L, 6) : p->xRot;
|
||||
LV()->ensureChunksAround((int)floorf(x), (int)floorf(z), 2);
|
||||
p->moveTo(x, y, z, yaw, pitch);
|
||||
if (!isLocalPlayer(p) && server()) {
|
||||
MovePlayerPacket packet(p->entityId, p->x, p->y - p->heightOffset, p->z, p->xRot, p->yRot);
|
||||
RakNet::BitStream bs;
|
||||
packet.write(&bs);
|
||||
MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int l_pmsg(lua_State* L) {
|
||||
sendChat(findPlayer(argInt(L, 1)), lua_tostring(L, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int l_broadcast(lua_State* L) {
|
||||
broadcastChat(lua_tostring(L, 1));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int l_pop(lua_State* L) {
|
||||
Player* p = findPlayer(argInt(L, 1));
|
||||
if (!p) { lua_pushboolean(L, 0); return 1; }
|
||||
std::string lower = p->name;
|
||||
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
|
||||
lua_pushboolean(L, LV()->ops.find(lower) != LV()->ops.end());
|
||||
return 1;
|
||||
}
|
||||
|
||||
int l_pheld(lua_State* L) {
|
||||
Player* p = findPlayer(argInt(L, 1));
|
||||
ItemInstance* item = p ? p->inventory->getSelected() : NULL;
|
||||
if (!item || item->isNull()) { lua_pushinteger(L, 0); lua_pushinteger(L, 0); lua_pushinteger(L, 0); return 3; }
|
||||
lua_pushinteger(L, item->id);
|
||||
lua_pushinteger(L, item->getAuxValue());
|
||||
lua_pushinteger(L, item->count);
|
||||
return 3;
|
||||
}
|
||||
|
||||
int l_pgive(lua_State* L) {
|
||||
Player* p = findPlayer(argInt(L, 1));
|
||||
if (!p) return 0;
|
||||
p->inventory->add(new ItemInstance(argInt(L, 2), argInt(L, 3), argInt(L, 4)));
|
||||
if (!isLocalPlayer(p) && server()) {
|
||||
SendInventoryPacket packet(p, false);
|
||||
RakNet::BitStream bs;
|
||||
packet.write(&bs);
|
||||
MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, p->owner, false);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int l_pgamemode(lua_State* L) {
|
||||
lua_pushinteger(L, LV()->getLevelData()->getGameType());
|
||||
return 1;
|
||||
}
|
||||
|
||||
// trace(id, maxDist) -> x, y, z, face (the block the player looks at)
|
||||
int l_ptrace(lua_State* L) {
|
||||
Player* p = findPlayer(argInt(L, 1));
|
||||
float dist = lua_isnumber(L, 2) ? argNum(L, 2) : 128.0f;
|
||||
if (!p) return 0;
|
||||
float yaw = p->yRot * Mth::DEGRAD, pitch = p->xRot * Mth::DEGRAD;
|
||||
Vec3 dir(-sinf(yaw) * cosf(pitch), -sinf(pitch), cosf(yaw) * cosf(pitch));
|
||||
Vec3 a(p->x, p->y, p->z);
|
||||
Vec3 b(a.x + dir.x * dist, a.y + dir.y * dist, a.z + dir.z * dist);
|
||||
HitResult hit = LV()->clip(a, b, false, false);
|
||||
if (!hit.isHit() || hit.type != TILE) return 0;
|
||||
lua_pushinteger(L, hit.x);
|
||||
lua_pushinteger(L, hit.y);
|
||||
lua_pushinteger(L, hit.z);
|
||||
lua_pushinteger(L, hit.f);
|
||||
return 4;
|
||||
}
|
||||
|
||||
int l_log(lua_State* L) {
|
||||
LOGI("[lua] %s\n", lua_tostring(L, 1));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int l_mkdir(lua_State* L) {
|
||||
MKDIR(lua_tostring(L, 1));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// listdir(path) -> { {name=, dir=bool}, ... }
|
||||
int l_listdir(lua_State* L) {
|
||||
std::string path = lua_tostring(L, 1);
|
||||
lua_newtable(L);
|
||||
int n = 0;
|
||||
#ifdef _WIN32
|
||||
WIN32_FIND_DATAA fd;
|
||||
HANDLE h = FindFirstFileA((path + "/*").c_str(), &fd);
|
||||
if (h != INVALID_HANDLE_VALUE) {
|
||||
do {
|
||||
if (!strcmp(fd.cFileName, ".") || !strcmp(fd.cFileName, "..")) continue;
|
||||
lua_newtable(L);
|
||||
lua_pushstring(L, fd.cFileName);
|
||||
lua_setfield(L, -2, "name");
|
||||
lua_pushboolean(L, (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
|
||||
lua_setfield(L, -2, "dir");
|
||||
lua_rawseti(L, -2, ++n);
|
||||
} while (FindNextFileA(h, &fd));
|
||||
FindClose(h);
|
||||
}
|
||||
#else
|
||||
if (DIR* d = opendir(path.c_str())) {
|
||||
while (dirent* e = readdir(d)) {
|
||||
if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
|
||||
struct stat st;
|
||||
bool isDir = stat((path + "/" + e->d_name).c_str(), &st) == 0 && S_ISDIR(st.st_mode);
|
||||
lua_newtable(L);
|
||||
lua_pushstring(L, e->d_name);
|
||||
lua_setfield(L, -2, "name");
|
||||
lua_pushboolean(L, isDir);
|
||||
lua_setfield(L, -2, "dir");
|
||||
lua_rawseti(L, -2, ++n);
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
#endif
|
||||
return 1;
|
||||
}
|
||||
|
||||
const luaL_Reg api[] = {
|
||||
{ "_get_block", l_get_block }, { "_set_block", l_set_block }, { "_flush", l_flush },
|
||||
{ "_solid_height", l_solid_height }, { "_loaded", l_loaded }, { "_ensure", l_ensure },
|
||||
{ "_get_time", l_get_time }, { "_set_time", l_set_time }, { "_seed", l_seed },
|
||||
{ "_explode", l_explode }, { "_spawn_mob", l_spawn_mob }, { "_drop_item", l_drop_item },
|
||||
{ "_butcher", l_butcher },
|
||||
{ "_players", l_players }, { "_pname", l_pname }, { "_ppos", l_ppos }, { "_pteleport", l_pteleport },
|
||||
{ "_pmsg", l_pmsg }, { "_broadcast", l_broadcast }, { "_pop", l_pop }, { "_pheld", l_pheld },
|
||||
{ "_pgive", l_pgive }, { "_pgamemode", l_pgamemode }, { "_ptrace", l_ptrace },
|
||||
{ "_log", l_log }, { "_mkdir", l_mkdir }, { "_listdir", l_listdir },
|
||||
{ NULL, NULL }
|
||||
};
|
||||
|
||||
int traceback(lua_State* L) {
|
||||
const char* msg = lua_tostring(L, 1);
|
||||
luaL_traceback(L, L, msg ? msg : "(error)", 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// calls the function sitting below `nargs` arguments; returns false on error
|
||||
bool protectedCall(lua_State* L, int nargs, int nresults) {
|
||||
int base = lua_gettop(L) - nargs;
|
||||
lua_pushcfunction(L, traceback);
|
||||
lua_insert(L, base);
|
||||
int rc = lua_pcall(L, nargs, nresults, base);
|
||||
lua_remove(L, base);
|
||||
if (rc != 0) {
|
||||
LOGE("[lua] %s\n", lua_tostring(L, -1));
|
||||
lua_pop(L, 1);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool fileExists(const std::string& p) {
|
||||
std::ifstream f(p.c_str());
|
||||
return f.good();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// =================================================================== engine
|
||||
LuaEngine& LuaEngine::get() {
|
||||
static LuaEngine engine;
|
||||
return engine;
|
||||
}
|
||||
|
||||
void LuaEngine::start(Minecraft* minecraft) {
|
||||
if (L) stop();
|
||||
mc = minecraft;
|
||||
g_dirty.clear();
|
||||
|
||||
L = luaL_newstate();
|
||||
luaL_openlibs(L);
|
||||
|
||||
lua_newtable(L);
|
||||
luaL_register(L, NULL, api);
|
||||
lua_setglobal(L, "mc");
|
||||
|
||||
// prelude: the friendly API on top of the primitives above
|
||||
const char* candidates[] = { "lua/prelude.lua", "data/lua/prelude.lua", "../lua/prelude.lua" };
|
||||
std::string prelude;
|
||||
for (unsigned int i = 0; i < sizeof(candidates) / sizeof(candidates[0]); ++i)
|
||||
if (fileExists(candidates[i])) { prelude = candidates[i]; break; }
|
||||
if (prelude.empty()) {
|
||||
LOGE("[lua] lua/prelude.lua not found, Lua mods are disabled\n");
|
||||
lua_close(L);
|
||||
L = 0;
|
||||
return;
|
||||
}
|
||||
if (luaL_loadfile(L, prelude.c_str()) != 0 || !protectedCall(L, 0, 0)) {
|
||||
if (lua_gettop(L) > 0) { LOGE("[lua] %s\n", lua_tostring(L, -1)); }
|
||||
lua_close(L);
|
||||
L = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
MKDIR("mods");
|
||||
loadMods();
|
||||
LOGI("[lua] LuaJIT mod host started\n");
|
||||
}
|
||||
|
||||
void LuaEngine::stop() {
|
||||
if (!L) return;
|
||||
lua_getglobal(L, "mc");
|
||||
lua_getfield(L, -1, "_fire");
|
||||
lua_remove(L, -2);
|
||||
lua_pushstring(L, "stop");
|
||||
lua_pushnil(L);
|
||||
protectedCall(L, 2, 1);
|
||||
lua_pop(L, 1);
|
||||
lua_close(L);
|
||||
L = 0;
|
||||
mc = 0;
|
||||
}
|
||||
|
||||
void LuaEngine::loadMods() {
|
||||
lua_getglobal(L, "mc");
|
||||
lua_getfield(L, -1, "_load_mods");
|
||||
lua_remove(L, -2);
|
||||
protectedCall(L, 0, 0);
|
||||
}
|
||||
|
||||
void LuaEngine::tick() {
|
||||
if (!L) return;
|
||||
lua_getglobal(L, "mc");
|
||||
lua_getfield(L, -1, "_tick");
|
||||
lua_remove(L, -2);
|
||||
protectedCall(L, 0, 0);
|
||||
}
|
||||
|
||||
// Calls mc._fire(event, ...) with `nargs` arguments already pushed after the event name.
|
||||
bool LuaEngine::fire(const char* event, int nargs, bool cancellable) {
|
||||
// stack now: args...; put the function and the event below them
|
||||
lua_getglobal(L, "mc");
|
||||
lua_getfield(L, -1, "_fire");
|
||||
lua_remove(L, -2);
|
||||
lua_insert(L, -(nargs + 1));
|
||||
lua_pushstring(L, event);
|
||||
lua_insert(L, -(nargs + 1));
|
||||
bool cancelled = false;
|
||||
if (protectedCall(L, nargs + 1, 1)) {
|
||||
if (cancellable && lua_isboolean(L, -1) && !lua_toboolean(L, -1)) cancelled = true;
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
return cancelled;
|
||||
}
|
||||
|
||||
void LuaEngine::onPlayerJoin(Player* player) {
|
||||
if (!L) return;
|
||||
lua_pushinteger(L, player->entityId);
|
||||
fire("join", 1, false);
|
||||
}
|
||||
|
||||
void LuaEngine::onPlayerLeave(Player* player) {
|
||||
if (!L) return;
|
||||
lua_pushinteger(L, player->entityId);
|
||||
fire("leave", 1, false);
|
||||
}
|
||||
|
||||
bool LuaEngine::onChat(Player* player, const std::string& message) {
|
||||
if (!L) return false;
|
||||
lua_pushinteger(L, player->entityId);
|
||||
lua_pushstring(L, message.c_str());
|
||||
return fire("chat", 2, true);
|
||||
}
|
||||
|
||||
bool LuaEngine::onBlockBreak(Player* player, int x, int y, int z) {
|
||||
if (!L) return false;
|
||||
lua_pushinteger(L, player->entityId);
|
||||
lua_pushinteger(L, x); lua_pushinteger(L, y); lua_pushinteger(L, z);
|
||||
lua_pushinteger(L, MC()->level->getTile(x, y, z));
|
||||
return fire("block_break", 5, true);
|
||||
}
|
||||
|
||||
bool LuaEngine::onUseItem(Player* player, int x, int y, int z, int face, ItemInstance* item) {
|
||||
if (!L) return false;
|
||||
lua_pushinteger(L, player->entityId);
|
||||
lua_pushinteger(L, x); lua_pushinteger(L, y); lua_pushinteger(L, z);
|
||||
lua_pushinteger(L, face);
|
||||
lua_pushinteger(L, item && !item->isNull() ? item->id : 0);
|
||||
lua_pushinteger(L, item && !item->isNull() ? item->getAuxValue() : 0);
|
||||
return fire("use_item", 7, true);
|
||||
}
|
||||
|
||||
bool LuaEngine::runCommand(Player* player, const std::string& name, const std::vector<std::string>& args, std::string& reply) {
|
||||
if (!L) return false;
|
||||
lua_getglobal(L, "mc");
|
||||
lua_getfield(L, -1, "_run_command");
|
||||
lua_remove(L, -2);
|
||||
lua_pushinteger(L, player->entityId);
|
||||
lua_pushstring(L, name.c_str());
|
||||
lua_newtable(L);
|
||||
for (unsigned int i = 0; i < args.size(); ++i) {
|
||||
lua_pushstring(L, args[i].c_str());
|
||||
lua_rawseti(L, -2, i + 1);
|
||||
}
|
||||
bool handled = false;
|
||||
if (protectedCall(L, 3, 2)) {
|
||||
handled = lua_toboolean(L, -2) != 0;
|
||||
if (lua_isstring(L, -1)) reply = lua_tostring(L, -1);
|
||||
lua_pop(L, 2);
|
||||
}
|
||||
return handled;
|
||||
}
|
||||
|
||||
std::vector<std::string> LuaEngine::commandNames() {
|
||||
std::vector<std::string> names;
|
||||
if (!L) return names;
|
||||
lua_getglobal(L, "mc");
|
||||
lua_getfield(L, -1, "_command_names");
|
||||
lua_remove(L, -2);
|
||||
if (protectedCall(L, 0, 1)) {
|
||||
int n = (int)lua_objlen(L, -1);
|
||||
for (int i = 1; i <= n; ++i) {
|
||||
lua_rawgeti(L, -1, i);
|
||||
if (lua_isstring(L, -1)) names.push_back(lua_tostring(L, -1));
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
50
src/lua/LuaEngine.h
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
class Minecraft;
|
||||
class Player;
|
||||
class ItemInstance;
|
||||
struct lua_State;
|
||||
|
||||
/**
|
||||
* LuaJIT mod host. Mods live in "mods/<name>/main.lua" (or "mods/<name>.lua")
|
||||
* next to the executable and run on the machine that hosts the world (dedicated
|
||||
* server, single player, or a listening client). See mods/README.md for the API.
|
||||
*/
|
||||
class LuaEngine {
|
||||
public:
|
||||
static LuaEngine& get();
|
||||
|
||||
// Called once the level of a hosting game is ready
|
||||
void start(Minecraft* mc);
|
||||
void stop();
|
||||
bool active() const { return L != 0; }
|
||||
|
||||
void tick();
|
||||
|
||||
// Events. The "cancellable" ones return true when a mod cancelled the action.
|
||||
void onPlayerJoin(Player* player);
|
||||
void onPlayerLeave(Player* player);
|
||||
bool onChat(Player* player, const std::string& message);
|
||||
bool onBlockBreak(Player* player, int x, int y, int z);
|
||||
bool onUseItem(Player* player, int x, int y, int z, int face, ItemInstance* item);
|
||||
bool onAttackBlock(Player* player, int x, int y, int z) { return onBlockBreak(player, x, y, z); }
|
||||
|
||||
// Chat commands registered by mods. Returns false when nobody knows `name`.
|
||||
bool runCommand(Player* player, const std::string& name, const std::vector<std::string>& args, std::string& reply);
|
||||
std::vector<std::string> commandNames();
|
||||
|
||||
// Used by the bindings
|
||||
Minecraft* minecraft() const { return mc; }
|
||||
lua_State* state() const { return L; }
|
||||
|
||||
private:
|
||||
LuaEngine() : L(0), mc(0) {}
|
||||
void loadMods();
|
||||
bool fire(const char* event, int nargs, bool cancellable);
|
||||
|
||||
lua_State* L;
|
||||
Minecraft* mc;
|
||||
};
|
||||
|
|
@ -91,16 +91,22 @@ int main(int numArguments, char* pszArgs[]) {
|
|||
}
|
||||
|
||||
port = std::stoi(findStringInConfig("port", propString));
|
||||
worldSize = std::stoi(findStringInConfig("world-size", propString));
|
||||
|
||||
if (worldSize < 16 || worldSize > 32) {
|
||||
throw std::runtime_error("Incorrect world size.");
|
||||
// The world is infinite. "view-distance" (in chunks) is how far around every
|
||||
// player the server keeps chunks loaded. The old "world-size" is ignored.
|
||||
try {
|
||||
worldSize = std::stoi(findStringInConfig("view-distance", propString));
|
||||
if (worldSize < 3 || worldSize > 32) {
|
||||
throw std::runtime_error("view-distance must be between 3 and 32.");
|
||||
}
|
||||
} catch (const std::out_of_range&) {
|
||||
throw std::runtime_error("Incorrect view-distance.");
|
||||
} catch (const std::runtime_error& e) {
|
||||
if (std::string(e.what()) == "Cannot find value") worldSize = 10;
|
||||
else throw;
|
||||
}
|
||||
LevelConstants::VIEW_DISTANCE_CHUNKS = worldSize;
|
||||
|
||||
LevelConstants::CHUNK_CACHE_WIDTH = worldSize;
|
||||
LevelConstants::LEVEL_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH;
|
||||
LevelConstants::LEVEL_DEPTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_DEPTH;
|
||||
|
||||
cachePath = findStringInConfig("level-cachepath", propString);
|
||||
externalPath = findStringInConfig("level-externalpath", propString);
|
||||
levelName = findStringInConfig("level-name", propString);
|
||||
|
|
@ -116,7 +122,7 @@ int main(int numArguments, char* pszArgs[]) {
|
|||
gamemode = GameType::Survival;
|
||||
}
|
||||
|
||||
printf("%d %s %s %d %d\n", port, cachePath.c_str(), externalPath.c_str(), gamemode, LevelConstants::CHUNK_CACHE_WIDTH);
|
||||
printf("%d %s %s %d %d\n", port, cachePath.c_str(), externalPath.c_str(), gamemode, LevelConstants::VIEW_DISTANCE_CHUNKS);
|
||||
} else {
|
||||
std::ofstream defaultProperties("server.properties");
|
||||
|
||||
|
|
@ -132,7 +138,7 @@ int main(int numArguments, char* pszArgs[]) {
|
|||
buffer << "level-externalpath=" << defaultSettings.getExternalPath() << std::endl;
|
||||
buffer << "gamemode=survival" << std::endl;
|
||||
buffer << "level-name=" << defaultSettings.getLevelName() << std::endl;
|
||||
buffer << "world-size=16" << std::endl;
|
||||
buffer << "view-distance=10" << std::endl;
|
||||
|
||||
defaultProperties << buffer.str();
|
||||
|
||||
|
|
|
|||
|
|
@ -43,12 +43,10 @@ ClientSideNetworkHandler::ClientSideNetworkHandler(Minecraft* minecraft, IRakNet
|
|||
: minecraft(minecraft),
|
||||
raknetInstance(raknetInstance),
|
||||
level(NULL),
|
||||
requestNextChunkPosition(0),
|
||||
requestNextChunkIndex(0)
|
||||
initialLoadDone(false),
|
||||
initialPending(0),
|
||||
spiralRadius(-1)
|
||||
{
|
||||
NumRequestChunks = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH;
|
||||
requestNextChunkIndexList.resize(NumRequestChunks);
|
||||
chunksLoaded.resize(NumRequestChunks);
|
||||
rakPeer = raknetInstance->getPeer();
|
||||
}
|
||||
|
||||
|
|
@ -56,35 +54,93 @@ ClientSideNetworkHandler::~ClientSideNetworkHandler()
|
|||
{
|
||||
}
|
||||
|
||||
void ClientSideNetworkHandler::requestNextChunk()
|
||||
void ClientSideNetworkHandler::requestChunk(int x, int z)
|
||||
{
|
||||
if (requestNextChunkIndex < NumRequestChunks)
|
||||
{
|
||||
IntPair& chunk = requestNextChunkIndexList[requestNextChunkIndex];
|
||||
RequestChunkPacket packet(chunk.x, chunk.y);
|
||||
raknetInstance->send(packet);
|
||||
const long long key = LevelConstants::chunkKey(x, z);
|
||||
if (requestedChunks.count(key) || loadedChunks.count(key)) return;
|
||||
|
||||
//LOGI("requesting chunks @ (%d, %d)\n", chunk.x, chunk.y);
|
||||
|
||||
//raknetInstance->send(new RequestChunkPacket(requestNextChunkPosition % LevelConstants::CHUNK_CACHE_WIDTH, requestNextChunkPosition / LevelConstants::CHUNK_CACHE_WIDTH));
|
||||
requestNextChunkIndex++;
|
||||
requestNextChunkPosition++;
|
||||
}
|
||||
}
|
||||
|
||||
bool ClientSideNetworkHandler::areAllChunksLoaded()
|
||||
{
|
||||
return (requestNextChunkPosition >= (LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH));
|
||||
RequestChunkPacket packet(x, z);
|
||||
raknetInstance->send(packet);
|
||||
requestedChunks.insert(key);
|
||||
}
|
||||
|
||||
bool ClientSideNetworkHandler::isChunkLoaded(int x, int z)
|
||||
{
|
||||
if (x < 0 || x >= LevelConstants::CHUNK_CACHE_WIDTH || z < 0 || z >= LevelConstants::CHUNK_CACHE_WIDTH) {
|
||||
LOGE("Error: Tried to request chunk (%d, %d)\n", x, z);
|
||||
return true;
|
||||
return loadedChunks.count(LevelConstants::chunkKey(x, z)) != 0;
|
||||
}
|
||||
|
||||
// Keeps the chunks around the local player in sync with the server: asks for
|
||||
// the ones that came into range (nearest first) and drops the ones left behind.
|
||||
void ClientSideNetworkHandler::updateChunks()
|
||||
{
|
||||
if (!level || !minecraft->player || !initialLoadDone) return;
|
||||
|
||||
Player* p = minecraft->player;
|
||||
const int pcx = Mth::floor(p->x / 16.0f);
|
||||
const int pcz = Mth::floor(p->z / 16.0f);
|
||||
const int radius = LevelConstants::VIEW_DISTANCE_CHUNKS + 1;
|
||||
|
||||
if (radius != spiralRadius) {
|
||||
spiralRadius = radius;
|
||||
spiral.clear();
|
||||
for (int dx = -radius; dx <= radius; ++dx)
|
||||
for (int dz = -radius; dz <= radius; ++dz)
|
||||
if (dx * dx + dz * dz <= radius * radius + radius)
|
||||
spiral.push_back(std::make_pair(dx, dz));
|
||||
struct ByDistance {
|
||||
bool operator()(const std::pair<int, int>& a, const std::pair<int, int>& b) const {
|
||||
return a.first * a.first + a.second * a.second < b.first * b.first + b.second * b.second;
|
||||
}
|
||||
};
|
||||
std::stable_sort(spiral.begin(), spiral.end(), ByDistance());
|
||||
}
|
||||
return chunksLoaded[x * LevelConstants::CHUNK_CACHE_WIDTH + z];
|
||||
//return areAllChunksLoaded();
|
||||
|
||||
// Request what is missing, a few at a time
|
||||
int budget = 4;
|
||||
if (requestedChunks.size() < 16) {
|
||||
for (unsigned int i = 0; i < spiral.size() && budget > 0; ++i) {
|
||||
const int cx = pcx + spiral[i].first;
|
||||
const int cz = pcz + spiral[i].second;
|
||||
const long long key = LevelConstants::chunkKey(cx, cz);
|
||||
if (requestedChunks.count(key) || loadedChunks.count(key)) continue;
|
||||
requestChunk(cx, cz);
|
||||
--budget;
|
||||
}
|
||||
}
|
||||
|
||||
// Forget chunks that are far away now
|
||||
const int unloadRadius = radius + 2;
|
||||
std::vector<long long> victims;
|
||||
for (std::set<long long>::iterator it = loadedChunks.begin(); it != loadedChunks.end() && victims.size() < 8; ++it) {
|
||||
const int cx = (int)(*it >> 32);
|
||||
const int cz = (int)(*it & 0xffffffffLL);
|
||||
if (std::abs(cx - pcx) > unloadRadius || std::abs(cz - pcz) > unloadRadius)
|
||||
victims.push_back(*it);
|
||||
}
|
||||
for (std::set<long long>::iterator it = requestedChunks.begin(); it != requestedChunks.end() && victims.size() < 8; ++it) {
|
||||
const int cx = (int)(*it >> 32);
|
||||
const int cz = (int)(*it & 0xffffffffLL);
|
||||
if (std::abs(cx - pcx) > unloadRadius || std::abs(cz - pcz) > unloadRadius)
|
||||
victims.push_back(*it);
|
||||
}
|
||||
for (unsigned int i = 0; i < victims.size(); ++i) {
|
||||
const int cx = (int)(victims[i] >> 32);
|
||||
const int cz = (int)(victims[i] & 0xffffffffLL);
|
||||
loadedChunks.erase(victims[i]);
|
||||
requestedChunks.erase(victims[i]);
|
||||
level->getChunkSource()->unloadChunk(cx, cz);
|
||||
}
|
||||
}
|
||||
|
||||
// The chunks right around the player arrived: the server may now send everything else.
|
||||
void ClientSideNetworkHandler::finishInitialLoad()
|
||||
{
|
||||
if (initialLoadDone) return;
|
||||
initialLoadDone = true;
|
||||
|
||||
ReadyPacket packet(ReadyPacket::READY_REQUESTEDCHUNKS);
|
||||
raknetInstance->send(packet);
|
||||
bufferedBlockUpdates.clear();
|
||||
}
|
||||
|
||||
void ClientSideNetworkHandler::onConnect(const RakNet::RakNetGUID& hostGuid)
|
||||
|
|
@ -104,10 +160,8 @@ void ClientSideNetworkHandler::onUnableToConnect()
|
|||
|
||||
void ClientSideNetworkHandler::onDisconnect(const RakNet::RakNetGUID& guid)
|
||||
{
|
||||
LevelConstants::CHUNK_CACHE_WIDTH = 16;
|
||||
LevelConstants::LEVEL_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH;
|
||||
LevelConstants::LEVEL_DEPTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_DEPTH;
|
||||
|
||||
clearChunksLoaded();
|
||||
|
||||
// TODO: Good disconnecting
|
||||
LOGI("onDisconnect\n");
|
||||
if (level)
|
||||
|
|
@ -174,18 +228,8 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, StartGam
|
|||
}
|
||||
#endif
|
||||
|
||||
// @todo @note i think its trash
|
||||
// we can put it directly to selectLevel?
|
||||
if (packet->chunkCacheWidth != 0) {
|
||||
printf("lol \n");
|
||||
LevelConstants::CHUNK_CACHE_WIDTH = packet->chunkCacheWidth;
|
||||
LevelConstants::LEVEL_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH;
|
||||
LevelConstants::LEVEL_DEPTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_DEPTH;
|
||||
LevelChunk::ChunkBlockCount = LevelConstants::CHUNK_BLOCK_COUNT;
|
||||
}
|
||||
NumRequestChunks = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH;
|
||||
requestNextChunkIndexList.resize(NumRequestChunks);
|
||||
chunksLoaded.resize(NumRequestChunks);
|
||||
// The world is infinite, the chunk cache width sent by the server is a legacy field.
|
||||
clearChunksLoaded();
|
||||
|
||||
const std::string& levelId = LevelStorageSource::TempLevelId;
|
||||
LevelStorageSource* storageSource = minecraft->getLevelSource();
|
||||
|
|
@ -499,6 +543,7 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, UpdateBl
|
|||
|
||||
int x = packet->x, z = packet->z;
|
||||
|
||||
// Updates for chunks we do not hold are already part of the chunk data we will get
|
||||
if (isChunkLoaded(x >> 4, z >> 4))
|
||||
{
|
||||
//LOGI("chunk is loaded - UPDATE @ %d, %d, %d -- %d, %d\n", x, packet->y, z, packet->blockId, packet->blockData);
|
||||
|
|
@ -506,15 +551,6 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, UpdateBl
|
|||
int y = packet->y;
|
||||
int tileId = Tile::transformToValidBlockId(packet->blockId, x, y, z);
|
||||
level->setTileAndData(x, y, z, tileId, packet->blockData);
|
||||
} else {
|
||||
SBufferedBlockUpdate update;
|
||||
update.blockId = packet->blockId;
|
||||
update.blockData = packet->blockData;
|
||||
update.setData = true;
|
||||
update.x = packet->x;
|
||||
update.y = packet->y;
|
||||
update.z = packet->z;
|
||||
bufferedBlockUpdates.push_back(update);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -555,6 +591,14 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ChunkDat
|
|||
}
|
||||
//LOGI("ChunkDataPacket\n");
|
||||
|
||||
const long long chunkKey = LevelConstants::chunkKey(packet->x, packet->z);
|
||||
const bool requested = requestedChunks.erase(chunkKey) > 0;
|
||||
if (!requested && loadedChunks.count(chunkKey) == 0) {
|
||||
// we do not want this chunk (any more)
|
||||
return;
|
||||
}
|
||||
// (a chunk we already hold can be pushed again, e.g. after a bulk edit by a mod)
|
||||
|
||||
LevelChunk* chunk = level->getChunkSource()->create(packet->x, packet->z);
|
||||
if (!chunk || chunk->isEmpty())
|
||||
{
|
||||
|
|
@ -672,66 +716,11 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ChunkDat
|
|||
//chunk->terrainPopulated = true;
|
||||
chunk->unsaved = false;
|
||||
|
||||
chunksLoaded[packet->x * LevelConstants::CHUNK_CACHE_WIDTH + packet->z] = true;
|
||||
loadedChunks.insert(chunkKey);
|
||||
|
||||
if (areAllChunksLoaded())
|
||||
{
|
||||
ReadyPacket packet(ReadyPacket::READY_REQUESTEDCHUNKS);
|
||||
raknetInstance->send(packet);
|
||||
|
||||
for (unsigned int i = 0; i < bufferedBlockUpdates.size(); i++)
|
||||
{
|
||||
const SBufferedBlockUpdate& update = bufferedBlockUpdates[i];
|
||||
int tileId = Tile::transformToValidBlockId( update.blockId, update.x, update.y, update.z );
|
||||
if (update.setData)
|
||||
level->setTileAndData(update.x, update.y, update.z, tileId, update.blockData);
|
||||
else
|
||||
level->setTile(update.x, update.y, update.z, tileId);
|
||||
}
|
||||
bufferedBlockUpdates.clear();
|
||||
if (requested && !initialLoadDone && initialPending > 0 && --initialPending == 0) {
|
||||
finishInitialLoad();
|
||||
}
|
||||
else
|
||||
{
|
||||
requestNextChunk();
|
||||
}
|
||||
}
|
||||
|
||||
class _ChunkSorter
|
||||
{
|
||||
public:
|
||||
_ChunkSorter(int x, int z)
|
||||
: x(x),
|
||||
y(z)
|
||||
{
|
||||
}
|
||||
|
||||
bool operator() (const IntPair& a, const IntPair& b) {
|
||||
const int ax = a.x - x, ay = a.y - y;
|
||||
const int bx = b.x - x, by = b.y - y;
|
||||
return (ax*ax + ay*ay) < (bx*bx + by*by);
|
||||
}
|
||||
private:
|
||||
int x;
|
||||
int y;
|
||||
};
|
||||
|
||||
|
||||
void ClientSideNetworkHandler::arrangeRequestChunkOrder() {
|
||||
clearChunksLoaded();
|
||||
|
||||
// Default sort is around center of the world
|
||||
int cx = LevelConstants::CHUNK_CACHE_WIDTH / 2;
|
||||
int cz = LevelConstants::CHUNK_CACHE_WIDTH / 2;
|
||||
|
||||
// If player exists, let's sort around him
|
||||
Player* p = minecraft? minecraft->player : NULL;
|
||||
if (p) {
|
||||
cx = Mth::floor(p->x / (float)LevelConstants::CHUNK_WIDTH);
|
||||
cz = Mth::floor(p->z / (float)LevelConstants::CHUNK_DEPTH);
|
||||
}
|
||||
|
||||
_ChunkSorter sorter(cx, cz);
|
||||
std::sort(requestNextChunkIndexList.begin(), requestNextChunkIndexList.end(), sorter);
|
||||
}
|
||||
|
||||
void ClientSideNetworkHandler::levelGenerated(Level* level)
|
||||
|
|
@ -740,8 +729,26 @@ void ClientSideNetworkHandler::levelGenerated(Level* level)
|
|||
ReadyPacket packet(ReadyPacket::READY_CLIENTGENERATION);
|
||||
raknetInstance->send(packet);
|
||||
|
||||
arrangeRequestChunkOrder();
|
||||
requestNextChunk();
|
||||
#ifndef STANDALONE_SERVER
|
||||
if (minecraft && minecraft->player) {
|
||||
const std::string skin = minecraft->options.getStringValue(OPTIONS_SKIN);
|
||||
if (!skin.empty() && skin != "Default") {
|
||||
SetSkinPacket skinPacket(minecraft->player->entityId, skin);
|
||||
raknetInstance->send(skinPacket);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// First ask for the chunks right around the player
|
||||
clearChunksLoaded();
|
||||
Player* p = minecraft ? minecraft->player : NULL;
|
||||
const int pcx = p ? Mth::floor(p->x / 16.0f) : 0;
|
||||
const int pcz = p ? Mth::floor(p->z / 16.0f) : 0;
|
||||
const int r = 2;
|
||||
for (int dx = -r; dx <= r; ++dx)
|
||||
for (int dz = -r; dz <= r; ++dz)
|
||||
requestChunk(pcx + dx, pcz + dz);
|
||||
initialPending = (int)requestedChunks.size();
|
||||
}
|
||||
|
||||
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, PlayerEquipmentPacket* packet)
|
||||
|
|
@ -1017,12 +1024,28 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, Adventur
|
|||
packet->fillIn(level->adventureSettings);
|
||||
}
|
||||
|
||||
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet)
|
||||
{
|
||||
if (!level) return;
|
||||
Entity* e = level->getEntity(packet->entityId);
|
||||
if (!e || !e->isPlayer() || e == minecraft->player) return;
|
||||
|
||||
Player* p = (Player*)e;
|
||||
p->skinName = packet->skin.C_String();
|
||||
#ifndef STANDALONE_SERVER
|
||||
// every client ships the same skin files; anything we do not have keeps the default look
|
||||
const std::string file = "data/images/skins/" + p->skinName + ".png";
|
||||
if (FILE* fp = fopen(file.c_str(), "rb")) {
|
||||
fclose(fp);
|
||||
p->setTextureName("skins/" + p->skinName + ".png");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void ClientSideNetworkHandler::clearChunksLoaded()
|
||||
{
|
||||
// Init the chunk positions
|
||||
for (int i = 0; i < NumRequestChunks; ++i) {
|
||||
requestNextChunkIndexList[i].x = i / LevelConstants::CHUNK_WIDTH;
|
||||
requestNextChunkIndexList[i].y = i % LevelConstants::CHUNK_WIDTH;
|
||||
chunksLoaded[i] = false;
|
||||
}
|
||||
requestedChunks.clear();
|
||||
loadedChunks.clear();
|
||||
initialLoadDone = false;
|
||||
initialPending = 0;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
#include "../world/level/LevelConstants.h"
|
||||
|
||||
#include <vector>
|
||||
#include <set>
|
||||
|
||||
class Minecraft;
|
||||
class Level;
|
||||
|
|
@ -81,15 +82,17 @@ public:
|
|||
virtual void handle(const RakNet::RakNetGUID& source, TakeItemPacket* packet);
|
||||
virtual void handle(const RakNet::RakNetGUID& source, WantCreatePacket* packet);
|
||||
virtual void handle(const RakNet::RakNetGUID& source, SendInventoryPacket* packet);
|
||||
virtual void handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet);
|
||||
|
||||
// Streams chunks in/out around the local player. Called once per game tick.
|
||||
void updateChunks();
|
||||
|
||||
private:
|
||||
|
||||
void requestNextChunk();
|
||||
void arrangeRequestChunkOrder();
|
||||
|
||||
bool isChunkLoaded(int x, int z);
|
||||
bool areAllChunksLoaded();
|
||||
void clearChunksLoaded();
|
||||
void requestChunk(int x, int z);
|
||||
void finishInitialLoad();
|
||||
private:
|
||||
|
||||
Minecraft* minecraft;
|
||||
|
|
@ -100,13 +103,14 @@ private:
|
|||
RakNet::RakNetGUID serverGuid;
|
||||
|
||||
BlockUpdateList bufferedBlockUpdates;
|
||||
int requestNextChunkPosition;
|
||||
|
||||
int NumRequestChunks;
|
||||
|
||||
int requestNextChunkIndex;
|
||||
std::vector<IntPair> requestNextChunkIndexList;
|
||||
std::vector<bool> chunksLoaded;
|
||||
// The world is infinite: only the chunks around the player are kept.
|
||||
std::set<long long> requestedChunks; // asked from the server, data not here yet
|
||||
std::set<long long> loadedChunks; // data received and applied
|
||||
bool initialLoadDone;
|
||||
int initialPending;
|
||||
std::vector<std::pair<int, int> > spiral;
|
||||
int spiralRadius;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ class ContainerSetDataPacket;
|
|||
class ContainerSetContentPacket;
|
||||
class WantCreatePacket;
|
||||
class ChatPacket;
|
||||
class SetSkinPacket;
|
||||
class SignUpdatePacket;
|
||||
class Minecraft;
|
||||
class Level;
|
||||
|
|
@ -119,6 +120,7 @@ public:
|
|||
virtual void handle(const RakNet::RakNetGUID& source, ContainerSetSlotPacket* packet) {}
|
||||
virtual void handle(const RakNet::RakNetGUID& source, ContainerSetContentPacket* packet) {}
|
||||
virtual void handle(const RakNet::RakNetGUID& source, ChatPacket* packet) {}
|
||||
virtual void handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet) {}
|
||||
virtual void handle(const RakNet::RakNetGUID& source, SignUpdatePacket* packet) {}
|
||||
virtual void handle(const RakNet::RakNetGUID& source, AdventureSettingsPacket* packet) {}
|
||||
virtual void handle(const RakNet::RakNetGUID& source, AnimatePacket* packet) {}
|
||||
|
|
|
|||
|
|
@ -177,6 +177,9 @@ Packet* MinecraftPackets::createPacket(int id)
|
|||
case PACKET_ADVENTURESETTINGS:
|
||||
packet = new AdventureSettingsPacket();
|
||||
break;
|
||||
case PACKET_SETSKIN:
|
||||
packet = new SetSkinPacket();
|
||||
break;
|
||||
}
|
||||
|
||||
return packet;
|
||||
|
|
|
|||
|
|
@ -88,6 +88,8 @@ enum MinecraftPacketIds
|
|||
PACKET_SIGNUPDATE,
|
||||
|
||||
PACKET_ADVENTURESETTINGS,
|
||||
|
||||
PACKET_SETSKIN,
|
||||
/*
|
||||
PACKET_PRELOGIN,
|
||||
PACKET_CHAT,
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@
|
|||
#include "../client/sound/SoundEngine.h"
|
||||
#endif
|
||||
#include "../server/ServerPlayer.h"
|
||||
#include "../lua/LuaEngine.h"
|
||||
#include "../world/entity/item/FallingTile.h"
|
||||
|
||||
#define TIMES(x) for(int itc ## __LINE__ = 0; itc ## __LINE__ < x; ++ itc ## __LINE__)
|
||||
|
|
@ -169,6 +170,7 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, MessageP
|
|||
return sendPrivate(resp, source);
|
||||
}
|
||||
|
||||
if (LuaEngine::get().onChat(player, msg)) return;
|
||||
displayGameMessage("<" + player->name + "> " + msg);
|
||||
}
|
||||
|
||||
|
|
@ -185,6 +187,7 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ChatPack
|
|||
return sendPrivate(resp, source);
|
||||
}
|
||||
|
||||
if (LuaEngine::get().onChat(player, packet->message)) return;
|
||||
displayGameMessage("<" + player->name + "> " + packet->message);
|
||||
}
|
||||
|
||||
|
|
@ -206,6 +209,7 @@ void ServerSideNetworkHandler::onDisconnect(const RakNet::RakNetGUID& guid)
|
|||
if (player->owner == guid)
|
||||
{
|
||||
minecraft->level->getLevelStorage()->savePlayer(*player);
|
||||
LuaEngine::get().onPlayerLeave(player);
|
||||
|
||||
std::string message = player->name;
|
||||
message += " disconnected from the game";
|
||||
|
|
@ -284,6 +288,9 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, LoginPac
|
|||
|
||||
LOGI("Adding new player... isCreative: %i\n", minecraft->isCreativeMode());
|
||||
|
||||
// The world is streamed in around the players: make sure the ground below the new player exists
|
||||
level->ensureChunksAround((int)newPlayer->x, (int)newPlayer->z, 2);
|
||||
|
||||
// Reset the player so he doesn't spawn inside blocks
|
||||
while (newPlayer->y > 0) {
|
||||
newPlayer->setPos(newPlayer->x, newPlayer->y, newPlayer->z);
|
||||
|
|
@ -352,6 +359,11 @@ void ServerSideNetworkHandler::onReady_ClientGeneration(const RakNet::RakNetGUID
|
|||
for (unsigned int i = 0; i < players.size(); i++) {
|
||||
Player* player = players[i];
|
||||
|
||||
if (!player->skinName.empty()) {
|
||||
SetSkinPacket skinPacket(player->entityId, player->skinName);
|
||||
sendPrivate(skinPacket, source);
|
||||
}
|
||||
|
||||
bitStream.Reset();
|
||||
AddPlayerPacket(player).write(&bitStream);
|
||||
rakPeer->Send(&bitStream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, source, false);
|
||||
|
|
@ -364,6 +376,7 @@ void ServerSideNetworkHandler::onReady_ClientGeneration(const RakNet::RakNetGUID
|
|||
}
|
||||
|
||||
level->addEntity(newPlayer);
|
||||
LuaEngine::get().onPlayerJoin(newPlayer);
|
||||
#ifndef STANDALONE_SERVER
|
||||
minecraft->gui.addMessage(newPlayer->name + " joined the game");
|
||||
#else
|
||||
|
|
@ -385,7 +398,9 @@ void ServerSideNetworkHandler::onReady_ClientGeneration(const RakNet::RakNetGUID
|
|||
if (!minecraft->level->getLevelStorage()->loadPlayer(*newPlayer)) {
|
||||
LOGW("Failed to load %s data\n", newPlayer->name.c_str());
|
||||
}
|
||||
|
||||
// the saved position can be anywhere in the world
|
||||
level->ensureChunksAround((int)newPlayer->x, (int)newPlayer->z, 2);
|
||||
|
||||
// Credits to EpikIzCool
|
||||
bitStream.Reset();
|
||||
MovePlayerPacket mv(newPlayer->entityId, newPlayer->x, newPlayer->y - newPlayer->heightOffset,
|
||||
|
|
@ -488,6 +503,13 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, RemoveBl
|
|||
|
||||
int x = packet->x, y = packet->y, z = packet->z;
|
||||
|
||||
if (LuaEngine::get().onBlockBreak(player, x, y, z)) {
|
||||
// a mod cancelled it: put the block back on the client
|
||||
UpdateBlockPacket restore(x, y, z, level->getTile(x, y, z), level->getData(x, y, z));
|
||||
sendPrivate(restore, source);
|
||||
return;
|
||||
}
|
||||
|
||||
// code copied from GameMode.cpp
|
||||
int oldId = level->getTile(x, y, z);
|
||||
int data = level->getData(x, y, z);
|
||||
|
|
@ -639,6 +661,31 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, Interact
|
|||
}
|
||||
}
|
||||
|
||||
static bool validSkinName(const std::string& s) {
|
||||
if (s.empty() || s.size() > 32) return false;
|
||||
for (size_t i = 0; i < s.size(); ++i) {
|
||||
char c = s[i];
|
||||
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-'))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet)
|
||||
{
|
||||
if (!level) return;
|
||||
Player* player = getPlayer(source);
|
||||
if (!player) return;
|
||||
|
||||
std::string skin = packet->skin.C_String();
|
||||
if (!validSkinName(skin)) skin.clear();
|
||||
player->skinName = skin;
|
||||
|
||||
// everybody else needs to know (the sender already wears it)
|
||||
SetSkinPacket out(player->entityId, skin);
|
||||
redistributePacket(&out, source);
|
||||
}
|
||||
|
||||
void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, AnimatePacket* packet)
|
||||
{
|
||||
if (!level)
|
||||
|
|
@ -736,6 +783,21 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, UseItemP
|
|||
|
||||
Player* player = (Player*) entity;
|
||||
int x = packet->x, y = packet->y, z = packet->z;
|
||||
|
||||
if (packet->face != 255 && LuaEngine::get().onUseItem(player, x, y, z, packet->face, &packet->item)) {
|
||||
// cancelled by a mod: refresh the clicked block and the block that would have been placed
|
||||
static const int dx[] = { 0, 0, 0, 0, -1, 1 };
|
||||
static const int dy[] = { -1, 1, 0, 0, 0, 0 };
|
||||
static const int dz[] = { 0, 0, -1, 1, 0, 0 };
|
||||
UpdateBlockPacket a(x, y, z, level->getTile(x, y, z), level->getData(x, y, z));
|
||||
sendPrivate(a, source);
|
||||
if (packet->face < 6) {
|
||||
int px = x + dx[packet->face], py = y + dy[packet->face], pz = z + dz[packet->face];
|
||||
UpdateBlockPacket b(px, py, pz, level->getTile(px, py, pz), level->getData(px, py, pz));
|
||||
sendPrivate(b, source);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Tile* t = Tile::tiles[level->getTile(x, y, z)];
|
||||
|
||||
if (t == Tile::invisible_bedrock) return;
|
||||
|
|
|
|||
|
|
@ -48,6 +48,7 @@ public:
|
|||
//virtual void handle(const RakNet::RakNetGUID& source, TeleportEntityPacket* packet);
|
||||
virtual void handle(const RakNet::RakNetGUID& source, InteractPacket* packet);
|
||||
virtual void handle(const RakNet::RakNetGUID& source, AnimatePacket* packet);
|
||||
virtual void handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet);
|
||||
virtual void handle(const RakNet::RakNetGUID& source, UseItemPacket* packet);
|
||||
virtual void handle(const RakNet::RakNetGUID& source, EntityEventPacket* packet);
|
||||
virtual void handle(const RakNet::RakNetGUID& source, PlayerActionPacket* packet);
|
||||
|
|
|
|||
|
|
@ -233,12 +233,8 @@ std::string CommandServer::parse(ConnectedClient& client, const std::string& s)
|
|||
apiPosTranslate.from(x0, y0, z0);
|
||||
apiPosTranslate.from(x1, y1, z1);
|
||||
|
||||
if (x0 < 0) x0 = 0;
|
||||
if (y0 < 0) y0 = 0;
|
||||
if (z0 < 0) z0 = 0;
|
||||
if (x1 >= LevelConstants::LEVEL_WIDTH ) x1 = LevelConstants::LEVEL_WIDTH - 1;
|
||||
if (y1 >= LevelConstants::LEVEL_HEIGHT) y1 = LevelConstants::LEVEL_HEIGHT - 1;
|
||||
if (z1 >= LevelConstants::LEVEL_DEPTH ) z1 = LevelConstants::LEVEL_DEPTH - 1;
|
||||
|
||||
for (int y = y0; y <= y1; ++y)
|
||||
for (int z = z0; z <= z1; ++z)
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@
|
|||
#include "AnimatePacket.h"
|
||||
#include "AdventureSettingsPacket.h"
|
||||
#include "ChatPacket.h"
|
||||
#include "SetSkinPacket.h"
|
||||
#include "ContainerAckPacket.h"
|
||||
#include "ContainerOpenPacket.h"
|
||||
#include "ContainerClosePacket.h"
|
||||
|
|
|
|||
38
src/network/packet/SetSkinPacket.h
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
#ifndef NET_MINECRAFT_NETWORK_PACKET__SetSkinPacket_H__
|
||||
#define NET_MINECRAFT_NETWORK_PACKET__SetSkinPacket_H__
|
||||
|
||||
#include "../Packet.h"
|
||||
|
||||
// Tells everyone which skin file (data/images/skins/<name>.png) a player wears.
|
||||
class SetSkinPacket: public Packet
|
||||
{
|
||||
public:
|
||||
int entityId;
|
||||
RakNet::RakString skin;
|
||||
|
||||
SetSkinPacket() : entityId(0) {}
|
||||
SetSkinPacket(int entityId, const std::string& skin)
|
||||
: entityId(entityId),
|
||||
skin(skin.c_str())
|
||||
{}
|
||||
|
||||
void write(RakNet::BitStream* bitStream)
|
||||
{
|
||||
bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SETSKIN));
|
||||
bitStream->Write(entityId);
|
||||
bitStream->Write(skin);
|
||||
}
|
||||
|
||||
void read(RakNet::BitStream* bitStream)
|
||||
{
|
||||
bitStream->Read(entityId);
|
||||
bitStream->Read(skin);
|
||||
}
|
||||
|
||||
void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback)
|
||||
{
|
||||
callback->handle(source, (SetSkinPacket*)this);
|
||||
}
|
||||
};
|
||||
|
||||
#endif /*NET_MINECRAFT_NETWORK_PACKET__SetSkinPacket_H__*/
|
||||
|
|
@ -878,10 +878,10 @@ bool Entity::load( CompoundTag* tag )
|
|||
float yy = pos->getFloat(1);
|
||||
float zz = pos->getFloat(2);
|
||||
|
||||
// Add a small padding if standing next to the world edges
|
||||
// The world is infinite, only keep the position inside the coordinate system
|
||||
const float padding = bbWidth * 0.5f + 0.001f;
|
||||
xx = Mth::clamp(xx, padding, (float)LevelConstants::LEVEL_WIDTH - padding);
|
||||
zz = Mth::clamp(zz, padding, (float)LevelConstants::LEVEL_DEPTH - padding);
|
||||
xx = Mth::clamp(xx, -(float)LevelConstants::LEVEL_WIDTH + padding, (float)LevelConstants::LEVEL_WIDTH - padding);
|
||||
zz = Mth::clamp(zz, -(float)LevelConstants::LEVEL_DEPTH + padding, (float)LevelConstants::LEVEL_DEPTH - padding);
|
||||
|
||||
xo = xOld = x = xx;
|
||||
yo = yOld = y = yy;
|
||||
|
|
|
|||
|
|
@ -164,6 +164,7 @@ public:
|
|||
float oBob, bob;
|
||||
|
||||
std::string name;
|
||||
std::string skinName; // file name (without .png) in data/images/skins, empty = default
|
||||
int dimension;
|
||||
|
||||
Abilities abilities;
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ public:
|
|||
}
|
||||
|
||||
bool operator<(const ChunkPos& rhs) const {
|
||||
return hashCode() < rhs.hashCode();
|
||||
return x < rhs.x || (x == rhs.x && z < rhs.z);
|
||||
}
|
||||
|
||||
float distanceToSqr(const Entity* e) const {
|
||||
|
|
|
|||
|
|
@ -281,8 +281,7 @@ void Level::tickTiles() {
|
|||
for (int i = 0; i < pollChunkOffsetsSize; i += 2) {
|
||||
const int xp = xx + pollChunkOffsets[i];
|
||||
const int zp = zz + pollChunkOffsets[i+1];
|
||||
if (xp >= 0 && xp < LevelConstants::CHUNK_CACHE_WIDTH &&
|
||||
zp >= 0 && zp < LevelConstants::CHUNK_CACHE_WIDTH)
|
||||
if (hasChunk(xp, zp))
|
||||
_chunksToPoll.insert(ChunkPos(xp, zp));
|
||||
}
|
||||
}
|
||||
|
|
@ -431,17 +430,13 @@ bool Level::findPath(Path* path, Entity* from, int xBest, int yBest, int zBest,
|
|||
/*protected*/
|
||||
void Level::setInitialSpawn() {
|
||||
isFindingSpawn = true;
|
||||
int xSpawn = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH / 2; // (Level.MAX_LEVEL_SIZE - 100) * 0;
|
||||
// The world is infinite: start looking for dry land around the origin.
|
||||
int xSpawn = 0;
|
||||
int ySpawn = 64;
|
||||
int zSpawn = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_DEPTH / 2; // (Level.MAX_LEVEL_SIZE - 100) * 0;
|
||||
int zSpawn = 0;
|
||||
while (!dimension->isValidSpawn(xSpawn, zSpawn)) {
|
||||
xSpawn += random.nextInt(32) - random.nextInt(32);
|
||||
zSpawn += random.nextInt(32) - random.nextInt(32);
|
||||
|
||||
if (xSpawn < 4) xSpawn += 32;
|
||||
if (xSpawn >= LevelConstants::LEVEL_WIDTH-4) xSpawn -= 32;
|
||||
if (zSpawn < 4) zSpawn += 32;
|
||||
if (zSpawn >= LevelConstants::LEVEL_DEPTH-4) zSpawn -= 32;
|
||||
}
|
||||
levelData.setSpawn(xSpawn, ySpawn, zSpawn);
|
||||
isFindingSpawn = false;
|
||||
|
|
@ -457,11 +452,6 @@ void Level::validateSpawn() {
|
|||
while (getTopTile(xSpawn, zSpawn) == 0 || getTopTile(xSpawn, zSpawn) == Tile::invisible_bedrock->id) {
|
||||
xSpawn += random.nextInt(8) - random.nextInt(8);
|
||||
zSpawn += random.nextInt(8) - random.nextInt(8);
|
||||
|
||||
if (xSpawn < 4) xSpawn += 8;
|
||||
if (xSpawn >= LevelConstants::LEVEL_WIDTH-4) xSpawn -= 8;
|
||||
if (zSpawn < 4) zSpawn += 8;
|
||||
if (zSpawn >= LevelConstants::LEVEL_DEPTH-4) zSpawn -= 8;
|
||||
}
|
||||
levelData.setXSpawn(xSpawn);
|
||||
levelData.setZSpawn(zSpawn);
|
||||
|
|
@ -947,10 +937,8 @@ HitResult Level::clip(const Vec3& A, const Vec3& b, bool liquid /*= false*/, boo
|
|||
if (solidOnly && tile != NULL && tile->getAABB(this, xTile0, yTile0, zTile0) == NULL) {
|
||||
// No collision
|
||||
} else if (t > 0 && tile->mayPick(data, liquid)) {
|
||||
if(xTile0 >= 0 && zTile0 >= 0 && xTile0 < LevelConstants::LEVEL_WIDTH && zTile0 < LevelConstants::LEVEL_WIDTH) {
|
||||
HitResult r = tile->clip(this, xTile0, yTile0, zTile0, a, b);
|
||||
if (r.isHit()) return r;
|
||||
}
|
||||
HitResult r = tile->clip(this, xTile0, yTile0, zTile0, a, b);
|
||||
if (r.isHit()) return r;
|
||||
}
|
||||
}
|
||||
return HitResult();
|
||||
|
|
@ -1022,7 +1010,12 @@ bool Level::addEntity(Entity* e) {
|
|||
if (e->isPlayer() && std::find(players.begin(), players.end(), e) == players.end()) {
|
||||
players.push_back( (Player*) e );
|
||||
}
|
||||
getChunk(xc, zc)->addEntity(e);
|
||||
if (!isClientSide || hasChunk(xc, zc)) {
|
||||
getChunk(xc, zc)->addEntity(e);
|
||||
} else {
|
||||
// chunk not streamed in yet: the entity is attached by Level::tick(Entity*) later
|
||||
e->inChunk = false;
|
||||
}
|
||||
entities.push_back(e);
|
||||
entityIdLookup[e->entityId] = e;
|
||||
entityAdded(e);
|
||||
|
|
@ -2250,9 +2243,20 @@ void Level::setNightMode( bool isNightMode ) {
|
|||
}
|
||||
|
||||
bool Level::inRange( int x, int y, int z ) {
|
||||
return x >= 0 && x < LevelConstants::LEVEL_WIDTH
|
||||
return x > -LevelConstants::LEVEL_WIDTH && x < LevelConstants::LEVEL_WIDTH
|
||||
&& y >= 0 && y < LevelConstants::LEVEL_HEIGHT
|
||||
&& z >= 0 && z < LevelConstants::LEVEL_DEPTH;
|
||||
&& z > -LevelConstants::LEVEL_DEPTH && z < LevelConstants::LEVEL_DEPTH;
|
||||
}
|
||||
|
||||
// Makes sure the chunks around a block position exist (generating/loading
|
||||
// them right now). Used before something is placed in an area that no
|
||||
// player has streamed in yet.
|
||||
void Level::ensureChunksAround(int x, int z, int radiusInChunks) {
|
||||
const int cx = x >> 4;
|
||||
const int cz = z >> 4;
|
||||
for (int dx = -radiusInChunks; dx <= radiusInChunks; ++dx)
|
||||
for (int dz = -radiusInChunks; dz <= radiusInChunks; ++dz)
|
||||
getChunk(cx + dx, cz + dz);
|
||||
}
|
||||
|
||||
//
|
||||
|
|
|
|||
|
|
@ -274,6 +274,7 @@ public:
|
|||
*/
|
||||
/*virtual*/ void setInitialSpawn();
|
||||
bool inRange(int x, int y, int z);
|
||||
void ensureChunksAround(int x, int z, int radiusInChunks);
|
||||
protected:
|
||||
void setZombieAi(std::vector<Zombie*>& zombies);
|
||||
/*virtual*/ void entityAdded(Entity* e);
|
||||
|
|
|
|||
|
|
@ -1,10 +1,14 @@
|
|||
#include "LevelConstants.h"
|
||||
|
||||
int LevelConstants::LEVEL_HEIGHT = 128;
|
||||
int LevelConstants::CHUNK_CACHE_WIDTH = 16; // in chunks
|
||||
int LevelConstants::CHUNK_WIDTH = 16; // in blocks
|
||||
int LevelConstants::CHUNK_DEPTH = 16;
|
||||
int LevelConstants::LEVEL_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH * CHUNK_WIDTH;
|
||||
int LevelConstants::LEVEL_DEPTH = LevelConstants::CHUNK_CACHE_WIDTH * CHUNK_DEPTH;
|
||||
// The world is infinite: these are only the outer bounds of the coordinate
|
||||
// system (blocks), kept far away so nothing ever reaches them in practice.
|
||||
int LevelConstants::LEVEL_WIDTH = 32000000;
|
||||
int LevelConstants::LEVEL_DEPTH = 32000000;
|
||||
// Legacy value, only sent over the network for compatibility.
|
||||
int LevelConstants::CHUNK_CACHE_WIDTH = 16; // in chunks
|
||||
int LevelConstants::VIEW_DISTANCE_CHUNKS = 10; // chunks kept loaded around every player
|
||||
int LevelConstants::CHUNK_COLUMNS = LevelConstants::CHUNK_WIDTH * LevelConstants::CHUNK_DEPTH;
|
||||
int LevelConstants::CHUNK_BLOCK_COUNT = LevelConstants::CHUNK_COLUMNS * LevelConstants::LEVEL_HEIGHT;
|
||||
int LevelConstants::CHUNK_BLOCK_COUNT = LevelConstants::CHUNK_COLUMNS * LevelConstants::LEVEL_HEIGHT;
|
||||
|
|
|
|||
|
|
@ -1,14 +1,22 @@
|
|||
#pragma once
|
||||
|
||||
class LevelConstants {
|
||||
public:
|
||||
static int CHUNK_CACHE_WIDTH; // in chunks
|
||||
static int LEVEL_WIDTH;
|
||||
static int LEVEL_DEPTH;
|
||||
static int LEVEL_HEIGHT;
|
||||
|
||||
static int CHUNK_WIDTH; // in blocks
|
||||
static int CHUNK_DEPTH;
|
||||
static int CHUNK_COLUMNS;
|
||||
static int CHUNK_BLOCK_COUNT;
|
||||
};
|
||||
#pragma once
|
||||
|
||||
class LevelConstants {
|
||||
public:
|
||||
static int CHUNK_CACHE_WIDTH; // legacy: only used by the network protocol
|
||||
static int LEVEL_WIDTH; // blocks, outer bound of the (infinite) world
|
||||
static int LEVEL_DEPTH;
|
||||
static int LEVEL_HEIGHT;
|
||||
|
||||
// Number of chunks around each player that the server keeps loaded.
|
||||
static int VIEW_DISTANCE_CHUNKS;
|
||||
|
||||
static int CHUNK_WIDTH; // in blocks
|
||||
static int CHUNK_DEPTH;
|
||||
static int CHUNK_COLUMNS;
|
||||
static int CHUNK_BLOCK_COUNT;
|
||||
|
||||
// Chunk coordinates are packed into one 64 bit key.
|
||||
static long long chunkKey(int x, int z) {
|
||||
return ((long long)x << 32) | (unsigned int)z;
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -38,12 +38,20 @@ int MobSpawner::tick(Level* level, bool spawnEnemies, bool spawnFriendlies) {
|
|||
// (The code above is the same as in the java version)
|
||||
// This code goes over the whole map one "row" at a time
|
||||
|
||||
// Spawn friendlies == loop over whole map, and disable Monster spawning this tick
|
||||
// Spawn friendlies == loop over the chunks around every player, and disable Monster spawning this tick
|
||||
if (spawnFriendlies) {
|
||||
spawnEnemies = false;
|
||||
for (int i = 0; i < 256; ++i)
|
||||
chunksToPoll.insert( std::make_pair( ChunkPos(i>>4, i&15), false) );
|
||||
|
||||
const int r = 8;
|
||||
for (unsigned int pi = 0; pi < level->players.size(); ++pi) {
|
||||
Player* p = level->players[pi];
|
||||
int xx = Mth::floor(p->x / 16);
|
||||
int zz = Mth::floor(p->z / 16);
|
||||
for (int x = -r; x <= r; x++)
|
||||
for (int z = -r; z <= r; z++) {
|
||||
if (level->hasChunk(xx + x, zz + z))
|
||||
chunksToPoll.insert(std::make_pair(ChunkPos(xx + x, zz + z), false));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Only spawn mobs, check around one player per tick (@todo: optimize the "count instances of"?)
|
||||
static unsigned int _pid = 0;
|
||||
|
|
@ -57,7 +65,7 @@ int MobSpawner::tick(Level* level, bool spawnEnemies, bool spawnFriendlies) {
|
|||
for (int z = -r; z <= r; z++) {
|
||||
const int cx = xx + x;
|
||||
const int cz = zz + z;
|
||||
if (cx >= 0 && cx < 16 && cz >= 0 && cz < 16)
|
||||
if (level->hasChunk(cx, cz))
|
||||
chunksToPoll.insert(std::make_pair(ChunkPos(cx, cz), false ));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
380
src/world/level/chunk/ChunkCache.cpp
Normal file
|
|
@ -0,0 +1,380 @@
|
|||
#include "ChunkCache.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <sstream>
|
||||
|
||||
#include "../tile/entity/TileEntity.h"
|
||||
#include "../../entity/EntityFactory.h"
|
||||
#include "../../entity/player/Player.h"
|
||||
#include "../../../nbt/CompoundTag.h"
|
||||
#include "../../../nbt/ListTag.h"
|
||||
#include "../../../platform/log.h"
|
||||
#include "../../../platform/time.h"
|
||||
#include "../../../util/Mth.h"
|
||||
|
||||
ChunkCache::ChunkCache(Level* level_, ChunkStorage* storage_, ChunkSource* source_)
|
||||
: loadBudgetMs(10),
|
||||
manualStreaming(false),
|
||||
xLast(-999999999),
|
||||
zLast(-999999999),
|
||||
source(source_),
|
||||
storage(storage_),
|
||||
level(level_),
|
||||
last(NULL),
|
||||
tickCount(0),
|
||||
spiralRadius(-1),
|
||||
playerRoundRobin(0)
|
||||
{
|
||||
isChunkCache = true;
|
||||
emptyChunk = new EmptyLevelChunk(level_, NULL, 0, 0);
|
||||
LOGI("Chunk cache created (infinite world).\n");
|
||||
}
|
||||
|
||||
ChunkCache::~ChunkCache()
|
||||
{
|
||||
delete source;
|
||||
delete emptyChunk;
|
||||
|
||||
for (ChunkMap::iterator it = chunks.begin(); it != chunks.end(); ++it) {
|
||||
it->second->deleteBlockData();
|
||||
delete it->second;
|
||||
}
|
||||
chunks.clear();
|
||||
}
|
||||
|
||||
bool ChunkCache::hasChunk(int x, int z)
|
||||
{
|
||||
if (x == xLast && z == zLast && last != NULL)
|
||||
return true;
|
||||
return chunks.find(LevelConstants::chunkKey(x, z)) != chunks.end();
|
||||
}
|
||||
|
||||
LevelChunk* ChunkCache::create(int x, int z)
|
||||
{
|
||||
return getChunk(x, z);
|
||||
}
|
||||
|
||||
LevelChunk* ChunkCache::getChunk(int x, int z)
|
||||
{
|
||||
if (x == xLast && z == zLast && last != NULL) {
|
||||
return last;
|
||||
}
|
||||
|
||||
const long long key = LevelConstants::chunkKey(x, z);
|
||||
ChunkMap::iterator found = chunks.find(key);
|
||||
if (found != chunks.end()) {
|
||||
xLast = x;
|
||||
zLast = z;
|
||||
last = found->second;
|
||||
return last;
|
||||
}
|
||||
|
||||
bool fromSave = false;
|
||||
LevelChunk* newChunk = load(x, z);
|
||||
if (newChunk != NULL) {
|
||||
fromSave = true;
|
||||
} else if (source == NULL) {
|
||||
// nothing can create this chunk
|
||||
return emptyChunk;
|
||||
} else {
|
||||
newChunk = source->getChunk(x, z);
|
||||
}
|
||||
|
||||
chunks[key] = newChunk;
|
||||
xLast = x;
|
||||
zLast = z;
|
||||
last = newChunk;
|
||||
|
||||
newChunk->lightLava();
|
||||
|
||||
if (fromSave) {
|
||||
for (int cx = 0; cx < 16; cx++)
|
||||
{
|
||||
for (int cz = 0; cz < 16; cz++)
|
||||
{
|
||||
int height = level->getHeightmap(cx + x * 16, cz + z * 16);
|
||||
for (int cy = height; cy >= 0; cy--)
|
||||
{
|
||||
level->updateLight(LightLayer::Sky, cx + x * 16, cy, cz + z * 16, cx + x * 16, cy, cz + z * 16);
|
||||
level->updateLight(LightLayer::Block, cx + x * 16 - 1, cy, cz + z * 16 - 1, cx + x * 16 + 1, cy, cz + z * 16 + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
newChunk->load();
|
||||
restoreEntities(newChunk);
|
||||
|
||||
if (!newChunk->terrainPopulated && hasChunk(x + 1, z + 1) && hasChunk(x, z + 1) && hasChunk(x + 1, z)) postProcess(this, x, z);
|
||||
if (hasChunk(x - 1, z) && !getChunk(x - 1, z)->terrainPopulated && hasChunk(x - 1, z + 1) && hasChunk(x, z + 1) && hasChunk(x - 1, z)) postProcess(this, x - 1, z);
|
||||
if (hasChunk(x, z - 1) && !getChunk(x, z - 1)->terrainPopulated && hasChunk(x + 1, z - 1) && hasChunk(x, z - 1) && hasChunk(x + 1, z)) postProcess(this, x, z - 1);
|
||||
if (hasChunk(x - 1, z - 1) && !getChunk(x - 1, z - 1)->terrainPopulated && hasChunk(x - 1, z - 1) && hasChunk(x, z - 1) && hasChunk(x - 1, z)) postProcess(this, x - 1, z - 1);
|
||||
|
||||
xLast = x;
|
||||
zLast = z;
|
||||
last = newChunk;
|
||||
|
||||
// let the renderers know that there is something to draw here now
|
||||
level->setTilesDirty(x * 16 - 1, 0, z * 16 - 1, x * 16 + 16, LevelConstants::LEVEL_HEIGHT - 1, z * 16 + 16);
|
||||
return newChunk;
|
||||
}
|
||||
|
||||
void ChunkCache::postProcess(ChunkSource* parent, int x, int z)
|
||||
{
|
||||
LevelChunk* chunk = getChunk(x, z);
|
||||
if (!chunk->terrainPopulated) {
|
||||
chunk->terrainPopulated = true;
|
||||
if (source != NULL) {
|
||||
source->postProcess(parent, x, z);
|
||||
chunk->clearUpdateMap();
|
||||
// the decorations belong to the generated state, make sure they are written out
|
||||
chunk->unsaved = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LevelChunk* ChunkCache::load(int x, int z)
|
||||
{
|
||||
if (storage == NULL || level->isClientSide) return NULL;
|
||||
|
||||
LevelChunk* levelChunk = storage->load(level, x, z);
|
||||
if (levelChunk != NULL) {
|
||||
levelChunk->lastSaveTime = level->getTime();
|
||||
}
|
||||
return levelChunk;
|
||||
}
|
||||
|
||||
void ChunkCache::save(LevelChunk* levelChunk)
|
||||
{
|
||||
if (storage == NULL || levelChunk->dontSave) return;
|
||||
|
||||
levelChunk->lastSaveTime = level->getTime();
|
||||
storage->save(level, levelChunk);
|
||||
levelChunk->unsaved = false;
|
||||
}
|
||||
|
||||
bool ChunkCache::hasLiveData(LevelChunk* levelChunk)
|
||||
{
|
||||
return levelChunk->countEntities() > 0 || !levelChunk->getTileEntityMap().empty();
|
||||
}
|
||||
|
||||
// Spawns the entities and tile entities that were stored together with a chunk
|
||||
void ChunkCache::restoreEntities(LevelChunk* levelChunk)
|
||||
{
|
||||
CompoundTag* tag = levelChunk->pendingData;
|
||||
if (!tag) return;
|
||||
levelChunk->pendingData = NULL;
|
||||
|
||||
if (!level->isClientSide) {
|
||||
if (tag->contains("TileEntities", Tag::TAG_List)) {
|
||||
ListTag* tileEntityTags = tag->getList("TileEntities");
|
||||
for (int i = 0; i < tileEntityTags->size(); ++i) {
|
||||
Tag* _et = tileEntityTags->get(i);
|
||||
if (!_et || _et->getId() != Tag::TAG_Compound) continue;
|
||||
|
||||
if (TileEntity* te = TileEntity::loadStatic((CompoundTag*)_et)) {
|
||||
if (!levelChunk->hasTileEntityAt(te)) {
|
||||
levelChunk->addTileEntity(te);
|
||||
} else {
|
||||
delete te;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (tag->contains("Entities", Tag::TAG_List)) {
|
||||
ListTag* entityTags = tag->getList("Entities");
|
||||
for (int i = 0; i < entityTags->size(); ++i) {
|
||||
Tag* _et = entityTags->get(i);
|
||||
if (!_et || _et->getId() != Tag::TAG_Compound) continue;
|
||||
|
||||
if (Entity* e = EntityFactory::loadEntity((CompoundTag*)_et, level)) {
|
||||
level->addEntity(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tag->deleteChildren();
|
||||
delete tag;
|
||||
}
|
||||
|
||||
void ChunkCache::unloadChunk(int x, int z)
|
||||
{
|
||||
ChunkMap::iterator it = chunks.find(LevelConstants::chunkKey(x, z));
|
||||
if (it == chunks.end()) return;
|
||||
|
||||
LevelChunk* chunk = it->second;
|
||||
|
||||
if (!level->isClientSide) {
|
||||
// Write the chunk (and everything living in it) out first
|
||||
save(chunk);
|
||||
|
||||
// The entities leave the world together with their chunk; they come back when it is loaded again
|
||||
std::vector<Entity*> es;
|
||||
chunk->collectEntities(es);
|
||||
for (unsigned int i = 0; i < es.size(); ++i) {
|
||||
Entity* e = es[i];
|
||||
if (e->isPlayer()) continue;
|
||||
e->inChunk = false;
|
||||
level->removeEntity(e);
|
||||
}
|
||||
}
|
||||
chunk->detachEntities();
|
||||
|
||||
chunks.erase(it);
|
||||
if (last == chunk) {
|
||||
last = NULL;
|
||||
xLast = zLast = -999999999;
|
||||
}
|
||||
|
||||
// Tile entities are owned by the level
|
||||
LevelChunk::TEMap& teMap = chunk->getTileEntityMapMutable();
|
||||
for (LevelChunk::TEMap::iterator te = teMap.begin(); te != teMap.end(); ++te) {
|
||||
TileEntity* t = te->second;
|
||||
if (!t) continue;
|
||||
Util::remove(level->pendingTileEntities, t);
|
||||
Util::remove(level->tileEntities, t);
|
||||
delete t;
|
||||
}
|
||||
teMap.clear();
|
||||
|
||||
chunk->unload();
|
||||
if (source) source->releaseChunk(x, z);
|
||||
chunk->deleteBlockData();
|
||||
delete chunk;
|
||||
}
|
||||
|
||||
void ChunkCache::getLoadedChunks(std::vector<LevelChunk*>& out)
|
||||
{
|
||||
out.reserve(out.size() + chunks.size());
|
||||
for (ChunkMap::iterator it = chunks.begin(); it != chunks.end(); ++it)
|
||||
out.push_back(it->second);
|
||||
}
|
||||
|
||||
bool ChunkCache::tick()
|
||||
{
|
||||
tickCount++;
|
||||
if (storage != NULL) storage->tick();
|
||||
|
||||
if (!level->isClientSide && !manualStreaming) {
|
||||
streamAroundPlayers();
|
||||
if ((tickCount % 10) == 0) unloadFarChunks();
|
||||
autosave();
|
||||
}
|
||||
return source != NULL ? source->tick() : false;
|
||||
}
|
||||
|
||||
void ChunkCache::streamAroundPlayers()
|
||||
{
|
||||
const PlayerList& players = level->players;
|
||||
if (players.empty()) return;
|
||||
|
||||
const int radius = LevelConstants::VIEW_DISTANCE_CHUNKS;
|
||||
if (radius != spiralRadius) {
|
||||
spiralRadius = radius;
|
||||
spiral.clear();
|
||||
for (int dx = -radius; dx <= radius; ++dx)
|
||||
for (int dz = -radius; dz <= radius; ++dz)
|
||||
if (dx * dx + dz * dz <= radius * radius + radius)
|
||||
spiral.push_back(std::make_pair(dx, dz));
|
||||
struct ByDistance {
|
||||
bool operator()(const std::pair<int, int>& a, const std::pair<int, int>& b) const {
|
||||
return a.first * a.first + a.second * a.second < b.first * b.first + b.second * b.second;
|
||||
}
|
||||
};
|
||||
std::stable_sort(spiral.begin(), spiral.end(), ByDistance());
|
||||
}
|
||||
|
||||
std::vector<std::pair<int, int> > centers;
|
||||
for (unsigned int i = 0; i < players.size(); ++i) {
|
||||
Player* p = players[i];
|
||||
if (p->removed) continue;
|
||||
centers.push_back(std::make_pair(Mth::floor(p->x / 16.0f), Mth::floor(p->z / 16.0f)));
|
||||
}
|
||||
if (centers.empty()) return;
|
||||
|
||||
const int start = getTimeMs();
|
||||
for (unsigned int i = 0; i < spiral.size(); ++i) {
|
||||
for (unsigned int c = 0; c < centers.size(); ++c) {
|
||||
const int cx = centers[c].first + spiral[i].first;
|
||||
const int cz = centers[c].second + spiral[i].second;
|
||||
if (!hasChunk(cx, cz)) {
|
||||
getChunk(cx, cz);
|
||||
if (getTimeMs() - start >= loadBudgetMs) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ChunkCache::unloadFarChunks()
|
||||
{
|
||||
const PlayerList& players = level->players;
|
||||
if (players.empty()) return;
|
||||
|
||||
std::vector<std::pair<int, int> > centers;
|
||||
for (unsigned int i = 0; i < players.size(); ++i) {
|
||||
Player* p = players[i];
|
||||
centers.push_back(std::make_pair(Mth::floor(p->x / 16.0f), Mth::floor(p->z / 16.0f)));
|
||||
}
|
||||
|
||||
const int unloadRadius = LevelConstants::VIEW_DISTANCE_CHUNKS + 3;
|
||||
std::vector<std::pair<int, int> > victims;
|
||||
for (ChunkMap::iterator it = chunks.begin(); it != chunks.end() && victims.size() < 6; ++it) {
|
||||
LevelChunk* c = it->second;
|
||||
bool isNear = false;
|
||||
for (unsigned int i = 0; i < centers.size(); ++i) {
|
||||
if (std::abs(c->x - centers[i].first) <= unloadRadius && std::abs(c->z - centers[i].second) <= unloadRadius) {
|
||||
isNear = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!isNear) victims.push_back(std::make_pair(c->x, c->z));
|
||||
}
|
||||
for (unsigned int i = 0; i < victims.size(); ++i)
|
||||
unloadChunk(victims[i].first, victims[i].second);
|
||||
}
|
||||
|
||||
void ChunkCache::autosave()
|
||||
{
|
||||
if (storage == NULL) return;
|
||||
|
||||
if ((tickCount % 1200) == 0) {
|
||||
autosaveQueue.clear();
|
||||
for (ChunkMap::iterator it = chunks.begin(); it != chunks.end(); ++it) {
|
||||
LevelChunk* c = it->second;
|
||||
if (c->shouldSave(false) || hasLiveData(c))
|
||||
autosaveQueue.push_back(it->first);
|
||||
}
|
||||
}
|
||||
|
||||
for (int n = 0; n < 3 && !autosaveQueue.empty(); ++n) {
|
||||
long long key = autosaveQueue.front();
|
||||
autosaveQueue.pop_front();
|
||||
ChunkMap::iterator it = chunks.find(key);
|
||||
if (it != chunks.end()) save(it->second);
|
||||
}
|
||||
}
|
||||
|
||||
void ChunkCache::saveAll(bool onlyUnsaved)
|
||||
{
|
||||
if (storage == NULL) return;
|
||||
|
||||
std::vector<LevelChunk*> toSave;
|
||||
for (ChunkMap::iterator it = chunks.begin(); it != chunks.end(); ++it) {
|
||||
LevelChunk* c = it->second;
|
||||
if (c->dontSave) continue;
|
||||
if (!onlyUnsaved || c->shouldSave(false) || hasLiveData(c))
|
||||
toSave.push_back(c);
|
||||
}
|
||||
storage->saveAll(level, toSave);
|
||||
for (unsigned int i = 0; i < toSave.size(); ++i)
|
||||
toSave[i]->unsaved = false;
|
||||
}
|
||||
|
||||
std::string ChunkCache::gatherStats()
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "ChunkCache: " << chunks.size();
|
||||
return ss.str();
|
||||
}
|
||||
|
|
@ -1,270 +1,87 @@
|
|||
#ifndef NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkCache_H__
|
||||
#define NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkCache_H__
|
||||
|
||||
//package net.minecraft.world.level.chunk;
|
||||
|
||||
#include "ChunkSource.h"
|
||||
#include "storage/ChunkStorage.h"
|
||||
#include "EmptyLevelChunk.h"
|
||||
#include "../Level.h"
|
||||
#include "../LevelConstants.h"
|
||||
|
||||
class ChunkCache: public ChunkSource {
|
||||
//static const int LevelConstants::CHUNK_CACHE_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH; // WAS 32;
|
||||
static const int MAX_SAVES = 2;
|
||||
public:
|
||||
ChunkCache(Level* level_, ChunkStorage* storage_, ChunkSource* source_)
|
||||
: xLast(-999999999),
|
||||
zLast(-999999999),
|
||||
last(NULL),
|
||||
level(level_),
|
||||
storage(storage_),
|
||||
source(source_)
|
||||
{
|
||||
isChunkCache = true;
|
||||
//emptyChunk = new EmptyLevelChunk(level_, emptyChunkBlocks, 0, 0);
|
||||
emptyChunk = new EmptyLevelChunk(level_, NULL, 0, 0);
|
||||
|
||||
chunks = new LevelChunk *[LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH];
|
||||
memset(chunks, 0, sizeof(LevelChunk*) * LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH);
|
||||
LOGI("Chunks allocated.");
|
||||
}
|
||||
|
||||
~ChunkCache() {
|
||||
delete source;
|
||||
delete emptyChunk;
|
||||
|
||||
for (int i = 0; i < LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH; i++)
|
||||
{
|
||||
if (chunks[i])
|
||||
{
|
||||
chunks[i]->deleteBlockData();
|
||||
delete chunks[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool fits(int x, int z) {
|
||||
return (x >= 0 && z >= 0 && x < LevelConstants::CHUNK_CACHE_WIDTH && z < LevelConstants::CHUNK_CACHE_WIDTH);
|
||||
}
|
||||
|
||||
bool hasChunk(int x, int z) {
|
||||
// with a fixed world size, chunks outside the fitting area are always available (emptyChunks)
|
||||
if (!fits(x, z)) return true;
|
||||
|
||||
if (x == xLast && z == zLast && last != NULL) {
|
||||
return true;
|
||||
}
|
||||
int xs = x & (LevelConstants::CHUNK_CACHE_WIDTH - 1);
|
||||
int zs = z & (LevelConstants::CHUNK_CACHE_WIDTH - 1);
|
||||
int slot = xs + zs * LevelConstants::CHUNK_CACHE_WIDTH;
|
||||
return chunks[slot] != NULL && (chunks[slot] == emptyChunk || chunks[slot]->isAt(x, z));
|
||||
}
|
||||
|
||||
LevelChunk* create(int x, int z) {
|
||||
return getChunk(x, z);
|
||||
}
|
||||
|
||||
LevelChunk* getChunk(int x, int z) {
|
||||
//static Stopwatch sw;
|
||||
//sw.start();
|
||||
|
||||
if (x == xLast && z == zLast && last != NULL) {
|
||||
return last;
|
||||
}
|
||||
if (!fits(x, z)) return emptyChunk;
|
||||
//if (!level->isFindingSpawn && !fits(x, z)) return emptyChunk;
|
||||
int xs = x & (LevelConstants::CHUNK_CACHE_WIDTH - 1);
|
||||
int zs = z & (LevelConstants::CHUNK_CACHE_WIDTH - 1);
|
||||
int slot = xs + zs * LevelConstants::CHUNK_CACHE_WIDTH;
|
||||
if (!hasChunk(x, z)) {
|
||||
if (chunks[slot] != NULL) {
|
||||
chunks[slot]->unload();
|
||||
save(chunks[slot]);
|
||||
saveEntities(chunks[slot]);
|
||||
}
|
||||
|
||||
LevelChunk* newChunk = load(x, z);
|
||||
bool updateLights = false;
|
||||
if (newChunk == NULL) {
|
||||
if (source == NULL) {
|
||||
newChunk = emptyChunk;
|
||||
} else {
|
||||
newChunk = source->getChunk(x, z);
|
||||
}
|
||||
} else {
|
||||
//return emptyChunk;
|
||||
updateLights = true;
|
||||
}
|
||||
chunks[slot] = newChunk;
|
||||
newChunk->lightLava();
|
||||
|
||||
if (updateLights)
|
||||
{
|
||||
for (int cx = 0; cx < 16; cx++)
|
||||
{
|
||||
for (int cz = 0; cz < 16; cz++)
|
||||
{
|
||||
int height = level->getHeightmap(cx + x * 16, cz + z * 16);
|
||||
for (int cy = height; cy >= 0; cy--)
|
||||
{
|
||||
level->updateLight(LightLayer::Sky, cx + x * 16, cy, cz + z * 16, cx + x * 16, cy, cz + z * 16);
|
||||
level->updateLight(LightLayer::Block, cx + x * 16 - 1, cy, cz + z * 16 - 1, cx + x * 16 + 1, cy, cz + z * 16 + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
//level->updateLight(LightLayer::Sky, x * 16, 0, z * 16, x * 16 + 15, 128, z * 16 + 15);
|
||||
//level->updateLight(LightLayer::Block, x * 16, 0, z * 16, x * 16 + 15, 128, z * 16 + 15);
|
||||
}
|
||||
|
||||
if (chunks[slot] != NULL) {
|
||||
chunks[slot]->load();
|
||||
}
|
||||
|
||||
if (!chunks[slot]->terrainPopulated && hasChunk(x + 1, z + 1) && hasChunk(x, z + 1) && hasChunk(x + 1, z)) postProcess(this, x, z);
|
||||
if (hasChunk(x - 1, z) && !getChunk(x - 1, z)->terrainPopulated && hasChunk(x - 1, z + 1) && hasChunk(x, z + 1) && hasChunk(x - 1, z)) postProcess(this, x - 1, z);
|
||||
if (hasChunk(x, z - 1) && !getChunk(x, z - 1)->terrainPopulated && hasChunk(x + 1, z - 1) && hasChunk(x, z - 1) && hasChunk(x + 1, z)) postProcess(this, x, z - 1);
|
||||
if (hasChunk(x - 1, z - 1) && !getChunk(x - 1, z - 1)->terrainPopulated && hasChunk(x - 1, z - 1) && hasChunk(x, z - 1) && hasChunk(x - 1, z)) postProcess(this, x - 1, z - 1);
|
||||
}
|
||||
xLast = x;
|
||||
zLast = z;
|
||||
last = chunks[slot];
|
||||
|
||||
//sw.stop();
|
||||
//sw.printEvery(500000, "ChunkCache::load: ");
|
||||
|
||||
return chunks[slot];
|
||||
}
|
||||
|
||||
Biome::MobList getMobsAt(const MobCategory& mobCategory, int x, int y, int z) {
|
||||
return source->getMobsAt(mobCategory, x, y, z);
|
||||
}
|
||||
|
||||
void postProcess(ChunkSource* parent, int x, int z) {
|
||||
if (!fits(x, z)) return;
|
||||
LevelChunk* chunk = getChunk(x, z);
|
||||
if (!chunk->terrainPopulated) {
|
||||
chunk->terrainPopulated = true;
|
||||
if (source != NULL) {
|
||||
source->postProcess(parent, x, z);
|
||||
chunk->clearUpdateMap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//bool save(bool force, ProgressListener progressListener) {
|
||||
// int saves = 0;
|
||||
// int count = 0;
|
||||
// if (progressListener != NULL) {
|
||||
// for (int i = 0; i < chunks.length; i++) {
|
||||
// if (chunks[i] != NULL && chunks[i].shouldSave(force)) {
|
||||
// count++;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// int cc = 0;
|
||||
// for (int i = 0; i < chunks.length; i++) {
|
||||
// if (chunks[i] != NULL) {
|
||||
// if (force && !chunks[i].dontSave) saveEntities(chunks[i]);
|
||||
// if (chunks[i].shouldSave(force)) {
|
||||
// save(chunks[i]);
|
||||
// chunks[i].unsaved = false;
|
||||
// if (++saves == MAX_SAVES && !force) return false;
|
||||
// if (progressListener != NULL) {
|
||||
// if (++cc % 10 == 0) {
|
||||
// progressListener.progressStagePercentage(cc * 100 / count);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// if (force) {
|
||||
// if (storage == NULL) return true;
|
||||
// storage.flush();
|
||||
// }
|
||||
// return true;
|
||||
//}
|
||||
|
||||
bool tick() {
|
||||
if (storage != NULL) storage->tick();
|
||||
return source->tick();
|
||||
}
|
||||
|
||||
bool shouldSave() {
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string gatherStats() {
|
||||
// return "ChunkCache: 1024";
|
||||
std::stringstream ss;
|
||||
ss << "ChunkCache: " << LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH;
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
void saveAll(bool onlyUnsaved) {
|
||||
if (storage != NULL) {
|
||||
std::vector<LevelChunk*> chunks;
|
||||
for (int z = 0; z < LevelConstants::CHUNK_CACHE_WIDTH; ++z)
|
||||
for (int x = 0; x < LevelConstants::CHUNK_CACHE_WIDTH; ++x) {
|
||||
LevelChunk* chunk = level->getChunk(x, z);
|
||||
if (!onlyUnsaved || chunk->shouldSave(false))
|
||||
chunks.push_back( chunk );
|
||||
}
|
||||
storage->saveAll(level, chunks);
|
||||
}
|
||||
}
|
||||
private:
|
||||
LevelChunk* load(int x, int z) {
|
||||
if (storage == NULL) return emptyChunk;
|
||||
if (x < 0 || x >= LevelConstants::CHUNK_CACHE_WIDTH || z < 0 || z >= LevelConstants::CHUNK_CACHE_WIDTH)
|
||||
{
|
||||
return emptyChunk;
|
||||
}
|
||||
//try {
|
||||
LevelChunk* levelChunk = storage->load(level, x, z);
|
||||
if (levelChunk != NULL) {
|
||||
levelChunk->lastSaveTime = level->getTime();
|
||||
}
|
||||
return levelChunk;
|
||||
//} catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// return emptyChunk;
|
||||
//}
|
||||
}
|
||||
|
||||
void saveEntities(LevelChunk* levelChunk) {
|
||||
if (storage == NULL) return;
|
||||
//try {
|
||||
storage->saveEntities(level, levelChunk);
|
||||
//} catch (Error e) {
|
||||
// e.printStackTrace();
|
||||
//}
|
||||
}
|
||||
|
||||
void save(LevelChunk* levelChunk) {
|
||||
if (storage == NULL) return;
|
||||
//try {
|
||||
levelChunk->lastSaveTime = level->getTime();
|
||||
storage->save(level, levelChunk);
|
||||
//} catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
//}
|
||||
}
|
||||
|
||||
public:
|
||||
int xLast;
|
||||
int zLast;
|
||||
private:
|
||||
//unsigned char emptyChunkBlocks[LevelChunk::ChunkBlockCount];
|
||||
LevelChunk* emptyChunk;
|
||||
ChunkSource* source;
|
||||
ChunkStorage* storage;
|
||||
LevelChunk** chunks;
|
||||
Level* level;
|
||||
|
||||
LevelChunk* last;
|
||||
|
||||
};
|
||||
|
||||
#endif /*NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkCache_H__*/
|
||||
#ifndef NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkCache_H__
|
||||
#define NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkCache_H__
|
||||
|
||||
//package net.minecraft.world.level.chunk;
|
||||
|
||||
#include <deque>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "ChunkSource.h"
|
||||
#include "storage/ChunkStorage.h"
|
||||
#include "EmptyLevelChunk.h"
|
||||
#include "../Level.h"
|
||||
#include "../LevelConstants.h"
|
||||
|
||||
/**
|
||||
* Holds every chunk of the (infinite) world that is currently in memory.
|
||||
*
|
||||
* On a server / in single player the cache streams chunks in around each
|
||||
* player, saves and unloads the ones that are left behind, and persists the
|
||||
* entities and tile entities that live in them. On a multiplayer client the
|
||||
* chunks are driven by the network handler instead (see unloadChunk).
|
||||
*/
|
||||
class ChunkCache: public ChunkSource {
|
||||
public:
|
||||
ChunkCache(Level* level_, ChunkStorage* storage_, ChunkSource* source_);
|
||||
~ChunkCache();
|
||||
|
||||
bool hasChunk(int x, int z);
|
||||
LevelChunk* create(int x, int z);
|
||||
LevelChunk* getChunk(int x, int z);
|
||||
|
||||
Biome::MobList getMobsAt(const MobCategory& mobCategory, int x, int y, int z) {
|
||||
return source->getMobsAt(mobCategory, x, y, z);
|
||||
}
|
||||
|
||||
void postProcess(ChunkSource* parent, int x, int z);
|
||||
|
||||
bool tick();
|
||||
bool shouldSave() { return true; }
|
||||
std::string gatherStats();
|
||||
|
||||
void saveAll(bool onlyUnsaved);
|
||||
void unloadChunk(int x, int z);
|
||||
void getLoadedChunks(std::vector<LevelChunk*>& out);
|
||||
int getLoadedChunkCount() { return (int)chunks.size(); }
|
||||
|
||||
// Chunks around the players that were not generated/loaded yet are
|
||||
// created nearest first, at most for this many milliseconds per tick.
|
||||
int loadBudgetMs;
|
||||
|
||||
// Disables the automatic loading/unloading around the players.
|
||||
bool manualStreaming;
|
||||
|
||||
public:
|
||||
int xLast;
|
||||
int zLast;
|
||||
|
||||
private:
|
||||
LevelChunk* load(int x, int z);
|
||||
void save(LevelChunk* levelChunk);
|
||||
void restoreEntities(LevelChunk* levelChunk);
|
||||
bool hasLiveData(LevelChunk* levelChunk);
|
||||
|
||||
void streamAroundPlayers();
|
||||
void unloadFarChunks();
|
||||
void autosave();
|
||||
|
||||
typedef std::unordered_map<long long, LevelChunk*> ChunkMap;
|
||||
ChunkMap chunks;
|
||||
|
||||
LevelChunk* emptyChunk;
|
||||
ChunkSource* source;
|
||||
ChunkStorage* storage;
|
||||
Level* level;
|
||||
|
||||
LevelChunk* last;
|
||||
|
||||
int tickCount;
|
||||
int unloadRadiusCache;
|
||||
std::vector<std::pair<int, int> > spiral; // chunk offsets sorted by distance
|
||||
int spiralRadius;
|
||||
unsigned int playerRoundRobin;
|
||||
std::deque<long long> autosaveQueue;
|
||||
};
|
||||
|
||||
#endif /*NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkCache_H__*/
|
||||
|
|
|
|||
|
|
@ -1,46 +1,56 @@
|
|||
#ifndef NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkSource_H__
|
||||
#define NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkSource_H__
|
||||
|
||||
//package net.minecraft.world.level.chunk;
|
||||
|
||||
#include <string>
|
||||
#include "../biome/Biome.h"
|
||||
|
||||
class ProgressListener;
|
||||
class LevelChunk;
|
||||
|
||||
class ChunkSource
|
||||
{
|
||||
public:
|
||||
bool isChunkCache;
|
||||
|
||||
ChunkSource()
|
||||
: isChunkCache(false)
|
||||
{}
|
||||
|
||||
virtual ~ChunkSource(){}
|
||||
|
||||
virtual bool hasChunk(int x, int y) = 0;
|
||||
|
||||
virtual LevelChunk* getChunk(int x, int z) = 0;
|
||||
|
||||
virtual LevelChunk* create(int x, int z) = 0;
|
||||
|
||||
virtual void postProcess(ChunkSource* parent, int x, int z) = 0;
|
||||
|
||||
//virtual bool save(bool force, ProgressListener* progressListener) = 0;
|
||||
|
||||
virtual bool tick() = 0;
|
||||
|
||||
virtual bool shouldSave() = 0;
|
||||
virtual void saveAll(bool onlyUnsaved) {}
|
||||
|
||||
virtual Biome::MobList getMobsAt(const MobCategory& mobCategory, int x, int y, int z) = 0;
|
||||
|
||||
/**
|
||||
* Returns some stats that are rendered when the user holds F3.
|
||||
*/
|
||||
virtual std::string gatherStats() = 0;
|
||||
};
|
||||
|
||||
#endif /*NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkSource_H__*/
|
||||
#ifndef NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkSource_H__
|
||||
#define NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkSource_H__
|
||||
|
||||
//package net.minecraft.world.level.chunk;
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "../biome/Biome.h"
|
||||
|
||||
class ProgressListener;
|
||||
class LevelChunk;
|
||||
|
||||
class ChunkSource
|
||||
{
|
||||
public:
|
||||
bool isChunkCache;
|
||||
|
||||
ChunkSource()
|
||||
: isChunkCache(false)
|
||||
{}
|
||||
|
||||
virtual ~ChunkSource(){}
|
||||
|
||||
virtual bool hasChunk(int x, int y) = 0;
|
||||
|
||||
virtual LevelChunk* getChunk(int x, int z) = 0;
|
||||
|
||||
// Called when the owner of the chunk has unloaded (and freed) it, so a
|
||||
// generator that keeps its own lookup table must forget about it.
|
||||
virtual void releaseChunk(int x, int z) {}
|
||||
|
||||
// Saves (server) and frees a chunk. Only chunk caches keep chunks.
|
||||
virtual void unloadChunk(int x, int z) {}
|
||||
virtual void getLoadedChunks(std::vector<LevelChunk*>& out) {}
|
||||
virtual int getLoadedChunkCount() { return 0; }
|
||||
|
||||
virtual LevelChunk* create(int x, int z) = 0;
|
||||
|
||||
virtual void postProcess(ChunkSource* parent, int x, int z) = 0;
|
||||
|
||||
//virtual bool save(bool force, ProgressListener* progressListener) = 0;
|
||||
|
||||
virtual bool tick() = 0;
|
||||
|
||||
virtual bool shouldSave() = 0;
|
||||
virtual void saveAll(bool onlyUnsaved) {}
|
||||
|
||||
virtual Biome::MobList getMobsAt(const MobCategory& mobCategory, int x, int y, int z) = 0;
|
||||
|
||||
/**
|
||||
* Returns some stats that are rendered when the user holds F3.
|
||||
*/
|
||||
virtual std::string gatherStats() = 0;
|
||||
};
|
||||
|
||||
#endif /*NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkSource_H__*/
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@
|
|||
#include "../tile/entity/TileEntity.h"
|
||||
#include "../tile/EntityTile.h"
|
||||
#include "../LevelConstants.h"
|
||||
#include "../../../nbt/CompoundTag.h"
|
||||
|
||||
/*static*/
|
||||
bool LevelChunk::touchedSky = false;
|
||||
|
|
@ -41,7 +42,13 @@ LevelChunk::LevelChunk( Level* level, unsigned char* blocks, int x, int z )
|
|||
|
||||
LevelChunk::~LevelChunk()
|
||||
{
|
||||
//delete blocks;
|
||||
//delete blocks; (see deleteBlockData)
|
||||
delete[] heightmap;
|
||||
delete[] updateMap;
|
||||
if (pendingData) {
|
||||
pendingData->deleteChildren();
|
||||
delete pendingData;
|
||||
}
|
||||
}
|
||||
|
||||
void LevelChunk::init()
|
||||
|
|
@ -49,6 +56,8 @@ void LevelChunk::init()
|
|||
heightmap = new char[LevelConstants::CHUNK_COLUMNS];
|
||||
updateMap = new unsigned char[LevelConstants::CHUNK_COLUMNS];
|
||||
|
||||
pendingData = NULL;
|
||||
loaded = false;
|
||||
terrainPopulated = false;
|
||||
dontSave = false;
|
||||
unsaved = false;
|
||||
|
|
@ -537,6 +546,23 @@ void LevelChunk::getEntitiesOfClass( int type, const AABB& bb, EntityList& list
|
|||
}
|
||||
}
|
||||
|
||||
void LevelChunk::collectEntities(std::vector<Entity*>& out) const
|
||||
{
|
||||
for (int yc = 0; yc < EntityBlocksArraySize; yc++) {
|
||||
out.insert(out.end(), entityBlocks[yc].begin(), entityBlocks[yc].end());
|
||||
}
|
||||
}
|
||||
|
||||
void LevelChunk::detachEntities()
|
||||
{
|
||||
for (int yc = 0; yc < EntityBlocksArraySize; yc++) {
|
||||
for (unsigned int i = 0; i < entityBlocks[yc].size(); i++) {
|
||||
entityBlocks[yc][i]->inChunk = false;
|
||||
}
|
||||
entityBlocks[yc].clear();
|
||||
}
|
||||
}
|
||||
|
||||
int LevelChunk::countEntities()
|
||||
{
|
||||
int entityCount = 0;
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ class Entity;
|
|||
class LightLayer;
|
||||
class AABB;
|
||||
class TileEntity;
|
||||
class CompoundTag;
|
||||
typedef std::vector<Entity*> EntityList;
|
||||
|
||||
class LevelChunk
|
||||
|
|
@ -99,6 +100,12 @@ public:
|
|||
|
||||
virtual bool isEmpty();
|
||||
const TEMap& getTileEntityMap() const;
|
||||
TEMap& getTileEntityMapMutable() { return tileEntities; }
|
||||
|
||||
// Appends every entity registered in this chunk (players included)
|
||||
void collectEntities(std::vector<Entity*>& out) const;
|
||||
// Forgets that the entities of this chunk are listed here (the chunk is going away)
|
||||
void detachEntities();
|
||||
private:
|
||||
void lightGap(int x, int z, int source);
|
||||
void lightGaps(int x, int z);
|
||||
|
|
@ -125,6 +132,10 @@ public:
|
|||
int x, z;
|
||||
int xt, zt;
|
||||
|
||||
// Entities and tile entities read from the save file, waiting to be spawned
|
||||
// by the chunk cache once the chunk is registered in the level (owned).
|
||||
CompoundTag* pendingData;
|
||||
|
||||
bool terrainPopulated;
|
||||
bool unsaved;
|
||||
bool dontSave;
|
||||
|
|
|
|||
|
|
@ -537,9 +537,13 @@ LevelChunk* RandomLevelSource::create(int x, int z) {
|
|||
return getChunk(x, z);
|
||||
}
|
||||
|
||||
void RandomLevelSource::releaseChunk(int x, int z) {
|
||||
chunkMap.erase(LevelConstants::chunkKey(x, z));
|
||||
}
|
||||
|
||||
LevelChunk* RandomLevelSource::getChunk(int xOffs, int zOffs) {
|
||||
//static int chunkx = 0;
|
||||
int hashedPos = ChunkPos::hashCode(xOffs, zOffs);
|
||||
const long long hashedPos = LevelConstants::chunkKey(xOffs, zOffs);
|
||||
|
||||
ChunkMap::iterator it = chunkMap.find(hashedPos);
|
||||
if (it != chunkMap.end())
|
||||
|
|
|
|||
|
|
@ -7,20 +7,9 @@ class Biome;
|
|||
class Level;
|
||||
class LevelChunk;
|
||||
|
||||
#if 1 || USE_MAP
|
||||
#include <map>
|
||||
typedef std::map<int, LevelChunk*> ChunkMap;
|
||||
#else
|
||||
#if defined(__APPLE__)
|
||||
#include <ext/hash_map>
|
||||
namespace std {
|
||||
using namespace __gnu_cxx;
|
||||
}
|
||||
#else
|
||||
#include <hash_map>
|
||||
#endif
|
||||
typedef std::hash_map<int, LevelChunk*> ChunkMap;
|
||||
#endif
|
||||
#include <map>
|
||||
// Keyed by LevelConstants::chunkKey(x, z)
|
||||
typedef std::map<long long, LevelChunk*> ChunkMap;
|
||||
|
||||
|
||||
#include "../chunk/ChunkSource.h"
|
||||
|
|
@ -44,6 +33,7 @@ public:
|
|||
bool hasChunk(int x, int y);
|
||||
LevelChunk* create(int x, int z);
|
||||
LevelChunk* getChunk(int xOffs, int zOffs);
|
||||
void releaseChunk(int x, int z);
|
||||
|
||||
void prepareHeights(int xOffs, int zOffs, unsigned char* blocks, /*Biome*/void* biomes, float* temperatures);
|
||||
void buildSurfaces(int xOffs, int zOffs, unsigned char* blocks, Biome** biomes);
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@
|
|||
#include "ExternalFileLevelStorage.h"
|
||||
#include "FolderMethods.h"
|
||||
#include "../chunk/LevelChunk.h"
|
||||
#include "../chunk/ChunkSource.h"
|
||||
#include "../Level.h"
|
||||
#include "../LevelConstants.h"
|
||||
#include "platform/log.h"
|
||||
|
|
@ -82,10 +83,7 @@ ExternalFileLevelStorage::ExternalFileLevelStorage(const std::string& levelId, c
|
|||
: levelId(levelId),
|
||||
levelPath(fullPath),
|
||||
loadedLevelData(NULL),
|
||||
regionFile(NULL),
|
||||
entitiesFile(NULL),
|
||||
tickCount(0),
|
||||
lastSavedEntitiesTick(-999999),
|
||||
level(NULL),
|
||||
loadedStorageVersion(SharedConstants::StorageVersion)
|
||||
{
|
||||
|
|
@ -109,10 +107,53 @@ ExternalFileLevelStorage::ExternalFileLevelStorage(const std::string& levelId, c
|
|||
|
||||
ExternalFileLevelStorage::~ExternalFileLevelStorage()
|
||||
{
|
||||
delete regionFile;
|
||||
closeRegions();
|
||||
delete loadedLevelData;
|
||||
}
|
||||
|
||||
void ExternalFileLevelStorage::closeRegions()
|
||||
{
|
||||
for (std::map<long long, RegionFile*>::iterator it = regions.begin(); it != regions.end(); ++it)
|
||||
delete it->second;
|
||||
regions.clear();
|
||||
regionOrder.clear();
|
||||
}
|
||||
|
||||
// Region files are opened on demand; only a handful stay open at once.
|
||||
RegionFile* ExternalFileLevelStorage::getRegion(int chunkX, int chunkZ)
|
||||
{
|
||||
const int rx = chunkX >> 5;
|
||||
const int rz = chunkZ >> 5;
|
||||
const long long key = LevelConstants::chunkKey(rx, rz);
|
||||
|
||||
std::map<long long, RegionFile*>::iterator it = regions.find(key);
|
||||
if (it != regions.end()) {
|
||||
regionOrder.remove(key);
|
||||
regionOrder.push_back(key);
|
||||
return it->second;
|
||||
}
|
||||
|
||||
static const size_t MaxOpenRegions = 12;
|
||||
while (regions.size() >= MaxOpenRegions && !regionOrder.empty()) {
|
||||
long long oldest = regionOrder.front();
|
||||
regionOrder.pop_front();
|
||||
std::map<long long, RegionFile*>::iterator ot = regions.find(oldest);
|
||||
if (ot != regions.end()) {
|
||||
delete ot->second;
|
||||
regions.erase(ot);
|
||||
}
|
||||
}
|
||||
|
||||
RegionFile* region = new RegionFile(levelPath, rx, rz);
|
||||
if (!region->open()) {
|
||||
delete region;
|
||||
return NULL;
|
||||
}
|
||||
regions[key] = region;
|
||||
regionOrder.push_back(key);
|
||||
return region;
|
||||
}
|
||||
|
||||
void ExternalFileLevelStorage::saveLevelData(LevelData& levelData, std::vector<Player*>* players) {
|
||||
ExternalFileLevelStorage::saveLevelData(levelPath, levelData, players);
|
||||
}
|
||||
|
|
@ -341,10 +382,6 @@ bool ExternalFileLevelStorage::readPlayerData(const std::string& filename, Level
|
|||
|
||||
// Fix coordinates
|
||||
Vec3& pos = dest.playerData.pos;
|
||||
if (pos.x < 0.5f) pos.x = 0.5f;
|
||||
if (pos.z < 0.5f) pos.z = 0.5f;
|
||||
if (pos.x > (LevelConstants::LEVEL_WIDTH - 0.5f)) pos.x = LevelConstants::LEVEL_WIDTH - 0.5f;
|
||||
if (pos.z > (LevelConstants::LEVEL_DEPTH - 0.5f)) pos.z = LevelConstants::LEVEL_DEPTH - 0.5f;
|
||||
if (pos.y < 0) pos.y = 64;
|
||||
|
||||
dest.playerDataVersion = version;
|
||||
|
|
@ -357,61 +394,15 @@ bool ExternalFileLevelStorage::readPlayerData(const std::string& filename, Level
|
|||
|
||||
void ExternalFileLevelStorage::tick()
|
||||
{
|
||||
// Chunks (and the entities inside them) are saved by the chunk cache.
|
||||
tickCount++;
|
||||
if ((tickCount % 1000) == 0 && level) {
|
||||
LOGI("Saving level...\n");
|
||||
|
||||
// look for chunks that needs to be saved
|
||||
for (int z = 0; z < LevelConstants::CHUNK_CACHE_WIDTH; z++)
|
||||
{
|
||||
for (int x = 0; x < LevelConstants::CHUNK_CACHE_WIDTH; x++)
|
||||
{
|
||||
LevelChunk* chunk = level->getChunk(x, z);
|
||||
if (chunk && chunk->unsaved)
|
||||
{
|
||||
int pos = x + z * LevelConstants::CHUNK_CACHE_WIDTH;
|
||||
UnsavedChunkList::iterator prev = unsavedChunkList.begin();
|
||||
for ( ; prev != unsavedChunkList.end(); ++prev)
|
||||
{
|
||||
if ((*prev).pos == pos)
|
||||
{
|
||||
// the chunk has been modified again, so update its time
|
||||
(*prev).addedToList = RakNet::GetTimeMS();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (prev == unsavedChunkList.end())
|
||||
{
|
||||
UnsavedLevelChunk unsaved;
|
||||
unsaved.pos = pos;
|
||||
unsaved.addedToList = RakNet::GetTimeMS();
|
||||
unsaved.chunk = chunk;
|
||||
unsavedChunkList.push_back(unsaved);
|
||||
}
|
||||
chunk->unsaved = false; // not actually saved, but in our working list at least
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
savePendingUnsavedChunks(2);
|
||||
}
|
||||
if (tickCount - lastSavedEntitiesTick > (60 * SharedConstants::TicksPerSecond)) {
|
||||
saveEntities(level, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
void ExternalFileLevelStorage::save(Level* level, LevelChunk* levelChunk)
|
||||
{
|
||||
if (!regionFile)
|
||||
{
|
||||
regionFile = new RegionFile(levelPath);
|
||||
if (!regionFile->open())
|
||||
{
|
||||
delete regionFile;
|
||||
regionFile = NULL;
|
||||
return;
|
||||
}
|
||||
}
|
||||
RegionFile* region = getRegion(levelChunk->x, levelChunk->z);
|
||||
if (!region)
|
||||
return;
|
||||
|
||||
// Write chunk
|
||||
RakNet::BitStream chunkData;
|
||||
|
|
@ -423,29 +414,68 @@ void ExternalFileLevelStorage::save(Level* level, LevelChunk* levelChunk)
|
|||
|
||||
chunkData.Write((const char*)levelChunk->updateMap, LevelConstants::CHUNK_COLUMNS);
|
||||
|
||||
regionFile->writeChunk(levelChunk->x, levelChunk->z, chunkData);
|
||||
// Flags: bit 0 = the terrain decorations (trees, ores, ...) were placed
|
||||
unsigned char flags = levelChunk->terrainPopulated ? 1 : 0;
|
||||
chunkData.Write((const char*)&flags, 1);
|
||||
|
||||
// Write entities
|
||||
// Entities and tile entities that live in this chunk
|
||||
if (!level->isClientSide) {
|
||||
CompoundTag base;
|
||||
ListTag* entityTags = new ListTag();
|
||||
ListTag* tileEntityTags = new ListTag();
|
||||
|
||||
std::vector<Entity*> chunkEntities;
|
||||
levelChunk->collectEntities(chunkEntities);
|
||||
for (unsigned int i = 0; i < chunkEntities.size(); ++i) {
|
||||
Entity* e = chunkEntities[i];
|
||||
if (e->removed || e->isPlayer()) continue;
|
||||
|
||||
CompoundTag* tag = new CompoundTag();
|
||||
if (e->save(tag))
|
||||
entityTags->add(tag);
|
||||
else
|
||||
delete tag;
|
||||
}
|
||||
|
||||
const LevelChunk::TEMap& teMap = levelChunk->getTileEntityMap();
|
||||
for (LevelChunk::TEMapCIterator it = teMap.begin(); it != teMap.end(); ++it) {
|
||||
TileEntity* te = it->second;
|
||||
if (!te || te->isRemoved() || !te->shouldSave()) continue;
|
||||
|
||||
CompoundTag* tag = new CompoundTag();
|
||||
if (te->save(tag))
|
||||
tileEntityTags->add(tag);
|
||||
else
|
||||
delete tag;
|
||||
}
|
||||
|
||||
const bool hasData = entityTags->size() > 0 || tileEntityTags->size() > 0;
|
||||
base.put("Entities", entityTags);
|
||||
base.put("TileEntities", tileEntityTags);
|
||||
|
||||
if (hasData) {
|
||||
RakNet::BitStream stream;
|
||||
RakDataOutput dos(stream);
|
||||
NbtIo::write(&base, &dos);
|
||||
int numBytes = (int)stream.GetNumberOfBytesUsed();
|
||||
chunkData.Write(numBytes);
|
||||
chunkData.Write((const char*)stream.GetData(), numBytes);
|
||||
}
|
||||
base.deleteChildren();
|
||||
}
|
||||
|
||||
region->writeChunk(levelChunk->x & 31, levelChunk->z & 31, chunkData);
|
||||
//LOGI("Saved chunk (%d, %d)\n", levelChunk->x, levelChunk->z);
|
||||
|
||||
}
|
||||
|
||||
LevelChunk* ExternalFileLevelStorage::load(Level* level, int x, int z)
|
||||
{
|
||||
if (!regionFile)
|
||||
{
|
||||
regionFile = new RegionFile(levelPath);
|
||||
if (!regionFile->open())
|
||||
{
|
||||
delete regionFile;
|
||||
regionFile = NULL;
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
RegionFile* region = getRegion(x, z);
|
||||
if (!region)
|
||||
return NULL;
|
||||
|
||||
RakNet::BitStream* chunkData = NULL;
|
||||
if (!regionFile->readChunk(x, z, &chunkData))
|
||||
if (!region->readChunk(x & 31, z & 31, &chunkData))
|
||||
{
|
||||
//LOGI("Failed to read data for %d, %d\n", x, z);
|
||||
return NULL;
|
||||
|
|
@ -463,47 +493,37 @@ LevelChunk* ExternalFileLevelStorage::load(Level* level, int x, int z)
|
|||
chunkData->Read((char*)levelChunk->blockLight.data, LevelConstants::CHUNK_BLOCK_COUNT / 2);
|
||||
}
|
||||
chunkData->Read((char*)levelChunk->updateMap, LevelConstants::CHUNK_COLUMNS);
|
||||
// This will be difficult to maintain.. Storage version could be per chunk
|
||||
// too (but probably better to just read all -> write all, so that all
|
||||
// chunks got same version anyway)
|
||||
//if (loadedStorageVersion >= ChunkVersion_Entity) {
|
||||
// int dictSize;
|
||||
// chunkData->Read(dictSize);
|
||||
|
||||
// RakDataInput dis(*chunkData);
|
||||
// Tag* tmp = Tag::readNamedTag(&dis);
|
||||
// if (tmp && tmp->getId() == Tag::TAG_Compound) {
|
||||
// CompoundTag* tag = (CompoundTag*) tmp;
|
||||
// Chunks written by older versions end here and were always fully decorated
|
||||
bool populated = true;
|
||||
if (chunkData->GetNumberOfUnreadBits() >= 8) {
|
||||
unsigned char flags = 0;
|
||||
chunkData->Read((char*)&flags, 1);
|
||||
populated = (flags & 1) != 0;
|
||||
}
|
||||
|
||||
// delete tmp;
|
||||
// }
|
||||
//}
|
||||
// Optional trailer: the entities and tile entities of the chunk
|
||||
if (!level->isClientSide && chunkData->GetNumberOfUnreadBits() >= 32) {
|
||||
int numBytes = 0;
|
||||
chunkData->Read(numBytes);
|
||||
if (numBytes > 0 && numBytes <= (int)(chunkData->GetNumberOfUnreadBits() >> 3)) {
|
||||
unsigned char* buf = new unsigned char[numBytes];
|
||||
chunkData->Read((char*)buf, numBytes);
|
||||
|
||||
RakNet::BitStream stream(buf, numBytes, false);
|
||||
RakDataInput dis(stream);
|
||||
levelChunk->pendingData = NbtIo::read(&dis);
|
||||
|
||||
delete[] buf;
|
||||
}
|
||||
}
|
||||
|
||||
delete [] chunkData->GetData();
|
||||
delete chunkData;
|
||||
|
||||
//bool dbg = (x == 7 && z == 9);
|
||||
|
||||
//int t = 0;
|
||||
//for (int i = 0; i < LevelConstants::CHUNK_COLUMNS; ++i) {
|
||||
// char bits = levelChunk->updateMap[i];
|
||||
// t += (bits != 0);
|
||||
// int xx = x * 16 + i%16;
|
||||
// int zz = z * 16 + i/16;
|
||||
// if (dbg && xx == 125 && zz == 152) {
|
||||
// LOGI("xz: %d, %d: %d\n", xx, zz, bits);
|
||||
// for (int j = 0; j < 8; ++j) {
|
||||
// if (bits & (1 << j)) {
|
||||
// LOGI("%d - %d\n", j << 4, ((j+1) << 4) - 1);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
//
|
||||
// Convert LevelChunks here if necessary
|
||||
//
|
||||
//LOGI("level version: %d: upd: %d - (%d, %d)\n", loadedStorageVersion, t, x, z);
|
||||
bool changed = false;
|
||||
|
||||
// Loaded level has old Cloth types (one Tile* per color)
|
||||
|
|
@ -511,104 +531,39 @@ LevelChunk* ExternalFileLevelStorage::load(Level* level, int x, int z)
|
|||
changed |= LevelConverters::v1_ClothIdToClothData(levelChunk);
|
||||
|
||||
// Loaded level is newer than our level - replace all unavailable block types
|
||||
//if (loadedStorageVersion > SharedConstants::StorageVersion)
|
||||
changed |= LevelConverters::ReplaceUnavailableBlocks(levelChunk);
|
||||
changed |= LevelConverters::ReplaceUnavailableBlocks(levelChunk);
|
||||
|
||||
levelChunk->recalcHeightmap();
|
||||
levelChunk->unsaved = changed;
|
||||
levelChunk->terrainPopulated = true;
|
||||
levelChunk->terrainPopulated = populated;
|
||||
levelChunk->createdFromSave = true;
|
||||
|
||||
return levelChunk;
|
||||
}
|
||||
|
||||
void ExternalFileLevelStorage::saveEntities( Level* level, LevelChunk* levelChunk )
|
||||
{
|
||||
lastSavedEntitiesTick = tickCount;
|
||||
int count = 0;
|
||||
float st = getTimeS();
|
||||
|
||||
// Version 1: Save ALL Entities for all chunks in one structure
|
||||
EntityList& entities = level->entities;
|
||||
|
||||
ListTag* entityTags = new ListTag();
|
||||
for (unsigned int i = 0; i < entities.size(); ++i) {
|
||||
Entity* e = entities[i];
|
||||
|
||||
CompoundTag* tag = new CompoundTag();
|
||||
if (e->save(tag)) {
|
||||
count++;
|
||||
entityTags->add(tag);
|
||||
} else
|
||||
delete tag;
|
||||
}
|
||||
|
||||
// Version 1: Save ALL TileEntities for all chunks in one structure
|
||||
TileEntityList& tileEntities = level->tileEntities;
|
||||
//TileEntityList keep, dontKeep;
|
||||
//partitionTileEntities
|
||||
|
||||
ListTag* tileEntityTags = new ListTag();
|
||||
for (unsigned int i = 0; i < tileEntities.size(); ++i) {
|
||||
TileEntity* e = tileEntities[i];
|
||||
if (!e->shouldSave()) continue;
|
||||
|
||||
CompoundTag* tag = new CompoundTag();
|
||||
if (e->save(tag)) {
|
||||
count++;
|
||||
tileEntityTags->add(tag);
|
||||
} else
|
||||
delete tag;
|
||||
}
|
||||
|
||||
CompoundTag base;
|
||||
base.put("Entities", entityTags);
|
||||
base.put("TileEntities", tileEntityTags);
|
||||
|
||||
RakNet::BitStream stream;
|
||||
RakDataOutput dos(stream);
|
||||
NbtIo::write(&base, &dos);
|
||||
int numBytes = stream.GetNumberOfBytesUsed();
|
||||
|
||||
FILE* fp = fopen((levelPath + "/entities.dat").c_str(), "wb");
|
||||
if (fp) {
|
||||
int version = 1;
|
||||
fwrite("ENT\0", 1, 4, fp);
|
||||
fwrite(&version, sizeof(int), 1, fp);
|
||||
fwrite(&numBytes, sizeof(int), 1, fp);
|
||||
fwrite(stream.GetData(), 1, numBytes, fp);
|
||||
fclose(fp);
|
||||
}
|
||||
|
||||
base.deleteChildren();
|
||||
|
||||
float tt = getTimeS() - st;
|
||||
LOGI("Time to save %d entities: %f s. Size: %d bytes\n", count, tt, numBytes);
|
||||
}
|
||||
|
||||
// Imports the global entities.dat that older versions of the game wrote.
|
||||
void ExternalFileLevelStorage::loadEntities(Level* level, LevelChunk* chunk) {
|
||||
lastSavedEntitiesTick = tickCount;
|
||||
FILE* fp = fopen((levelPath + "/entities.dat").c_str(), "rb");
|
||||
if (fp) {
|
||||
char header[5];
|
||||
int version, numBytes;
|
||||
fread(header, 1, 4, fp);
|
||||
fread(&version, sizeof(int), 1, fp);
|
||||
fread(&numBytes, sizeof(int), 1, fp);
|
||||
const std::string path = levelPath + "/entities.dat";
|
||||
FILE* fp = fopen(path.c_str(), "rb");
|
||||
if (!fp) return;
|
||||
|
||||
int left = getRemainingFileSize(fp);
|
||||
if (numBytes <= left && numBytes > 0) {
|
||||
unsigned char* buf = new unsigned char[numBytes];
|
||||
char header[5] = {0};
|
||||
int version = 0, numBytes = 0;
|
||||
fread(header, 1, 4, fp);
|
||||
fread(&version, sizeof(int), 1, fp);
|
||||
fread(&numBytes, sizeof(int), 1, fp);
|
||||
|
||||
fread(buf, 1, numBytes, fp);
|
||||
int left = getRemainingFileSize(fp);
|
||||
if (numBytes <= left && numBytes > 0) {
|
||||
unsigned char* buf = new unsigned char[numBytes];
|
||||
|
||||
RakNet::BitStream stream(buf, numBytes, false);
|
||||
RakDataInput dis(stream);
|
||||
fread(buf, 1, numBytes, fp);
|
||||
|
||||
CompoundTag* tag = NbtIo::read(&dis);
|
||||
//
|
||||
// Read Entity:es
|
||||
//
|
||||
RakNet::BitStream stream(buf, numBytes, false);
|
||||
RakDataInput dis(stream);
|
||||
|
||||
CompoundTag* tag = NbtIo::read(&dis);
|
||||
if (tag) {
|
||||
if (tag->contains("Entities", Tag::TAG_List)) {
|
||||
ListTag* entityTags = tag->getList("Entities");
|
||||
for (int i = 0; i < entityTags->size(); ++i) {
|
||||
|
|
@ -623,9 +578,6 @@ void ExternalFileLevelStorage::loadEntities(Level* level, LevelChunk* chunk) {
|
|||
}
|
||||
}
|
||||
}
|
||||
//
|
||||
// Read TileEntity:s
|
||||
//
|
||||
if (tag->contains("TileEntities", Tag::TAG_List)) {
|
||||
ListTag* tileEntityTags = tag->getList("TileEntities");
|
||||
for (int i = 0; i < tileEntityTags->size(); ++i) {
|
||||
|
|
@ -636,67 +588,35 @@ void ExternalFileLevelStorage::loadEntities(Level* level, LevelChunk* chunk) {
|
|||
}
|
||||
CompoundTag* et = (CompoundTag*)_et;
|
||||
if (TileEntity* e = TileEntity::loadStatic(et)) {
|
||||
|
||||
LevelChunk* chunk = level->getChunkAt(e->x, e->z);
|
||||
if (chunk && !chunk->hasTileEntityAt(e)) {
|
||||
LOGI("Adding TileEntity %d to %d, %d, %d\n", e->type, e->x, e->y, e->z);
|
||||
chunk->addTileEntity(e);
|
||||
LevelChunk* lc = level->getChunkAt(e->x, e->z);
|
||||
if (lc && !lc->hasTileEntityAt(e)) {
|
||||
lc->addTileEntity(e);
|
||||
} else {
|
||||
if (!chunk)
|
||||
LOGE("Couldn't find chunk at %d, %d to add %d\n", e->x, e->z, e->type);
|
||||
else
|
||||
LOGE("Already have TileEntity at %d, %d to add %d\n", e->x, e->z, e->type);
|
||||
delete e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tag->deleteChildren();
|
||||
delete tag;
|
||||
|
||||
delete[] buf;
|
||||
}
|
||||
LOGI("header: %s, version: %d, bytes: %d (remaining: %d)\n", header, version, numBytes, left);
|
||||
|
||||
//fread(stream.GetData(), 1, numBytes, fp);
|
||||
fclose(fp);
|
||||
delete[] buf;
|
||||
}
|
||||
fclose(fp);
|
||||
|
||||
// Entities are stored per chunk from now on.
|
||||
const std::string migrated = path + ".migrated";
|
||||
remove(migrated.c_str());
|
||||
rename(path.c_str(), migrated.c_str());
|
||||
}
|
||||
|
||||
void ExternalFileLevelStorage::saveGame(Level* level) {
|
||||
saveEntities(level, NULL);
|
||||
}
|
||||
|
||||
int ExternalFileLevelStorage::savePendingUnsavedChunks( int maxCount ) {
|
||||
if (maxCount < 0)
|
||||
maxCount = unsavedChunkList.size();
|
||||
|
||||
int count = 0;
|
||||
while (++count <= maxCount && !unsavedChunkList.empty()) {
|
||||
|
||||
UnsavedChunkList::iterator it = unsavedChunkList.begin();
|
||||
UnsavedChunkList::iterator remove = unsavedChunkList.begin();
|
||||
UnsavedLevelChunk* oldest = &(*it);
|
||||
|
||||
for ( ; it != unsavedChunkList.end(); ++it) {
|
||||
if ((*it).addedToList < oldest->addedToList) {
|
||||
oldest = &(*it);
|
||||
remove = it;
|
||||
}
|
||||
}
|
||||
LevelChunk* chunk = oldest->chunk;
|
||||
unsavedChunkList.erase(remove);
|
||||
|
||||
save(level, chunk);
|
||||
}
|
||||
return count;
|
||||
if (level && level->getChunkSource())
|
||||
level->getChunkSource()->saveAll(true);
|
||||
}
|
||||
|
||||
void ExternalFileLevelStorage::saveAll( Level* level, std::vector<LevelChunk*>& levelChunks ) {
|
||||
ChunkStorage::saveAll(level, levelChunks);
|
||||
int numChunks = savePendingUnsavedChunks(-1);
|
||||
LOGI("Saving %d additional chunks.\n", numChunks);
|
||||
}
|
||||
|
||||
#endif /*DEMO_MODE*/
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
|
||||
#include <vector>
|
||||
#include <list>
|
||||
#include <map>
|
||||
|
||||
//#include "com/mojang/nbt/CompoundTag.h"
|
||||
#include "LevelStorage.h"
|
||||
|
|
@ -16,16 +17,6 @@ class Player;
|
|||
class Dimension;
|
||||
class RegionFile;
|
||||
|
||||
|
||||
typedef struct UnsavedLevelChunk
|
||||
{
|
||||
int pos;
|
||||
RakNet::TimeMS addedToList;
|
||||
LevelChunk* chunk;
|
||||
} UnsavedLevelChunk;
|
||||
|
||||
typedef std::list<UnsavedLevelChunk> UnsavedChunkList;
|
||||
|
||||
/*public*/
|
||||
class ExternalFileLevelStorage:
|
||||
public LevelStorage,
|
||||
|
|
@ -54,16 +45,15 @@ public:
|
|||
static bool writeLevelData(const std::string& datFileName, LevelData& dest, const std::vector<Player*>* players);
|
||||
static void saveLevelData(const std::string& directory, LevelData& levelData, std::vector<Player*>* players);
|
||||
|
||||
int savePendingUnsavedChunks(int maxCount);
|
||||
|
||||
//
|
||||
// ChunkStorage methods
|
||||
//
|
||||
virtual LevelChunk* load(Level* level, int x, int z);
|
||||
void save(Level* level, LevelChunk* levelChunk);
|
||||
// @note, loadEntities and saveEntities dont use second parameter
|
||||
// Entities and tile entities are saved together with their chunk. This
|
||||
// only imports the old global "entities.dat" of worlds saved by older
|
||||
// versions (once).
|
||||
void loadEntities(Level* level, LevelChunk* levelChunk);
|
||||
void saveEntities(Level* level, LevelChunk* levelChunk);
|
||||
void saveGame(Level* level);
|
||||
void saveAll(Level* level, std::vector<LevelChunk*>& levelChunks);
|
||||
|
||||
|
|
@ -83,17 +73,20 @@ public:
|
|||
virtual void tick();
|
||||
virtual void flush() {}
|
||||
private:
|
||||
RegionFile* getRegion(int chunkX, int chunkZ);
|
||||
void closeRegions();
|
||||
|
||||
std::string levelId;
|
||||
std::string levelPath;
|
||||
LevelData* loadedLevelData;
|
||||
RegionFile* regionFile;
|
||||
RegionFile* entitiesFile;
|
||||
|
||||
// Open region files, least recently used first
|
||||
std::list<long long> regionOrder;
|
||||
std::map<long long, RegionFile*> regions;
|
||||
|
||||
Level* level;
|
||||
int tickCount;
|
||||
int loadedStorageVersion;
|
||||
UnsavedChunkList unsavedChunkList;
|
||||
int lastSavedEntitiesTick;
|
||||
};
|
||||
|
||||
#endif /*NET_MINECRAFT_WORLD_LEVEL_STORAGE__ExternalFileLevelStorage_H__*/
|
||||
|
|
|
|||
|
|
@ -13,12 +13,27 @@ static void logAssert(int actual, int expected) {
|
|||
}
|
||||
}
|
||||
|
||||
RegionFile::RegionFile(const std::string& basePath)
|
||||
/*static*/
|
||||
std::string RegionFile::fileNameFor(const std::string& basePath, int regionX, int regionZ)
|
||||
{
|
||||
std::string name = basePath;
|
||||
name += "/";
|
||||
if (regionX == 0 && regionZ == 0) {
|
||||
name += REGION_DAT_NAME;
|
||||
} else {
|
||||
name += "r.";
|
||||
name += std::to_string(regionX);
|
||||
name += ".";
|
||||
name += std::to_string(regionZ);
|
||||
name += ".dat";
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
RegionFile::RegionFile(const std::string& basePath, int regionX, int regionZ)
|
||||
: file(NULL)
|
||||
{
|
||||
filename = basePath;
|
||||
filename += "/";
|
||||
filename += REGION_DAT_NAME;
|
||||
filename = fileNameFor(basePath, regionX, regionZ);
|
||||
|
||||
offsets = new int[SECTOR_INTS];
|
||||
|
||||
|
|
@ -96,6 +111,7 @@ void RegionFile::close()
|
|||
|
||||
bool RegionFile::readChunk(int x, int z, RakNet::BitStream** destChunkData)
|
||||
{
|
||||
if (!file) return false;
|
||||
int offset = offsets[x + z * SECTOR_COLS];
|
||||
|
||||
if (offset == 0)
|
||||
|
|
@ -127,6 +143,7 @@ bool RegionFile::readChunk(int x, int z, RakNet::BitStream** destChunkData)
|
|||
|
||||
bool RegionFile::writeChunk(int x, int z, RakNet::BitStream& chunkData)
|
||||
{
|
||||
if (!file) return false;
|
||||
int size = chunkData.GetNumberOfBytesUsed() + sizeof(int);
|
||||
|
||||
int offset = offsets[x + z * SECTOR_COLS];
|
||||
|
|
|
|||
|
|
@ -1,31 +1,38 @@
|
|||
#ifndef NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__
|
||||
#define NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include "../../../raknet/BitStream.h"
|
||||
|
||||
typedef std::map<int, bool> FreeSectorMap;
|
||||
|
||||
class RegionFile
|
||||
{
|
||||
public:
|
||||
RegionFile(const std::string& basePath);
|
||||
virtual ~RegionFile();
|
||||
|
||||
bool open();
|
||||
bool readChunk(int x, int z, RakNet::BitStream** destChunkData);
|
||||
bool writeChunk(int x, int z, RakNet::BitStream& chunkData);
|
||||
private:
|
||||
bool write(int sector, RakNet::BitStream& chunkData);
|
||||
void close();
|
||||
|
||||
FILE* file;
|
||||
std::string filename;
|
||||
int* offsets;
|
||||
int* emptyChunk;
|
||||
FreeSectorMap sectorFree;
|
||||
};
|
||||
|
||||
|
||||
#endif /*NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__*/
|
||||
#ifndef NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__
|
||||
#define NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include "../../../raknet/BitStream.h"
|
||||
|
||||
typedef std::map<int, bool> FreeSectorMap;
|
||||
|
||||
// One region holds the 32x32 chunks with (x >> 5, z >> 5) == (regionX, regionZ).
|
||||
// Region (0, 0) lives in the legacy "chunks.dat" so worlds created by the old
|
||||
// fixed-size versions keep loading.
|
||||
class RegionFile
|
||||
{
|
||||
public:
|
||||
RegionFile(const std::string& basePath, int regionX, int regionZ);
|
||||
virtual ~RegionFile();
|
||||
|
||||
bool open();
|
||||
void close();
|
||||
|
||||
// x and z are chunk coordinates local to the region (0..31)
|
||||
bool readChunk(int x, int z, RakNet::BitStream** destChunkData);
|
||||
bool writeChunk(int x, int z, RakNet::BitStream& chunkData);
|
||||
|
||||
static std::string fileNameFor(const std::string& basePath, int regionX, int regionZ);
|
||||
private:
|
||||
bool write(int sector, RakNet::BitStream& chunkData);
|
||||
|
||||
FILE* file;
|
||||
std::string filename;
|
||||
int* offsets;
|
||||
int* emptyChunk;
|
||||
FreeSectorMap sectorFree;
|
||||
};
|
||||
|
||||
|
||||
#endif /*NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__*/
|
||||
|
|
|
|||
|
|
@ -512,16 +512,7 @@ float Tile::getBrightness( LevelSource* level, int x, int y, int z )
|
|||
bool Tile::shouldRenderFace( LevelSource* level, int x, int y, int z, int face )
|
||||
{
|
||||
if (face == 0 && y == -1) return false;
|
||||
// For fixed size worlds //@todo: external constants rather than magic numbers
|
||||
// @fixme @ahtung temp fix
|
||||
|
||||
auto xz = LevelConstants::CHUNK_CACHE_WIDTH == 16 ? 256 :
|
||||
LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH / (LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH / 256 / 2);
|
||||
|
||||
if (face == 2 && z == -1) return false;
|
||||
if (face == 3 && z == xz) return false;
|
||||
if (face == 4 && x == -1) return false;
|
||||
if (face == 5 && x == xz) return false;
|
||||
// The world is infinite, there is no edge whose outer faces could be skipped
|
||||
// Common
|
||||
if (face == 0 && yy0 > 0) return true;
|
||||
if (face == 1 && yy1 < 1) return true;
|
||||
|
|
|
|||
|
|
@ -130,7 +130,7 @@ Vec3 NetherReactorTileEntity::getSpawnPosition( float minDistance, float varible
|
|||
void NetherReactorTileEntity::spawnEnemy() {
|
||||
Mob* mob = MobFactory::CreateMob(MobTypes::PigZombie, level);
|
||||
Vec3 enemyPosition = getSpawnPosition(3, 4, -1);
|
||||
while(enemyPosition.x < 0 || enemyPosition.z < 0 || enemyPosition.x >= LevelConstants::LEVEL_WIDTH || enemyPosition.z >= LevelConstants::LEVEL_DEPTH) {
|
||||
while(enemyPosition.x <= -LevelConstants::LEVEL_WIDTH || enemyPosition.z <= -LevelConstants::LEVEL_DEPTH || enemyPosition.x >= LevelConstants::LEVEL_WIDTH || enemyPosition.z >= LevelConstants::LEVEL_DEPTH) {
|
||||
enemyPosition = getSpawnPosition(3, 4, -1);
|
||||
}
|
||||
MobSpawner::addMob(level, mob, enemyPosition.x, enemyPosition.y, enemyPosition.z, 0, 0, true);
|
||||
|
|
@ -140,7 +140,7 @@ void NetherReactorTileEntity::spawnEnemy() {
|
|||
|
||||
void NetherReactorTileEntity::spawnItem() {
|
||||
Vec3 itemPosition= getSpawnPosition(3, 4, -1);
|
||||
while(itemPosition.x < 0 || itemPosition.z < 0 || itemPosition.x >= LevelConstants::LEVEL_WIDTH || itemPosition.z >= LevelConstants::LEVEL_DEPTH) {
|
||||
while(itemPosition.x <= -LevelConstants::LEVEL_WIDTH || itemPosition.z <= -LevelConstants::LEVEL_DEPTH || itemPosition.x >= LevelConstants::LEVEL_WIDTH || itemPosition.z >= LevelConstants::LEVEL_DEPTH) {
|
||||
itemPosition = getSpawnPosition(3, 4, -1);
|
||||
}
|
||||
ItemEntity* item = new ItemEntity(level, itemPosition.x, itemPosition.y, itemPosition.z, getSpawnItem());
|
||||
|
|
|
|||
23
tools/convert-music.ps1
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
<#
|
||||
Converts FLAC/MP3/WAV files to the OGG Vorbis tracks the game plays from data\music.
|
||||
|
||||
.\tools\convert-music.ps1 -Source "F:\Music\Minecraft - Volume Alpha" -Prefix alpha
|
||||
.\tools\convert-music.ps1 -Source "F:\Music\Minecraft - Volume Beta" -Prefix beta
|
||||
|
||||
Needs ffmpeg (with libvorbis) in PATH. Every .ogg in data\music is shuffled by the
|
||||
in-game music player, volume is the "Music" slider in the options.
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory)] [string]$Source,
|
||||
[string]$Prefix = 'track',
|
||||
[string]$Out = (Join-Path $PSScriptRoot '..\data\music')
|
||||
)
|
||||
New-Item -ItemType Directory -Force $Out | Out-Null
|
||||
Get-ChildItem -LiteralPath $Source -Include *.flac, *.mp3, *.wav, *.m4a -Recurse | ForEach-Object {
|
||||
$name = ($_.BaseName -replace '[^\w\- ]', '') -replace '\s+', '_'
|
||||
$dst = Join-Path $Out "${Prefix}_$name.ogg"
|
||||
if (-not (Test-Path $dst)) {
|
||||
& ffmpeg -loglevel error -y -i $_.FullName -vn -map_metadata -1 -acodec libvorbis -aq 4 -ar 44100 -ac 2 $dst
|
||||
Write-Host $dst
|
||||
}
|
||||
}
|
||||