From 110cb2a896553b60b32153c3d021f72e42f72aa6 Mon Sep 17 00:00:00 2001 From: Kirill Sokolov Date: Tue, 20 Oct 2026 21:08:09 +0300 Subject: [PATCH] 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 --- .gitignore | 7 + CMakeLists.txt | 29 +- README.md | 19 + cmake/LuaJIT.cmake | 70 + data/images/skins/blonde.png | Bin 0 -> 1668 bytes data/images/skins/green.png | Bin 0 -> 1675 bytes data/images/skins/ninja.png | Bin 0 -> 1633 bytes data/images/skins/orange.png | Bin 0 -> 1663 bytes data/images/skins/pink.png | Bin 0 -> 1718 bytes data/images/skins/purple.png | Bin 0 -> 1660 bytes data/images/skins/red.png | Bin 0 -> 1623 bytes data/images/skins/snow.png | Bin 0 -> 1691 bytes data/images/skins/steve.png | Bin 0 -> 1651 bytes data/images/skins/yellow.png | Bin 0 -> 1680 bytes lua/prelude.lua | 404 +++++ mods/README.md | 120 ++ mods/hello.lua | 22 + mods/worldedit/lib.lua | 450 +++++ mods/worldedit/main.lua | 1574 +++++++++++++++++ package-windows.ps1 | 76 + src/SharedConstants.h | 4 +- src/client/Minecraft.cpp | 43 +- src/client/gamemode/GameMode.cpp | 6 + src/client/gui/screens/ConsoleScreen.cpp | 72 + src/client/gui/screens/ConsoleScreen.h | 1 + src/client/player/LocalPlayer.cpp | 11 +- src/client/renderer/Chunk.cpp | 8 + src/client/renderer/LevelRenderer.cpp | 11 +- src/client/sound/MusicPlayer.cpp | 228 +++ src/client/sound/MusicPlayer.h | 48 + src/client/sound/SoundEngine.cpp | 3 + src/client/sound/SoundEngine.h | 8 + src/commands/CommandManager.cpp | 17 +- src/lua/LuaEngine.cpp | 628 +++++++ src/lua/LuaEngine.h | 50 + src/main_dedicated.cpp | 24 +- src/network/ClientSideNetworkHandler.cpp | 259 +-- src/network/ClientSideNetworkHandler.h | 24 +- src/network/NetEventCallback.h | 2 + src/network/Packet.cpp | 3 + src/network/Packet.h | 2 + src/network/ServerSideNetworkHandler.cpp | 64 +- src/network/ServerSideNetworkHandler.h | 1 + src/network/command/CommandServer.cpp | 4 - src/network/packet/PacketInclude.h | 1 + src/network/packet/SetSkinPacket.h | 38 + src/world/entity/Entity.cpp | 6 +- src/world/entity/player/Player.h | 1 + src/world/level/ChunkPos.h | 2 +- src/world/level/Level.cpp | 46 +- src/world/level/Level.h | 1 + src/world/level/LevelConstants.cpp | 12 +- src/world/level/LevelConstants.h | 36 +- src/world/level/MobSpawner.cpp | 18 +- src/world/level/chunk/ChunkCache.cpp | 380 ++++ src/world/level/chunk/ChunkCache.h | 357 +--- src/world/level/chunk/ChunkSource.h | 102 +- src/world/level/chunk/LevelChunk.cpp | 28 +- src/world/level/chunk/LevelChunk.h | 11 + .../level/levelgen/RandomLevelSource.cpp | 6 +- src/world/level/levelgen/RandomLevelSource.h | 18 +- .../storage/ExternalFileLevelStorage.cpp | 392 ++-- .../level/storage/ExternalFileLevelStorage.h | 29 +- src/world/level/storage/RegionFile.cpp | 25 +- src/world/level/storage/RegionFile.h | 69 +- src/world/level/tile/Tile.cpp | 11 +- .../tile/entity/NetherReactorTileEntity.cpp | 4 +- tools/convert-music.ps1 | 23 + 68 files changed, 5064 insertions(+), 844 deletions(-) create mode 100644 cmake/LuaJIT.cmake create mode 100644 data/images/skins/blonde.png create mode 100644 data/images/skins/green.png create mode 100644 data/images/skins/ninja.png create mode 100644 data/images/skins/orange.png create mode 100644 data/images/skins/pink.png create mode 100644 data/images/skins/purple.png create mode 100644 data/images/skins/red.png create mode 100644 data/images/skins/snow.png create mode 100644 data/images/skins/steve.png create mode 100644 data/images/skins/yellow.png create mode 100644 lua/prelude.lua create mode 100644 mods/README.md create mode 100644 mods/hello.lua create mode 100644 mods/worldedit/lib.lua create mode 100644 mods/worldedit/main.lua create mode 100644 package-windows.ps1 create mode 100644 src/client/sound/MusicPlayer.cpp create mode 100644 src/client/sound/MusicPlayer.h create mode 100644 src/lua/LuaEngine.cpp create mode 100644 src/lua/LuaEngine.h create mode 100644 src/network/packet/SetSkinPacket.h create mode 100644 src/world/level/chunk/ChunkCache.cpp create mode 100644 tools/convert-music.ps1 diff --git a/.gitignore b/.gitignore index 5465697..028faf9 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/CMakeLists.txt b/CMakeLists.txt index b978db0..df8b711 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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" "$/lua" + COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/mods" "$/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" $/data + COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/lua" $/lua + COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/mods" $/mods ) else() add_custom_command( diff --git a/README.md b/README.md index 094ec25..9b2fc0c 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,25 @@ This project aims to preserve and improve this early version of Minecraft PE.

+ +# This fork: infinite world, Lua mods, WorldEdit, skins, music + +- **Infinite world** - chunks are generated, saved (region files `r...dat`, old `chunks.dat` worlds still load) and unloaded around the players. Dedicated server: `view-distance=` 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 ` in the chat console; other players see the skin you pick. Drop a `.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 diff --git a/cmake/LuaJIT.cmake b/cmake/LuaJIT.cmake new file mode 100644 index 0000000..5d1f4c0 --- /dev/null +++ b/cmake/LuaJIT.cmake @@ -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") + + # /VC/Tools/MSVC//bin/Hostx64/x64/cl.exe -> /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) diff --git a/data/images/skins/blonde.png b/data/images/skins/blonde.png new file mode 100644 index 0000000000000000000000000000000000000000..aef7319c9ee7fb483c93dd0e1bd677e08c6b7ba5 GIT binary patch literal 1668 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 literal 0 HcmV?d00001 diff --git a/data/images/skins/orange.png b/data/images/skins/orange.png new file mode 100644 index 0000000000000000000000000000000000000000..8f9ab49c158b9f679c67e6e99da6d0415389ac36 GIT binary patch literal 1663 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�{z%tFgK5tF0MUC6h&*hV&6kYxK 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 VbFVHZo!S5Z002ovPDHLkV1g#=8fyRm literal 0 HcmV?d00001 diff --git a/data/images/skins/snow.png b/data/images/skins/snow.png new file mode 100644 index 0000000000000000000000000000000000000000..1a5b305daf98404888300151dc733b1ef44d431f GIT binary patch literal 1691 zcmV;M24wk(P)$Eu-oF)(-0xqR3H3<}wLPgQ3hxSnD zsWc}S(?g(#-U2>^5(kn?YFv7#+R7F+i&~>~jEiiUU2COiwc45Y=Jl|e(adUhwNk7| z{({h(`TgFT_x=5T@B4mhum#4C9Mk}w@8j4u;TXVQGx`4MulAh(&c`#xR^Ql5h<=jFr zX;**#9qux=tbnN8gMc6i0B~%ZwChGk;z`Dq0f>_nLLimebQGRs^u@#v0;Fo4_kljM z{@}st&Uf_%qAv}QN-<#DcuLaneVVHV*-UckD@P7?n7RKopsxU!!l1FP1pw}##$VS1 z;E52sZZM7=9@GGV2E#BA1`N0szG_|H0*MR^EJM-Alz2yDwlYcSVu1>4j#nvy_+ z)*7*X`wP*sck3hW*6MrOCnPFBYmI4IG@2421S!X4&1>yX>VS00CgZp$1l1J}r4<8~ z$(pBV$N*EAC@D96B%RJky@HTRB7}i!TCEH!i3U=R zh2uE<`i&nF_y*O*74AQ*a_9a-0$)-4Y?+^)dlAQRNI4c7P)cG76W6p5!aypy@B4_> zHE0C*fyDCze5rZ!rRSM^`7~+AWYBea?N`5N?De-vc^*#}zC`ZakNL?TK42(cB<+|? zzI>WDUwR&2>ed>81Y?72^s#-|M?@ls76gIDaU6c|ji<>CWm)#u$PWxr7*F9EN8Vnz>$!D{eZkoUS z=TrXi-#hq$#4;@ctrLBO3Ut&*?1unYKYHO=0P@)^m0Argn@B0K90!fZo%sg@T9Y3h z0-)*p47e#)8j7axqtRH7gKgU=+2mVC5A)*KAp#|-)M@}MuK4`<-?yWWx`UeU9(#u2 z12(_B_s=h!bR3(aueDBeHOG%1PuOQ?XM1K$Yps9r>eoBke)rK$E?v6Rb3>DplRej$ zQtGhxP)hOhbKm5CtxdyQSGfZhCUpp<$nnGa!HxpGAV%+1X)Ha5oj^XC%|SFc`;Y(TEhae_=H6FtYzH^BAl*E{-~rioH& zll|=3vq^%6(epftko-1PE_3SCDGG%GnM{U>cRx&!&*gIDa=CasT*uetsTk5e&zj5I=H{9zELOt~bz^2#$@7MLJL_l@hjmKHrf@ zu~;OR%SF#|QgMISIPdK+O_SL_{U&<;`^O%YW6vdg=4Nk^8FT=c{VP=d@?JlbB6O^P zQmK?6+DjwiWb*lZ!WJi1C=@pNgyV&Ug-z>r3kpDGd7~}Q3_2{WdR=|DLdOaS#Vw9d zBid~@Zrs?E(PFU(w1|bo+Yt{$p-^C9VIgt87Zw&M7K<#cdQpbk5f4PC_xYi%`vMDg zE`R`|qoW%e zz6`*`#6(ZW(C^x{Yl-(4E?fXM$i&62P$)##S+^|5{fot7LPV8PJ;~*V(o||2&!KN+ zx!$sMIU;dH70`{~ty{NxE>NvjsZ=UtG8yLP<~VcaOl0$YAK&*Wl}emEc`|w*YDOlL zA(zWVf*aS1>FMc?S`@9ZPBN^FUKP>{kM*}ex1%yXKF;*?G$SJ;RIAlZz9G?>nHfe# lMiO0Pi1zG;<97RY@qfwU^QBBiH?jZ#002ovPDHLkV1f+lNU{I` literal 0 HcmV?d00001 diff --git a/data/images/skins/steve.png b/data/images/skins/steve.png new file mode 100644 index 0000000000000000000000000000000000000000..555fb1175d1c446100d6f3a977f72aadb5255b23 GIT binary patch literal 1651 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 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 diff --git a/mods/README.md b/mods/README.md new file mode 100644 index 0000000..a083123 --- /dev/null +++ b/mods/README.md @@ -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//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`). diff --git a/mods/hello.lua b/mods/hello.lua new file mode 100644 index 0000000..1f4a9bb --- /dev/null +++ b/mods/hello.lua @@ -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 ", usage = "/tp ", 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 (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) diff --git a/mods/worldedit/lib.lua b/mods/worldedit/lib.lua new file mode 100644 index 0000000..3d6ecce --- /dev/null +++ b/mods/worldedit/lib.lua @@ -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 diff --git a/mods/worldedit/main.lua b/mods/worldedit/main.lua new file mode 100644 index 0000000..6d8ca1d --- /dev/null +++ b/mods/worldedit/main.lua @@ -0,0 +1,1574 @@ +-- WorldEdit for MinecraftPE, written against the Lua mod API (see ../README.md). +-- Command names, arguments, flags and behaviour follow EngineHub's WorldEdit +-- (https://worldedit.enginehub.org/en/latest/commands/). Everything is typed +-- with the usual double slash: "//wand", "//set stone", "/undo", ... + +local W = require("lib") + +local floor, ceil, abs, min, max = math.floor, math.ceil, math.abs, math.min, math.max +local get_block = mc.world.get_block + +local WAND = mc.item.wooden_axe +local NAVWAND = mc.item.compass +local PICKAXES = { [270] = true, [274] = true, [257] = true, [278] = true, [285] = true } + +-- ----------------------------------------------------------------- helpers +-- Names starting with "/" are typed with two slashes (//set). Commands that WorldEdit also +-- offers with a single slash (/undo, /tool, ...) are registered under both spellings. +local SINGLE = {} +for name in ("unstuck ! ascend asc descend desc ceil thru jumpto j up toggleeditwand undo redo clearhistory " + .. "tool none mask material mat range superpickaxe pickaxe sp brush br fixlava fixwater removeabove " + .. "removebelow removenear replacenear snow thaw green extinguish ex ext butcher toggleplace schematic " + .. "schem clearclipboard ;"):gmatch("%S+") do SINGLE[name] = true end + +local function reg(names, desc, fn) + if type(names) == "string" then names = { names } end + for _, n in ipairs(names) do + mc.command(n, { description = desc, op = true }, fn) + local bare = n:match("^/(.+)$") + if bare and SINGLE[bare] then + mc.command(bare, { description = desc, op = true }, fn) + end + end +end + +local function fmt(p) return string.format("(%d, %d, %d)", p[1], p[2], p[3]) end + +local function say(ctx, ...) ctx.player:say(...) end + +local function selection(ctx) + local s = W.session(ctx.player) + local r = W.region(s) + if not r then + say(ctx, "Make a region selection first (//wand, //pos1, //pos2).") + return s, nil + end + return s, r +end + +local function describe_pos(s, which, p) + local msg = string.format("Position %d set to %s", which, fmt(p)) + local r = W.region(s) + if r then msg = msg .. " (" .. W.volume(r) .. " blocks)" end + return msg .. "." +end + +local function set_pos(player, which, p) + local s = W.session(player) + s[which == 1 and "pos1" or "pos2"] = p + player:say(describe_pos(s, which, p)) +end + +--- Runs `fn(edit)` as one undoable edit and reports the number of changed blocks. +local function edit_session(ctx, fn, noun) + local s = W.session(ctx.player) + local edit = W.new_edit(s) + local ok, err = pcall(fn, edit, s) + local n = edit:commit() + if not ok then + say(ctx, "Error: " .. tostring(err)) + return n + end + if edit.overflow then say(ctx, "Block change limit reached (" .. s.limit .. "), use //limit.") end + say(ctx, n .. " " .. (noun or "blocks") .. " changed.") + return n +end + +local function pattern_or_err(ctx, text) + local p, err = W.pattern(text) + if not p then say(ctx, err) end + return p +end + +local function num(text, default) + local n = tonumber(text) + return n or default +end + +local function player_block(ctx) return ctx.player:block_pos() end + +local function radii(text) + local list = {} + for part in tostring(text):gmatch("[^,]+") do list[#list + 1] = tonumber(part) end + return list +end + +-- ----------------------------------------------------------------- help +local help_lines = { + "Navigation: /unstuck /ascend /descend /ceil /thru /jumpto /up", + "Selection: //wand //pos1 //pos2 //hpos1 //hpos2 //chunk //sel //expand //contract //shift //outset //inset //size //count //distr", + "Region: //set //replace //overlay //center //naturalize //walls //faces //smooth //move //stack //hollow //line", + "Generation: //sphere //hsphere //cyl //hcyl //cone //pyramid //hpyramid", + "Clipboard: //copy //cut //paste //rotate //flip /clearclipboard /schematic", + "History: /undo /redo /clearhistory", + "Tools: /tool /brush /mask /material /range /size // (super pickaxe)", + "Utility: //fill //fillr //drain /fixlava /fixwater /removeabove /removebelow /removenear /replacenear", + " /snow /thaw /green /extinguish /butcher //limit /toggleplace /we", +} +reg({ "/help" }, "Shows the WorldEdit commands", function(ctx) + for _, l in ipairs(help_lines) do say(ctx, l) end +end) + +reg({ "we", "worldedit" }, "WorldEdit information", function(ctx) + local sub = ctx.args[1] + if sub == "version" or sub == "ver" or not sub then + say(ctx, "WorldEdit (MinecraftPE Lua port) 1.0, based on the EngineHub WorldEdit command set.") + else + say(ctx, "Usage: /we version") + end +end) + +reg("/limit", "Sets the block change limit", function(ctx) + local s = W.session(ctx.player) + if ctx.args[1] then s.limit = tonumber(ctx.args[1]) or s.limit end + say(ctx, "Block change limit: " .. (s.limit < 0 and "unlimited" or s.limit)) +end) + +-- ------------------------------------------------------------- navigation +local function free(x, y, z) + local id = get_block(x, y, z) + return id == 0 or id == 50 or id == 31 or id == 37 or id == 38 or id == 78 or id == 6 +end + +local function standable(x, y, z) + return not free(x, y - 1, z) and not W.is_liquid(get_block(x, y - 1, z)) and free(x, y, z) and free(x, y + 1, z) +end + +reg({ "/unstuck", "/!" }, "Escape from being stuck inside a block", function(ctx) + local x, y, z = player_block(ctx) + for dy = 0, 127 - y do + if free(x, y + dy, z) and free(x, y + dy + 1, z) then + ctx.player:teleport(x + 0.5, y + dy, z + 0.5) + return "There you go!" + end + end + return "Nowhere to go." +end) + +local function levels_arg(ctx) return max(1, floor(num(ctx.args[1], 1))) end + +reg({ "/ascend", "/asc" }, "Go up a floor", function(ctx) + local x, y, z = player_block(ctx) + local levels, found = levels_arg(ctx), 0 + local cy, last = y, nil + for yy = y + 1, 126 do + if standable(x, yy, z) and not standable(x, yy - 1, z) and (not free(x, yy - 1, z) or yy > cy + 1) then + found = found + 1 + last = yy + if found >= levels then break end + end + end + if not last then return "No free spot above you found." end + ctx.player:teleport(x + 0.5, last, z + 0.5) + return "Ascended " .. found .. " level" .. (found > 1 and "s" or "") .. "." +end) + +reg({ "/descend", "/desc" }, "Go down a floor", function(ctx) + local x, y, z = player_block(ctx) + local levels, found, last = levels_arg(ctx), 0, nil + for yy = y - 1, 1, -1 do + if standable(x, yy, z) then + found = found + 1 + last = yy + if found >= levels then break end + end + end + if not last then return "No free spot below you found." end + ctx.player:teleport(x + 0.5, last, z + 0.5) + return "Descended " .. found .. " level" .. (found > 1 and "s" or "") .. "." +end) + +reg("/ceil", "Go to the ceiling", function(ctx) + local flags, pos = W.parse(ctx.args) + local clearance = max(0, floor(num(pos[1], 0))) + local x, y, z = player_block(ctx) + for yy = 126, y + 1, -1 do + if not free(x, yy + 1, z) and free(x, yy, z) and free(x, yy - 1, z) then + local ty = yy - 1 - clearance + if ty > y then + ctx.player:teleport(x + 0.5, ty, z + 0.5) + if flags.g then mc.world.set_block(x, ty - 1, z, 20, 0) end + return "Whoosh!" + end + end + end + return "No free spot above you found." +end) + +reg("/thru", "Pass through walls", function(ctx) + local x, y, z = ctx.player:pos() + local dir, dx, dz = ctx.player:facing() + local yaw, pitch = ctx.player:look() + local vy = pitch > 50 and -1 or (pitch < -50 and 1 or 0) + if vy ~= 0 then dx, dz = 0, 0 end + local bx, by, bz = floor(x), floor(y), floor(z) + local inWall = false + for i = 1, 100 do + local cx, cy, cz = bx + dx * i, by + vy * i, bz + dz * i + if not free(cx, cy, cz) or not free(cx, cy + 1, cz) then inWall = true + elseif inWall and free(cx, cy, cz) and free(cx, cy + 1, cz) then + ctx.player:teleport(cx + 0.5, cy, cz + 0.5) + return "Whoosh!" + end + end + return "No free spot ahead of you found." +end) + +reg({ "/jumpto", "/j" }, "Teleport to the targeted location", function(ctx) + local x, y, z = ctx.player:target(300) + if not x then return "No block in sight!" end + ctx.player:teleport(x + 0.5, y + 1, z + 0.5) + return "Poof!" +end) + +reg("/up", "Go upwards some distance", function(ctx) + local flags, pos = W.parse(ctx.args) + local dist = floor(num(pos[1], 0)) + if dist <= 0 then return "Usage: /up " end + local x, y, z = player_block(ctx) + local ty = min(126, y + dist) + ctx.player:teleport(x + 0.5, ty, z + 0.5) + mc.world.set_block(x, ty - 1, z, 20, 0) + return "Whoosh!" +end) + +-- --------------------------------------------------------------- selection +reg("/wand", "Gives the wand item", function(ctx) + local flags = W.parse(ctx.args) + if flags.n then + ctx.player:give(NAVWAND, 1) + return "Navigation wand given (left click: /jumpto, right click: /thru)." + end + ctx.player:give(WAND, 1) + return "Left click: select pos #1; Right click: select pos #2" +end) + +reg("/toggleeditwand", "Toggles the wand function", function(ctx) + local s = W.session(ctx.player) + s.wand_off = not s.wand_off + return "Edit wand " .. (s.wand_off and "disabled." or "enabled.") +end) + +local function parse_coords(text) + if not text then return nil end + local c = {} + for n in text:gmatch("[^,]+") do c[#c + 1] = tonumber(n) end + if #c == 3 then return { floor(c[1]), floor(c[2]), floor(c[3]) } end +end + +local function pos_cmd(which) + return function(ctx) + local p = parse_coords(ctx.args[1]) + if not p then + local x, y, z = player_block(ctx) + p = { x, y, z } + end + set_pos(ctx.player, which, p) + end +end +reg("/pos1", "Set position 1", pos_cmd(1)) +reg("/pos2", "Set position 2", pos_cmd(2)) + +reg("/pos", "Set positions", function(ctx) + local x, y, z = player_block(ctx) + set_pos(ctx.player, 1, { x, y, z }) +end) + +local function hpos_cmd(which) + return function(ctx) + local x, y, z = ctx.player:target(300) + if not x then return "No block in sight!" end + set_pos(ctx.player, which, { x, y, z }) + end +end +reg("/hpos1", "Set position 1 to targeted block", hpos_cmd(1)) +reg("/hpos2", "Set position 2 to targeted block", hpos_cmd(2)) + +reg("/chunk", "Select the chunk you are in", function(ctx) + local flags, pos = W.parse(ctx.args) + local s = W.session(ctx.player) + local x, _, z = player_block(ctx) + local cx, cz = floor(x / 16), floor(z / 16) + if pos[1] then + local c = radii(pos[1]) + if c[1] and c[2] then + if flags.c then cx, cz = c[1], c[2] else cx, cz = floor(c[1] / 16), floor(c[2] / 16) end + end + end + s.pos1 = { cx * 16, 0, cz * 16 } + s.pos2 = { cx * 16 + 15, 127, cz * 16 + 15 } + return "Chunk selected: (" .. cx .. ", " .. cz .. ")" +end) + +local function sel_apply(s, fn) + local r = W.region(s) + fn(r) + s.pos1 = { r.x0, r.y0, r.z0 } + s.pos2 = { r.x1, r.y1, r.z1 } + return r +end + +local function move_edge(r, dir, amount) + if dir[1] > 0 then r.x1 = r.x1 + amount elseif dir[1] < 0 then r.x0 = r.x0 - amount end + if dir[2] > 0 then r.y1 = r.y1 + amount elseif dir[2] < 0 then r.y0 = r.y0 - amount end + if dir[3] > 0 then r.z1 = r.z1 + amount elseif dir[3] < 0 then r.z0 = r.z0 - amount end + r.y0, r.y1 = max(0, r.y0), min(127, r.y1) +end + +reg("/expand", "Expand the selection area", function(ctx) + local s, r = selection(ctx) + if not r then return end + if ctx.args[1] == "vert" or ctx.args[1] == "vertical" then + s.pos1[2], s.pos2[2] = 0, 127 + return "Region expanded vertically." + end + local amount = floor(num(ctx.args[1], 0)) + local rev, dirWord = nil, ctx.args[2] + if tonumber(ctx.args[2]) then rev = floor(tonumber(ctx.args[2])); dirWord = ctx.args[3] end + local dir = W.direction(ctx.player, dirWord) + local before = W.volume(r) + sel_apply(s, function(r2) + move_edge(r2, dir, amount) + if rev then move_edge(r2, { -dir[1], -dir[2], -dir[3] }, rev) end + end) + return "Region expanded " .. (W.volume(W.region(s)) - before) .. " blocks." +end) + +reg("/contract", "Contract the selection area", function(ctx) + local s, r = selection(ctx) + if not r then return end + local amount = floor(num(ctx.args[1], 0)) + local rev, dirWord = nil, ctx.args[2] + if tonumber(ctx.args[2]) then rev = floor(tonumber(ctx.args[2])); dirWord = ctx.args[3] end + local dir = W.direction(ctx.player, dirWord) + local before = W.volume(r) + sel_apply(s, function(r2) + -- contracting moves the far edge in the direction towards the opposite one + move_edge(r2, dir, -amount) + if rev then move_edge(r2, { -dir[1], -dir[2], -dir[3] }, -rev) end + end) + return "Region contracted " .. (before - W.volume(W.region(s))) .. " blocks." +end) + +reg("/shift", "Shift the selection area", function(ctx) + local s, r = selection(ctx) + if not r then return end + local amount = floor(num(ctx.args[1], 0)) + local dir = W.direction(ctx.player, ctx.args[2]) + for _, p in ipairs({ s.pos1, s.pos2 }) do + p[1], p[2], p[3] = p[1] + dir[1] * amount, p[2] + dir[2] * amount, p[3] + dir[3] * amount + end + return "Region shifted." +end) + +local function outset_inset(sign) + return function(ctx) + local s, r = selection(ctx) + if not r then return end + local flags, pos = W.parse(ctx.args) + local a = floor(num(pos[1], 0)) * sign + sel_apply(s, function(r2) + if not flags.v then r2.x0, r2.x1, r2.z0, r2.z1 = r2.x0 - a, r2.x1 + a, r2.z0 - a, r2.z1 + a end + if not flags.h then r2.y0, r2.y1 = max(0, r2.y0 - a), min(127, r2.y1 + a) end + end) + return "Region " .. (sign > 0 and "outset." or "inset.") + end +end +reg("/outset", "Outset the selection area", outset_inset(1)) +reg("/inset", "Inset the selection area", outset_inset(-1)) + +reg({ "/sel", "/;", "/desel", "/deselect" }, "Choose a region selector", function(ctx) + local s = W.session(ctx.player) + if not ctx.args[1] or ctx.args[1] == "clear" or ctx.name == "/desel" or ctx.name == "/deselect" then + s.pos1, s.pos2 = nil, nil + return "Selection cleared." + end + if ctx.args[1] == "cuboid" then return "Cuboid: left click for point 1, right click for point 2" end + return "Only the cuboid selector is available." +end) + +reg("/size", "Get information about the selection", function(ctx) + local flags = W.parse(ctx.args) + local s = W.session(ctx.player) + if flags.c then + local c = s.clipboard + if not c then return "Your clipboard is empty. Use //copy first." end + return string.format("Size: %d x %d x %d\nBlocks: %d", c.w, c.h, c.l, c.w * c.h * c.l) + end + local _, r = selection(ctx) + if not r then return end + say(ctx, "Type: cuboid") + say(ctx, "Position 1: " .. fmt(s.pos1)) + say(ctx, "Position 2: " .. fmt(s.pos2)) + say(ctx, string.format("Size: %d x %d x %d", r.x1 - r.x0 + 1, r.y1 - r.y0 + 1, r.z1 - r.z0 + 1)) + say(ctx, "Number of blocks: " .. W.volume(r)) +end) + +reg("/count", "Counts the number of blocks matching a mask", function(ctx) + local _, r = selection(ctx) + if not r then return end + local mask, err = W.mask(ctx.args[1]) + if not mask then return err or "Usage: //count " end + W.load_region(r) + local n = 0 + W.each(r, function(x, y, z) + local id, d = get_block(x, y, z) + if mask(id, d) then n = n + 1 end + end) + return "Counted: " .. n +end) + +reg("/distr", "Get the distribution of blocks in the selection", function(ctx) + local flags = W.parse(ctx.args) + local _, r = selection(ctx) + if not r then return end + W.load_region(r) + local counts, total = {}, 0 + W.each(r, function(x, y, z) + local id, d = get_block(x, y, z) + local key = flags.d and (id * 16 + d) or id + counts[key] = (counts[key] or 0) + 1 + total = total + 1 + end) + local list = {} + for k, v in pairs(counts) do list[#list + 1] = { k, v } end + table.sort(list, function(a, b) return a[2] > b[2] end) + say(ctx, "# total blocks: " .. total) + for i = 1, min(#list, 12) do + local k = list[i][1] + local name = flags.d and (mc.block.name(floor(k / 16)) .. ":" .. (k % 16)) or mc.block.name(k) + say(ctx, string.format("%-7d (%.3f%%) %s", list[i][2], list[i][2] * 100 / total, name)) + end +end) + +reg("/trim", "Shrink the selection to the blocks matching a mask", function(ctx) + local s, r = selection(ctx) + if not r then return end + local mask = W.mask(ctx.args[1] or "#existing") + local nx0, ny0, nz0, nx1, ny1, nz1 = 1e9, 1e9, 1e9, -1e9, -1e9, -1e9 + W.each(r, function(x, y, z) + local id, d = get_block(x, y, z) + if mask(id, d) then + nx0, ny0, nz0 = min(nx0, x), min(ny0, y), min(nz0, z) + nx1, ny1, nz1 = max(nx1, x), max(ny1, y), max(nz1, z) + end + end) + if nx0 == 1e9 then return "No blocks match." end + s.pos1, s.pos2 = { nx0, ny0, nz0 }, { nx1, ny1, nz1 } + return "Region trimmed." +end) + +-- ----------------------------------------------------------------- region +reg("/set", "Set all the blocks inside the selection to a pattern", function(ctx) + local _, r = selection(ctx) + if not r then return end + local pattern = pattern_or_err(ctx, ctx.args[1]) + if not pattern then return end + W.load_region(r) + edit_session(ctx, function(e) W.each(r, function(x, y, z) e:place(x, y, z, pattern) end) end) +end) + +reg({ "/replace", "/re", "/rep" }, "Replace all blocks in the selection with another", function(ctx) + local _, r = selection(ctx) + if not r then return end + local from, to = ctx.args[1], ctx.args[2] + if not to then from, to = "#existing", ctx.args[1] end + local mask, err = W.mask(from) + if not mask then return err or "Usage: //replace [from] " end + local pattern = pattern_or_err(ctx, to) + if not pattern then return end + W.load_region(r) + edit_session(ctx, function(e) + W.each(r, function(x, y, z) + local id, d = get_block(x, y, z) + if mask(id, d) then e:place(x, y, z, pattern) end + end) + end) +end) + +reg("/overlay", "Set a block on top of blocks in the region", function(ctx) + local _, r = selection(ctx) + if not r then return end + local pattern = pattern_or_err(ctx, ctx.args[1]) + if not pattern then return end + W.load_region(r) + edit_session(ctx, function(e) + for x = r.x0, r.x1 do + for z = r.z0, r.z1 do + local top = W.top_existing(x, z, r.y0, r.y1) + if top and top < 127 then e:place(x, top + 1, z, pattern) end + end + end + end) +end) + +reg({ "/center", "/middle" }, "Set the center block(s)", function(ctx) + local _, r = selection(ctx) + if not r then return end + local pattern = pattern_or_err(ctx, ctx.args[1]) + if not pattern then return end + edit_session(ctx, function(e) + local cx0, cx1 = floor((r.x0 + r.x1) / 2), ceil((r.x0 + r.x1) / 2) + local cy0, cy1 = floor((r.y0 + r.y1) / 2), ceil((r.y0 + r.y1) / 2) + local cz0, cz1 = floor((r.z0 + r.z1) / 2), ceil((r.z0 + r.z1) / 2) + for x = cx0, cx1 do for y = cy0, cy1 do for z = cz0, cz1 do e:place(x, y, z, pattern) end end end + end) +end) + +reg("/naturalize", "3 layers of dirt on top then rock below", function(ctx) + local _, r = selection(ctx) + if not r then return end + W.load_region(r) + edit_session(ctx, function(e) + for x = r.x0, r.x1 do + for z = r.z0, r.z1 do + local depth = 0 + for y = r.y1, r.y0, -1 do + local id = get_block(x, y, z) + if id ~= 0 and not W.is_liquid(id) then + if depth == 0 then e:set(x, y, z, 2, 0) + elseif depth <= 3 then e:set(x, y, z, 3, 0) + else e:set(x, y, z, 1, 0) end + depth = depth + 1 + else + depth = 0 + end + end + end + end + end) +end) + +reg("/walls", "Build the four sides of the selection", function(ctx) + local _, r = selection(ctx) + if not r then return end + local pattern = pattern_or_err(ctx, ctx.args[1]) + if not pattern then return end + W.load_region(r) + edit_session(ctx, function(e) W.walls_and_faces(r, e, pattern, false) end) +end) + +reg({ "/faces", "/outline" }, "Build the walls, ceiling, and floor of a selection", function(ctx) + local _, r = selection(ctx) + if not r then return end + local pattern = pattern_or_err(ctx, ctx.args[1]) + if not pattern then return end + W.load_region(r) + edit_session(ctx, function(e) W.walls_and_faces(r, e, pattern, true) end) +end) + +reg("/hollow", "Hollows out the object contained in this selection", function(ctx) + local _, r = selection(ctx) + if not r then return end + local flags, pos = W.parse(ctx.args) + local thickness = max(1, floor(num(pos[1], 1))) + local fill = pattern_or_err(ctx, pos[2] or "air") + if not fill then return end + W.load_region(r) + local function inside(x, y, z) return x >= r.x0 and x <= r.x1 and y >= r.y0 and y <= r.y1 and z >= r.z0 and z <= r.z1 end + local N = { { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 0, 1 }, { 0, 0, -1 } } + local keep, frontier = {}, {} + local function key(x, y, z) return (x - r.x0) + (z - r.z0) * 4096 + (y * 16777216) end + W.each(r, function(x, y, z) + if get_block(x, y, z) ~= 0 then + for _, n in ipairs(N) do + local nx, ny, nz = x + n[1], y + n[2], z + n[3] + if not inside(nx, ny, nz) or get_block(nx, ny, nz) == 0 then + keep[key(x, y, z)] = true + frontier[#frontier + 1] = { x, y, z } + break + end + end + end + end) + for _ = 2, thickness do + local nextFrontier = {} + for _, p in ipairs(frontier) do + for _, n in ipairs(N) do + local nx, ny, nz = p[1] + n[1], p[2] + n[2], p[3] + n[3] + if inside(nx, ny, nz) and get_block(nx, ny, nz) ~= 0 and not keep[key(nx, ny, nz)] then + keep[key(nx, ny, nz)] = true + nextFrontier[#nextFrontier + 1] = { nx, ny, nz } + end + end + end + frontier = nextFrontier + end + edit_session(ctx, function(e) + W.each(r, function(x, y, z) + if get_block(x, y, z) ~= 0 and not keep[key(x, y, z)] then e:place(x, y, z, fill) end + end) + end) +end) + +-- Gaussian terrain smoothing, like the WorldEdit height map filter (5x5 kernel) +local KERNEL, KSUM = {}, 0 +for dx = -2, 2 do + for dz = -2, 2 do + local w = math.exp(-(dx * dx + dz * dz) / 2) + KERNEL[#KERNEL + 1] = { dx, dz, w } + KSUM = KSUM + w + end +end + +local function smooth_region(e, r, iterations, mask) + local w, l = r.x1 - r.x0 + 1, r.z1 - r.z0 + 1 + local function heights() + local h, types = {}, {} + for x = r.x0, r.x1 do + for z = r.z0, r.z1 do + local top + for y = r.y1, r.y0, -1 do + local id, d = get_block(x, y, z) + if id ~= 0 and not W.is_liquid(id) and (not mask or mask(id, d)) then top = y; types[#types + 1] = nil; break end + end + h[(x - r.x0) * l + (z - r.z0)] = top or (r.y0 - 1) + end + end + return h + end + for _ = 1, iterations do + local h = heights() + local newH = {} + for x = 0, w - 1 do + for z = 0, l - 1 do + local sum, wsum = 0, 0 + for _, k in ipairs(KERNEL) do + local nx, nz = x + k[1], z + k[2] + if nx >= 0 and nx < w and nz >= 0 and nz < l then + sum = sum + h[nx * l + nz] * k[3] + wsum = wsum + k[3] + end + end + newH[x * l + z] = floor(sum / wsum + 0.5) + end + end + for x = 0, w - 1 do + for z = 0, l - 1 do + local wx, wz = r.x0 + x, r.z0 + z + local oh, nh = h[x * l + z], newH[x * l + z] + if nh > oh then + local id, d = get_block(wx, max(oh, r.y0), wz) + if oh < r.y0 then id, d = 3, 0 end + for y = oh + 1, min(nh, r.y1) do e:set(wx, y, wz, id, d) end + elseif nh < oh then + for y = nh + 1, oh do e:set(wx, y, wz, 0, 0) end + end + end + end + end +end + +reg("/smooth", "Smooth the elevation in the selection", function(ctx) + local _, r = selection(ctx) + if not r then return end + local iterations = max(1, floor(num(ctx.args[1], 1))) + local mask = ctx.args[2] and W.mask(ctx.args[2]) + W.load_region(r) + edit_session(ctx, function(e) smooth_region(e, r, iterations, mask) end) +end) + +-- ------------------------------------------------------- move / stack +local function read_region(r, skipAir) + local blocks = {} + local n = 0 + for x = r.x0, r.x1 do + for y = r.y0, r.y1 do + for z = r.z0, r.z1 do + local id, d = get_block(x, y, z) + if not (skipAir and id == 0) then + n = n + 1 + blocks[n] = { x - r.x0, y - r.y0, z - r.z0, id, d } + end + end + end + end + return blocks +end + +reg("/move", "Move the contents of the selection", function(ctx) + local s, r = selection(ctx) + if not r then return end + local flags, pos = W.parse(ctx.args, { m = true }) + local count = max(1, floor(num(pos[1], 1))) + local dir = W.direction(ctx.player, pos[2]) + local replace = pattern_or_err(ctx, pos[3] or "air") + if not replace then return end + local mask = flags.m and W.mask(flags.m) + local dx, dy, dz = dir[1] * count, dir[2] * count, dir[3] * count + local target = { x0 = r.x0 + dx, x1 = r.x1 + dx, y0 = r.y0 + dy, y1 = r.y1 + dy, z0 = r.z0 + dz, z1 = r.z1 + dz } + W.load_region(r); W.load_region(target) + local blocks = read_region(r, flags.a) + edit_session(ctx, function(e) + for _, b in ipairs(blocks) do + if not mask or mask(b[4], b[5]) then e:place(r.x0 + b[1], r.y0 + b[2], r.z0 + b[3], replace) end + end + for _, b in ipairs(blocks) do + if not mask or mask(b[4], b[5]) then e:set(target.x0 + b[1], target.y0 + b[2], target.z0 + b[3], b[4], b[5]) end + end + end) + if flags.s then + s.pos1 = { target.x0, target.y0, target.z0 } + s.pos2 = { target.x1, target.y1, target.z1 } + end +end) + +reg("/stack", "Repeat the contents of the selection", function(ctx) + local s, r = selection(ctx) + if not r then return end + local flags, pos = W.parse(ctx.args, { m = true }) + local count = max(1, floor(num(pos[1], 1))) + local dir = W.direction(ctx.player, pos[2]) + local sx = (r.x1 - r.x0 + 1) * dir[1] + local sy = (r.y1 - r.y0 + 1) * dir[2] + local sz = (r.z1 - r.z0 + 1) * dir[3] + local mask = flags.m and W.mask(flags.m) + W.load_region(r) + local blocks = read_region(r, flags.a) + edit_session(ctx, function(e) + for i = 1, count do + W.load_region({ x0 = r.x0 + sx * i, x1 = r.x1 + sx * i, z0 = r.z0 + sz * i, z1 = r.z1 + sz * i, y0 = 0, y1 = 0 }) + for _, b in ipairs(blocks) do + if not mask or mask(b[4], b[5]) then + e:set(r.x0 + b[1] + sx * i, r.y0 + b[2] + sy * i, r.z0 + b[3] + sz * i, b[4], b[5]) + end + end + end + end) + if flags.s then + s.pos2 = { r.x1 + sx * count, r.y1 + sy * count, r.z1 + sz * count } + end +end) + +-- ------------------------------------------------------------- generation +local function gen_origin(ctx, flags, raise) + local x, y, z = player_block(ctx) + if flags.r then y = y + raise end + return x, y, z +end + +local function sphere_cmd(hollowDefault) + return function(ctx) + local flags, pos = W.parse(ctx.args) + local pattern = pattern_or_err(ctx, pos[1]) + if not pattern then return end + local rad = radii(pos[2] or "") + if not rad[1] then return "Usage: //sphere [-hr] " end + local rx, ry, rz = rad[1], rad[2] or rad[1], rad[3] or rad[1] + local x, y, z = gen_origin(ctx, flags, ry) + local filled = not (flags.h or hollowDefault) + W.load_region({ x0 = x - rx, x1 = x + rx, z0 = z - rz, z1 = z + rz, y0 = 0, y1 = 0 }) + edit_session(ctx, function(e) W.sphere(e, x, y, z, pattern, rx, ry, rz, filled) end) + end +end +reg("/sphere", "Generate a filled sphere", sphere_cmd(false)) +reg("/hsphere", "Generate a hollow sphere", sphere_cmd(true)) + +local function cyl_cmd(hollowDefault) + return function(ctx) + local flags, pos = W.parse(ctx.args) + local pattern = pattern_or_err(ctx, pos[1]) + if not pattern then return end + local rad = radii(pos[2] or "") + if not rad[1] then return "Usage: //cyl [-h] [height]" end + local rx, rz = rad[1], rad[2] or rad[1] + local height = floor(num(pos[3], 1)) + local x, y, z = player_block(ctx) + W.load_region({ x0 = x - rx, x1 = x + rx, z0 = z - rz, z1 = z + rz, y0 = 0, y1 = 0 }) + edit_session(ctx, function(e) W.cylinder(e, x, y, z, pattern, rx, rz, height, not (flags.h or hollowDefault)) end) + end +end +reg("/cyl", "Generate a cylinder", cyl_cmd(false)) +reg("/hcyl", "Generate a hollow cylinder", cyl_cmd(true)) + +reg("/cone", "Generate a cone", function(ctx) + local flags, pos = W.parse(ctx.args) + local pattern = pattern_or_err(ctx, pos[1]) + if not pattern then return end + local rad = radii(pos[2] or "") + if not rad[1] then return "Usage: //cone [-h] [height]" end + local rx, rz = rad[1], rad[2] or rad[1] + local height = floor(num(pos[3], 1)) + local x, y, z = player_block(ctx) + W.load_region({ x0 = x - rx, x1 = x + rx, z0 = z - rz, z1 = z + rz, y0 = 0, y1 = 0 }) + edit_session(ctx, function(e) W.cone(e, x, y, z, pattern, rx, rz, height, not flags.h) end) +end) + +local function pyramid_cmd(hollowDefault) + return function(ctx) + local flags, pos = W.parse(ctx.args) + local pattern = pattern_or_err(ctx, pos[1]) + if not pattern then return end + local size = floor(num(pos[2], 0)) + if size < 1 then return "Usage: //pyramid [-h] " end + local x, y, z = player_block(ctx) + W.load_region({ x0 = x - size, x1 = x + size, z0 = z - size, z1 = z + size, y0 = 0, y1 = 0 }) + edit_session(ctx, function(e) W.pyramid(e, x, y, z, pattern, size, not (flags.h or hollowDefault)) end) + end +end +reg("/pyramid", "Generate a filled pyramid", pyramid_cmd(false)) +reg("/hpyramid", "Generate a hollow pyramid", pyramid_cmd(true)) + +reg("/line", "Draws a line segment between the cuboid selection corners", function(ctx) + local s, r = selection(ctx) + if not r then return end + local flags, pos = W.parse(ctx.args) + local pattern = pattern_or_err(ctx, pos[1]) + if not pattern then return end + local thickness = floor(num(pos[2], 0)) + W.load_region(r) + edit_session(ctx, function(e) W.line(e, s.pos1, s.pos2, pattern, thickness, not flags.h) end) +end) + +-- -------------------------------------------------------------- clipboard +local function take_clipboard(ctx, r, flags, cut, leave) + local s = W.session(ctx.player) + local px, py, pz = player_block(ctx) + W.load_region(r) + local mask = flags.m and W.mask(flags.m) + local blocks = {} + local n = 0 + for x = r.x0, r.x1 do + for y = r.y0, r.y1 do + for z = r.z0, r.z1 do + local id, d = get_block(x, y, z) + if not mask or mask(id, d) then + n = n + 1 + blocks[n] = { x - r.x0, y - r.y0, z - r.z0, id, d } + end + end + end + end + s.clipboard = { + w = r.x1 - r.x0 + 1, h = r.y1 - r.y0 + 1, l = r.z1 - r.z0 + 1, + ox = r.x0 - px, oy = r.y0 - py, oz = r.z0 - pz, -- offset from copy position to min corner + wx = r.x0, wy = r.y0, wz = r.z0, -- original world position + blocks = blocks, + } + say(ctx, n .. " block(s) were copied.") + if cut then + edit_session(ctx, function(e) + for _, b in ipairs(blocks) do e:place(r.x0 + b[1], r.y0 + b[2], r.z0 + b[3], leave) end + end) + end +end + +reg("/copy", "Copy the selection to the clipboard", function(ctx) + local flags = W.parse(ctx.args, { m = true }) + local _, r = selection(ctx) + if r then take_clipboard(ctx, r, flags, false) end +end) + +reg("/cut", "Cut the selection to the clipboard", function(ctx) + local flags, pos = W.parse(ctx.args, { m = true }) + local _, r = selection(ctx) + if not r then return end + local leave = pattern_or_err(ctx, pos[1] or "air") + if leave then take_clipboard(ctx, r, flags, true, leave) end +end) + +reg("/paste", "Paste the clipboard's contents", function(ctx) + local flags = W.parse(ctx.args, { m = true }) + local s = W.session(ctx.player) + local c = s.clipboard + if not c then return "Your clipboard is empty. Use //copy first." end + local px, py, pz = player_block(ctx) + local bx, by, bz + if flags.o then bx, by, bz = c.wx, c.wy, c.wz else bx, by, bz = px + c.ox, py + c.oy, pz + c.oz end + local mask = flags.m and W.mask(flags.m) + W.load_region({ x0 = bx, x1 = bx + c.w, z0 = bz, z1 = bz + c.l, y0 = 0, y1 = 0 }) + if not flags.n then + edit_session(ctx, function(e) + for _, b in ipairs(c.blocks) do + if not (flags.a and b[4] == 0) and (not mask or mask(b[4], b[5])) then + e:set(bx + b[1], by + b[2], bz + b[3], b[4], b[5]) + end + end + end) + end + if flags.s or flags.n then + s.pos1 = { bx, by, bz } + s.pos2 = { bx + c.w - 1, by + c.h - 1, bz + c.l - 1 } + end +end) + +local function transform_clipboard(c, fn, newW, newH, newL, ox, oy, oz) + local out = {} + for i, b in ipairs(c.blocks) do out[i] = fn(b) end + c.blocks = out + c.w, c.h, c.l = newW or c.w, newH or c.h, newL or c.l + if ox then c.ox, c.oy, c.oz = ox, oy, oz end +end + +reg("/rotate", "Rotate the contents of the clipboard", function(ctx) + local s = W.session(ctx.player) + local c = s.clipboard + if not c then return "Your clipboard is empty. Use //copy first." end + local deg = floor(num(ctx.args[1], 0)) + if deg % 90 ~= 0 then return "Angles must be multiples of 90 degrees." end + local turns = (deg / 90) % 4 + for _ = 1, turns do + -- 90 degrees clockwise around y: (x, z) -> (l - 1 - z, x) + local w, l = c.w, c.l + transform_clipboard(c, function(b) + return { l - 1 - b[3], b[2], b[1], b[4], W.rotate_data(b[4], b[5], 1) } + end, l, c.h, w, -(c.oz + l - 1), c.oy, c.ox) + end + return "The clipboard copy has been rotated." +end) + +reg({ "/flip", "/mirror" }, "Flip the contents of the clipboard", function(ctx) + local s = W.session(ctx.player) + local c = s.clipboard + if not c then return "Your clipboard is empty. Use //copy first." end + local dir = W.direction(ctx.player, ctx.args[1]) + local w, h, l = c.w, c.h, c.l + transform_clipboard(c, function(b) + local x, y, z = b[1], b[2], b[3] + if dir[1] ~= 0 then x = w - 1 - x end + if dir[2] ~= 0 then y = h - 1 - y end + if dir[3] ~= 0 then z = l - 1 - z end + return { x, y, z, b[4], b[5] } + end) + if dir[1] ~= 0 then c.ox = -(c.ox + w - 1) end + if dir[2] ~= 0 then c.oy = -(c.oy + h - 1) end + if dir[3] ~= 0 then c.oz = -(c.oz + l - 1) end + return "The clipboard copy has been flipped." +end) + +reg("/clearclipboard", "Clear your clipboard", function(ctx) + W.session(ctx.player).clipboard = nil + return "Clipboard cleared." +end) + +-- schematics are stored as Lua tables in schematics/.schem +reg({ "/schematic", "/schem" }, "Schematic commands for saving/loading areas", function(ctx) + local sub = ctx.args[1] + local s = W.session(ctx.player) + mc._mkdir("schematics") + local function path(name) return "schematics/" .. name:gsub("[^%w_%-]", "_") .. ".schem" end + if sub == "save" then + local name = ctx.args[#ctx.args] + if not s.clipboard or not name or name == "save" then return "Usage: /schematic save (copy something first)" end + local ok, err = mc.save_table(path(name), s.clipboard) + return ok and ("Clipboard saved as " .. name .. ".") or ("Could not save: " .. tostring(err)) + elseif sub == "load" then + local name = ctx.args[#ctx.args] + local data = name and mc.load_table(path(name)) + if not data then return "Schematic not found." end + s.clipboard = data + return "Schematic " .. name .. " loaded. Paste it with //paste" + elseif sub == "list" or sub == "all" or sub == "ls" then + local names = {} + for _, e in ipairs(mc._listdir("schematics")) do + local n = e.name:match("^(.+)%.schem$") + if n then names[#names + 1] = n end + end + table.sort(names) + return "Available schematics: " .. (#names > 0 and table.concat(names, ", ") or "(none)") + elseif sub == "delete" or sub == "d" then + local name = ctx.args[2] + if not name then return "Usage: /schematic delete " end + os.remove(path(name)) + return "Deleted " .. name .. "." + elseif sub == "formats" then + return "Available formats: mcpe-lua (default)" + end + return "Usage: /schematic " +end) + +-- ---------------------------------------------------------------- history +reg({ "/undo" }, "Undo your last action", function(ctx) + local times = max(1, floor(num(ctx.args[1], 1))) + local s = W.session(ctx.player) + local done = 0 + for _ = 1, times do + if not W.undo(s) then break end + done = done + 1 + end + if done == 0 then return "Nothing left to undo." end + return "Undo successful." +end) + +reg({ "/redo" }, "Redo your last undone action", function(ctx) + local times = max(1, floor(num(ctx.args[1], 1))) + local s = W.session(ctx.player) + local done = 0 + for _ = 1, times do + if not W.redo(s) then break end + done = done + 1 + end + if done == 0 then return "Nothing left to redo." end + return "Redo successful." +end) + +reg("/clearhistory", "Clear your history", function(ctx) + local s = W.session(ctx.player) + s.undo, s.redo = {}, {} + return "History cleared." +end) + +-- ------------------------------------------------------------------ utility +local function flood_fill(ctx, recursive) + local flags, pos = W.parse(ctx.args) + local pattern = pattern_or_err(ctx, pos[1]) + if not pattern then return end + local radius = floor(num(pos[2], 0)) + if radius < 1 then return "Usage: //fill [depth]" end + local depth = floor(num(pos[3], 1 / 0)) + local ox, oy, oz = player_block(ctx) + W.load_region({ x0 = ox - radius, x1 = ox + radius, z0 = oz - radius, z1 = oz + radius, y0 = 0, y1 = 0 }) + edit_session(ctx, function(e) + local seen = {} + local queue, head = {}, 1 + local function push(x, y, z) + local k = (x * 4096 + z) * 256 + y + if seen[k] then return end + if (x - ox) ^ 2 + (z - oz) ^ 2 > radius * radius then return end + if y > oy or y < oy - depth + 1 or y < 0 then return end + if get_block(x, y, z) ~= 0 then return end + seen[k] = true + queue[#queue + 1] = { x, y, z } + end + push(ox, oy, oz) + if recursive then push(ox, oy - 1, oz) end + while head <= #queue do + local p = queue[head]; head = head + 1 + e:place(p[1], p[2], p[3], pattern) + push(p[1] + 1, p[2], p[3]); push(p[1] - 1, p[2], p[3]) + push(p[1], p[2], p[3] + 1); push(p[1], p[2], p[3] - 1) + if recursive then push(p[1], p[2] - 1, p[3]) end + end + end) +end +reg("/fill", "Fill a hole", function(ctx) flood_fill(ctx, false) end) +reg("/fillr", "Fill a hole recursively", function(ctx) flood_fill(ctx, true) end) + +reg("/drain", "Drain a pool", function(ctx) + local flags, pos = W.parse(ctx.args) + local radius = floor(num(pos[1], 0)) + if radius < 1 then return "Usage: //drain [-w] " end + local ox, oy, oz = player_block(ctx) + W.load_region({ x0 = ox - radius, x1 = ox + radius, z0 = oz - radius, z1 = oz + radius, y0 = 0, y1 = 0 }) + edit_session(ctx, function(e) + local seen, queue, head = {}, {}, 1 + local function push(x, y, z) + if y < 0 or y > 127 then return end + local k = (x * 4096 + z) * 256 + y + if seen[k] or (x - ox) ^ 2 + (y - oy) ^ 2 + (z - oz) ^ 2 > radius * radius then return end + if not W.is_liquid(get_block(x, y, z)) then return end + seen[k] = true + queue[#queue + 1] = { x, y, z } + end + for dx = -1, 1 do for dy = -1, 2 do for dz = -1, 1 do push(ox + dx, oy + dy, oz + dz) end end end + while head <= #queue do + local p = queue[head]; head = head + 1 + e:set(p[1], p[2], p[3], 0, 0) + push(p[1] + 1, p[2], p[3]); push(p[1] - 1, p[2], p[3]) + push(p[1], p[2] + 1, p[3]); push(p[1], p[2] - 1, p[3]) + push(p[1], p[2], p[3] + 1); push(p[1], p[2], p[3] - 1) + end + end) +end) + +local function near_sphere(ctx, radius, fn) + local ox, oy, oz = player_block(ctx) + W.load_region({ x0 = ox - radius, x1 = ox + radius, z0 = oz - radius, z1 = oz + radius, y0 = 0, y1 = 0 }) + for x = ox - radius, ox + radius do + for y = max(0, oy - radius), min(127, oy + radius) do + for z = oz - radius, oz + radius do + if (x - ox) ^ 2 + (y - oy) ^ 2 + (z - oz) ^ 2 <= radius * radius then fn(x, y, z) end + end + end + end +end + +reg("/fixwater", "Level nearby water", function(ctx) + local radius = floor(num(ctx.args[1], 0)) + if radius < 1 then return "Usage: /fixwater " end + edit_session(ctx, function(e) + near_sphere(ctx, radius, function(x, y, z) + local id = get_block(x, y, z) + if id == 8 then e:set(x, y, z, 9, 0) end + end) + end) +end) + +reg("/fixlava", "Level nearby lava", function(ctx) + local radius = floor(num(ctx.args[1], 0)) + if radius < 1 then return "Usage: /fixlava " end + edit_session(ctx, function(e) + near_sphere(ctx, radius, function(x, y, z) + local id = get_block(x, y, z) + if id == 10 then e:set(x, y, z, 11, 0) end + end) + end) +end) + +local function column_remove(ctx, dirY) + local size = max(1, floor(num(ctx.args[1], 1))) + local height = floor(num(ctx.args[2], 127)) + local ox, oy, oz = player_block(ctx) + W.load_region({ x0 = ox - size, x1 = ox + size, z0 = oz - size, z1 = oz + size, y0 = 0, y1 = 0 }) + edit_session(ctx, function(e) + local y0, y1 + if dirY > 0 then y0, y1 = oy + 2, min(127, oy + 1 + height) else y0, y1 = max(0, oy - height), oy - 1 end + for x = ox - size, ox + size do + for z = oz - size, oz + size do + for y = y0, y1 do e:set(x, y, z, 0, 0) end + end + end + end) +end +reg("/removeabove", "Remove blocks above your head", function(ctx) column_remove(ctx, 1) end) +reg("/removebelow", "Remove blocks below you", function(ctx) column_remove(ctx, -1) end) + +reg("/removenear", "Remove blocks near you", function(ctx) + local mask, err = W.mask(ctx.args[1]) + if not mask then return err or "Usage: /removenear [size]" end + local size = floor(num(ctx.args[2], 50)) + edit_session(ctx, function(e) + near_sphere(ctx, size, function(x, y, z) + local id, d = get_block(x, y, z) + if mask(id, d) then e:set(x, y, z, 0, 0) end + end) + end) +end) + +reg("/replacenear", "Replace nearby blocks", function(ctx) + local size = floor(num(ctx.args[1], 0)) + if size < 1 then return "Usage: /replacenear [from] " end + local from, to = ctx.args[2], ctx.args[3] + if not to then from, to = "#existing", ctx.args[2] end + local mask = W.mask(from) + local pattern = pattern_or_err(ctx, to) + if not mask or not pattern then return end + edit_session(ctx, function(e) + near_sphere(ctx, size, function(x, y, z) + local id, d = get_block(x, y, z) + if mask(id, d) then e:place(x, y, z, pattern) end + end) + end) +end) + +reg("/snow", "Simulates snow", function(ctx) + local flags, pos = W.parse(ctx.args) + local size = max(1, floor(num(pos[1], 10))) + local ox, _, oz = player_block(ctx) + W.load_region({ x0 = ox - size, x1 = ox + size, z0 = oz - size, z1 = oz + size, y0 = 0, y1 = 0 }) + edit_session(ctx, function(e) + for x = ox - size, ox + size do + for z = oz - size, oz + size do + if (x - ox) ^ 2 + (z - oz) ^ 2 <= size * size then + local top = W.top_existing(x, z, 0, 127) + if top and top < 127 then + local id = get_block(x, top, z) + if id == 9 or id == 8 then e:set(x, top, z, 79, 0) + elseif id ~= 78 and id ~= 80 and id ~= 79 then e:set(x, top + 1, z, 78, 0) end + end + end + end + end + end) +end) + +reg("/thaw", "Thaws the area", function(ctx) + local size = max(1, floor(num(ctx.args[1], 10))) + edit_session(ctx, function(e) + near_sphere(ctx, size, function(x, y, z) + local id = get_block(x, y, z) + if id == 78 then e:set(x, y, z, 0, 0) elseif id == 79 then e:set(x, y, z, 9, 0) end + end) + end) +end) + +reg("/green", "Converts dirt to grass blocks", function(ctx) + local size = max(1, floor(num(ctx.args[1], 10))) + local ox, _, oz = player_block(ctx) + W.load_region({ x0 = ox - size, x1 = ox + size, z0 = oz - size, z1 = oz + size, y0 = 0, y1 = 0 }) + edit_session(ctx, function(e) + for x = ox - size, ox + size do + for z = oz - size, oz + size do + if (x - ox) ^ 2 + (z - oz) ^ 2 <= size * size then + local top = W.top_existing(x, z, 0, 127) + if top and get_block(x, top, z) == 3 then e:set(x, top, z, 2, 0) end + end + end + end + end) +end) + +reg({ "/extinguish", "/ex", "/ext" }, "Extinguish nearby fire", function(ctx) + local size = floor(num(ctx.args[1], 40)) + edit_session(ctx, function(e) + near_sphere(ctx, size, function(x, y, z) + if get_block(x, y, z) == 51 then e:set(x, y, z, 0, 0) end + end) + end) +end) + +reg("/butcher", "Kill all or nearby mobs", function(ctx) + local flags, pos = W.parse(ctx.args) + local radius = floor(num(pos[1], 0)) + local x, y, z = ctx.player:pos() + local n = mc.world.butcher(x, y, z, radius > 0 and radius or 0, flags.f or flags.a) + return "Killed " .. n .. " mobs" .. (radius > 0 and (" in a radius of " .. radius) or "") .. "." +end) + +reg("/toggleplace", "Switch between your position and pos1 for placement", function(ctx) + local s = W.session(ctx.player) + s.place_at_pos1 = not s.place_at_pos1 + return "Now placing at " .. (s.place_at_pos1 and "pos #1." or "the block you stand in.") +end) + +-- ------------------------------------------------------------------- tools +local function held_id(player) local id = player:held(); return id end + +reg("/tool", "Bind a tool to the item in your hand", function(ctx) + local s = W.session(ctx.player) + local item = held_id(ctx.player) + if item == 0 then return "Hold an item to bind the tool to." end + local sub = ctx.args[1] + if sub == "none" or sub == "unbind" then + s.tools[item] = nil + return "Tool unbound from your current item." + elseif sub == "repl" then + local p = pattern_or_err(ctx, ctx.args[2]) + if not p then return end + s.tools[item] = { type = "repl", pattern = p } + return "Block replacer tool bound to " .. mc.block.name(item) .. "." + elseif sub == "info" then + s.tools[item] = { type = "info" } + return "Block info tool bound." + elseif sub == "farwand" then + s.tools[item] = { type = "farwand" } + return "Far wand tool bound." + elseif sub == "navwand" then + s.tools[item] = { type = "nav" } + return "Navigation wand bound." + elseif sub == "selwand" then + s.tools[item] = { type = "wand" } + return "Selection wand bound." + elseif sub == "deltree" then + s.tools[item] = { type = "deltree" } + return "Floating tree remover bound." + elseif sub == "floodfill" or sub == "flood" then + local p = pattern_or_err(ctx, ctx.args[2]) + if not p then return end + s.tools[item] = { type = "flood", pattern = p, range = floor(num(ctx.args[3], 5)) } + return "Block flood fill tool bound." + end + return "Usage: /tool " +end) + +reg("/none", "Unbind the tool of your item", function(ctx) + local s = W.session(ctx.player) + s.tools[held_id(ctx.player)] = nil + return "Tool unbound from your current item." +end) + +reg("/mask", "Set the brush mask", function(ctx) + local s = W.session(ctx.player) + if not ctx.args[1] then s.brush_mask = nil; return "Brush mask disabled." end + local m, err = W.mask(ctx.args[1]) + if not m then return err end + s.brush_mask = m + return "Brush mask set." +end) + +reg({ "/material", "/mat" }, "Set the brush material", function(ctx) + local s = W.session(ctx.player) + local p = pattern_or_err(ctx, ctx.args[1]) + if not p then return end + s.brush_material = p + return "Brush material set." +end) + +reg("/range", "Set the brush range", function(ctx) + local s = W.session(ctx.player) + s.brush_range = floor(num(ctx.args[1], 200)) + return "Brush range set." +end) + +reg("size", "Set the brush size", function(ctx) + local s = W.session(ctx.player) + s.brush_size = max(1, min(20, floor(num(ctx.args[1], 5)))) + return "Brush size set to " .. s.brush_size .. "." +end) + +reg({ "/superpickaxe", "/pickaxe", "/sp" }, "Select super pickaxe mode", function(ctx) + local s = W.session(ctx.player) + local mode = ctx.args[1] + if mode == "single" or mode == "area" or mode == "recursive" or mode == "recur" then + s.superpick = (mode == "recur") and "recursive" or mode + s.superpick_range = floor(num(ctx.args[2], 3)) + return "Mode changed. Left click with a pickaxe. // to disable." + end + return "Usage: /sp [range]" +end) + +reg({ "/", ",", "/," }, "Toggle the super pickaxe pickaxe function", function(ctx) + local s = W.session(ctx.player) + if s.superpick then s.superpick = nil; return "Super pick axe disabled." end + s.superpick = "single" + return "Super pick axe enabled." +end) + +-- brushes +local BRUSHES = { sphere = true, cylinder = true, cyl = true, set = true, smooth = true, gravity = true, + extinguish = true, ex = true, raise = true, lower = true, butcher = true, kill = true } + +reg({ "/brush", "/br" }, "Brush tool", function(ctx) + local s = W.session(ctx.player) + local item = held_id(ctx.player) + if item == 0 then return "Hold an item to bind the brush to." end + local flags, pos = W.parse(ctx.args) + local kind = pos[1] + if kind == "none" or kind == "unbind" then + s.tools[item] = nil + return "Brush unbound from your current item." + end + if kind == "s" then kind = "sphere" elseif kind == "c" then kind = "cylinder" elseif kind == "cyl" then kind = "cylinder" + elseif kind == "ex" then kind = "extinguish" elseif kind == "kill" then kind = "butcher" end + if not kind or not BRUSHES[kind] then + return "Usage: /brush ..." + end + local brush = { type = "brush", kind = kind, hollow = flags.h } + local i = 2 + if kind == "sphere" or kind == "cylinder" then + brush.pattern = pattern_or_err(ctx, pos[i]); if not brush.pattern then return end + brush.radius = floor(num(pos[i + 1], 2)) + if kind == "cylinder" then brush.height = floor(num(pos[i + 2], 1)) end + elseif kind == "set" then + brush.pattern = pattern_or_err(ctx, pos[i + 2] or pos[i]); if not brush.pattern then return end + brush.radius = floor(num(pos[i + 1], 2)) + else + brush.radius = floor(num(pos[i], 2)) + brush.iterations = floor(num(pos[i + 1], 4)) + end + s.tools[item] = brush + return "Brush '" .. kind .. "' bound to your current item." +end) + +local function use_brush(player, s, brush, x, y, z) + if brush.kind == "extinguish" then + local e = W.new_edit(s) + for dx = -brush.radius, brush.radius do for dy = -brush.radius, brush.radius do for dz = -brush.radius, brush.radius do + if get_block(x + dx, y + dy, z + dz) == 51 then e:set(x + dx, y + dy, z + dz, 0, 0) end + end end end + e:commit() + return + elseif brush.kind == "butcher" then + mc.world.butcher(x, y, z, brush.radius, false) + return + end + local edit = W.new_edit(s) + local mask = s.brush_mask + local r = brush.radius + W.load_region({ x0 = x - r, x1 = x + r, z0 = z - r, z1 = z + r, y0 = 0, y1 = 0 }) + if brush.kind == "sphere" then + local inner = brush.pattern + local pat = inner + if mask then + pat = function() return inner() end + end + local guarded = { + set = function(_, bx, by, bz, id, d) + if mask then local oid, od = get_block(bx, by, bz); if not mask(oid, od) then return end end + edit:set(bx, by, bz, id, d) + end, + place = function(self, bx, by, bz, p) local id, d = p(); self.set(self, bx, by, bz, id, d) end, + } + W.sphere(guarded, x, y, z, pat, r, r, r, not brush.hollow) + elseif brush.kind == "cylinder" then + W.cylinder(edit, x, y, z, brush.pattern, r, r, brush.height, not brush.hollow) + elseif brush.kind == "set" then + for dx = -r, r do for dy = -r, r do for dz = -r, r do + if dx * dx + dy * dy + dz * dz <= r * r + 1 then + local oid, od = get_block(x + dx, y + dy, z + dz) + if not mask or mask(oid, od) then edit:place(x + dx, y + dy, z + dz, brush.pattern) end + end + end end end + elseif brush.kind == "smooth" then + smooth_region(edit, { x0 = x - r, x1 = x + r, z0 = z - r, z1 = z + r, y0 = max(0, y - r), y1 = min(127, y + r) }, brush.iterations or 4, mask) + elseif brush.kind == "raise" or brush.kind == "lower" then + for dx = -r, r do for dz = -r, r do + if dx * dx + dz * dz <= r * r then + local top = W.top_ground(x + dx, z + dz, 0, 127) + if top then + if brush.kind == "raise" then + local id, d = get_block(x + dx, top, z + dz) + edit:set(x + dx, top + 1, z + dz, id, d) + else + edit:set(x + dx, top, z + dz, 0, 0) + end + end + end + end end + elseif brush.kind == "gravity" then + for dx = -r, r do for dz = -r, r do + if dx * dx + dz * dz <= r * r then + local bx, bz = x + dx, z + dz + local y0 = max(0, y - r) + local floorY = y0 + for yy = y0, min(127, y + r) do + local id, d = get_block(bx, yy, bz) + if id ~= 0 then + if yy ~= floorY then + edit:set(bx, floorY, bz, id, d) + edit:set(bx, yy, bz, 0, 0) + end + floorY = floorY + 1 + end + end + end + end end + end + edit:commit() +end + +-- ------------------------------------------------------------ item events +local function is_op(player) return player:is_op() end + +-- Adjacent block a right click would have placed (to refresh nothing here, server does it) +mc.on("block_break", function(player, x, y, z, tile) + if not is_op(player) then return end + local s = W.session(player) + local item = held_id(player) + + if item == WAND and not s.wand_off then + set_pos(player, 1, { x, y, z }) + return false + end + if item == NAVWAND and not s.wand_off then + player:teleport(x + 0.5, y + 1, z + 0.5) + return false + end + local tool = s.tools[item] + if tool and tool.type == "wand" then + set_pos(player, 1, { x, y, z }) + return false + elseif tool and tool.type == "nav" then + player:teleport(x + 0.5, y + 1, z + 0.5) + return false + end + + -- super pickaxe + if s.superpick and PICKAXES[item] then + local edit = W.new_edit(s) + if s.superpick == "single" then + edit:set(x, y, z, 0, 0) + elseif s.superpick == "area" then + local r = s.superpick_range + for dx = -r, r do for dy = -r, r do for dz = -r, r do + if dx * dx + dy * dy + dz * dz <= r * r then edit:set(x + dx, y + dy, z + dz, 0, 0) end + end end end + else + local r = s.superpick_range + local seen, queue, head = {}, { { x, y, z } }, 1 + seen[(x * 4096 + z) * 256 + y] = true + while head <= #queue do + local p = queue[head]; head = head + 1 + if get_block(p[1], p[2], p[3]) == tile then + edit:set(p[1], p[2], p[3], 0, 0) + for _, n in ipairs({ { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 0, 1 }, { 0, 0, -1 } }) do + local nx, ny, nz = p[1] + n[1], p[2] + n[2], p[3] + n[3] + local k = (nx * 4096 + nz) * 256 + ny + if not seen[k] and abs(nx - x) <= r and abs(ny - y) <= r and abs(nz - z) <= r then + seen[k] = true + queue[#queue + 1] = { nx, ny, nz } + end + end + end + end + end + edit:commit() + return false + end +end) + +mc.on("use_item", function(player, x, y, z, face, item, aux) + if not is_op(player) then return end + local s = W.session(player) + + if item == WAND and not s.wand_off then + set_pos(player, 2, { x, y, z }) + return false + end + if item == NAVWAND and not s.wand_off then + -- /thru + local px, py, pz = player:pos() + local _, dx, dz = player:facing() + local bx, by, bz = floor(px), floor(py), floor(pz) + local inWall = false + for i = 1, 100 do + local cx, cz = bx + dx * i, bz + dz * i + if not free(cx, by, cz) or not free(cx, by + 1, cz) then inWall = true + elseif inWall then player:teleport(cx + 0.5, by, cz + 0.5); break end + end + return false + end + + local tool = s.tools[item] + if not tool then return end + if tool.type == "repl" then + local e = W.new_edit(s) + e:place(x, y, z, tool.pattern) + e:commit() + return false + elseif tool.type == "info" then + local id, d = get_block(x, y, z) + player:say(string.format("%s (%d:%d) at (%d, %d, %d)", mc.block.name(id), id, d, x, y, z)) + return false + elseif tool.type == "wand" then + set_pos(player, 2, { x, y, z }) + return false + elseif tool.type == "nav" then + return false + elseif tool.type == "flood" then + local e = W.new_edit(s) + local target = get_block(x, y, z) + local seen, queue, head = {}, { { x, y, z } }, 1 + seen[(x * 4096 + z) * 256 + y] = true + while head <= #queue do + local p = queue[head]; head = head + 1 + e:place(p[1], p[2], p[3], tool.pattern) + for _, n in ipairs({ { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 0, 1 }, { 0, 0, -1 } }) do + local nx, ny, nz = p[1] + n[1], p[2] + n[2], p[3] + n[3] + local k = (nx * 4096 + nz) * 256 + ny + if not seen[k] and abs(nx - x) <= tool.range and abs(ny - y) <= tool.range and abs(nz - z) <= tool.range + and get_block(nx, ny, nz) == target then + seen[k] = true + queue[#queue + 1] = { nx, ny, nz } + end + end + end + e:commit() + return false + elseif tool.type == "farwand" then + set_pos(player, 2, { x, y, z }) + return false + elseif tool.type == "deltree" then + local e = W.new_edit(s) + local seen, queue, head = {}, { { x, y, z } }, 1 + while head <= #queue and #queue < 4000 do + local p = queue[head]; head = head + 1 + local id = get_block(p[1], p[2], p[3]) + if id == 17 or id == 18 then + e:set(p[1], p[2], p[3], 0, 0) + for _, n in ipairs({ { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 }, { 0, 0, 1 }, { 0, 0, -1 } }) do + local nx, ny, nz = p[1] + n[1], p[2] + n[2], p[3] + n[3] + local k = (nx * 4096 + nz) * 256 + ny + if not seen[k] then seen[k] = true; queue[#queue + 1] = { nx, ny, nz } end + end + end + end + e:commit() + return false + elseif tool.type == "brush" then + use_brush(player, s, tool, x, y, z) + return false + end +end) + +mc.log("WorldEdit loaded: " .. #mc._command_names() .. " commands registered") diff --git a/package-windows.ps1 b/package-windows.ps1 new file mode 100644 index 0000000..b1e78f9 --- /dev/null +++ b/package-windows.ps1 @@ -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" diff --git a/src/SharedConstants.h b/src/SharedConstants.h index f97ea36..e9394c5 100755 --- a/src/SharedConstants.h +++ b/src/SharedConstants.h @@ -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; diff --git a/src/client/Minecraft.cpp b/src/client/Minecraft.cpp index ded2191..eba68a1 100755 --- a/src/client/Minecraft.cpp +++ b/src/client/Minecraft.cpp @@ -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 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; diff --git a/src/client/gamemode/GameMode.cpp b/src/client/gamemode/GameMode.cpp index 8009d64..0092c50 100755 --- a/src/client/gamemode/GameMode.cpp +++ b/src/client/gamemode/GameMode.cpp @@ -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); diff --git a/src/client/gui/screens/ConsoleScreen.cpp b/src/client/gui/screens/ConsoleScreen.cpp index 9d3e874..8eae25f 100644 --- a/src/client/gui/screens/ConsoleScreen.cpp +++ b/src/client/gui/screens/ConsoleScreen.cpp @@ -9,6 +9,17 @@ #include "../../../network/packet/MessagePacket.h" #include "../../../platform/log.h" #include "util/StringUtils.h" +#include "../../../network/packet/SetSkinPacket.h" +#include +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif #include #include @@ -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|]: 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 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 , 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 // --------------------------------------------------------------------------- diff --git a/src/client/gui/screens/ConsoleScreen.h b/src/client/gui/screens/ConsoleScreen.h index f0c1fd5..80fd859 100644 --- a/src/client/gui/screens/ConsoleScreen.h +++ b/src/client/gui/screens/ConsoleScreen.h @@ -25,6 +25,7 @@ public: private: void execute(); + void executeSkinCommand(const std::string& arg); std::string _input; int _cursorBlink; // tick counter for cursor blink diff --git a/src/client/player/LocalPlayer.cpp b/src/client/player/LocalPlayer.cpp index 29ccf44..738b513 100755 --- a/src/client/player/LocalPlayer.cpp +++ b/src/client/player/LocalPlayer.cpp @@ -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 diff --git a/src/client/renderer/Chunk.cpp b/src/client/renderer/Chunk.cpp index 527508a..0d98df5 100755 --- a/src/client/renderer/Chunk.cpp +++ b/src/client/renderer/Chunk.cpp @@ -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); diff --git a/src/client/renderer/LevelRenderer.cpp b/src/client/renderer/LevelRenderer.cpp index 1ce3ffd..4b804a5 100755 --- a/src/client/renderer/LevelRenderer.cpp +++ b/src/client/renderer/LevelRenderer.cpp @@ -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; diff --git a/src/client/sound/MusicPlayer.cpp b/src/client/sound/MusicPlayer.cpp new file mode 100644 index 0000000..366a635 --- /dev/null +++ b/src/client/sound/MusicPlayer.cpp @@ -0,0 +1,228 @@ +#include "MusicPlayer.h" + +#if defined(PLATFORM_DESKTOP) && !defined(NO_SOUND) + +#include +#include + +#define STB_VORBIS_HEADER_ONLY +#include "stb_vorbis.c" + +#include +#include +#include + +#include "../../platform/log.h" + +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#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 >(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 diff --git a/src/client/sound/MusicPlayer.h b/src/client/sound/MusicPlayer.h new file mode 100644 index 0000000..bb83702 --- /dev/null +++ b/src/client/sound/MusicPlayer.h @@ -0,0 +1,48 @@ +#pragma once + +#include +#include + +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 tracks; + std::string trackName; + + unsigned int source; + unsigned int buffers[4]; + stb_vorbis* decoder; + int channels; + int sampleRate; + std::vector pcm; + bool decoderDone; +}; diff --git a/src/client/sound/SoundEngine.cpp b/src/client/sound/SoundEngine.cpp index 2f847fb..d6e43d9 100755 --- a/src/client/sound/SoundEngine.cpp +++ b/src/client/sound/SoundEngine.cpp @@ -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; diff --git a/src/client/sound/SoundEngine.h b/src/client/sound/SoundEngine.h index bf3d131..3d2220e 100755 --- a/src/client/sound/SoundEngine.h +++ b/src/client/sound/SoundEngine.h @@ -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; diff --git a/src/commands/CommandManager.cpp b/src/commands/CommandManager.cpp index 16b331c..b82a640 100644 --- a/src/commands/CommandManager.cpp +++ b/src/commands/CommandManager.cpp @@ -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 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 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); } diff --git a/src/lua/LuaEngine.cpp b/src/lua/LuaEngine.cpp new file mode 100644 index 0000000..d3aad99 --- /dev/null +++ b/src/lua/LuaEngine.cpp @@ -0,0 +1,628 @@ +#include "LuaEngine.h" + +extern "C" { +#include "lua.h" +#include "lauxlib.h" +#include "lualib.h" +} + +#include +#include +#include +#include +#include +#include +#include + +#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 +#include +#define MKDIR(p) _mkdir(p) +#else +#include +#include +#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 g_dirty; + +void markDirty(int x, int y, int z) { + const long long key = LevelConstants::chunkKey(x >> 4, z >> 4); + std::map::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::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& 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 LuaEngine::commandNames() { + std::vector 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; +} diff --git a/src/lua/LuaEngine.h b/src/lua/LuaEngine.h new file mode 100644 index 0000000..d5049d6 --- /dev/null +++ b/src/lua/LuaEngine.h @@ -0,0 +1,50 @@ +#pragma once + +#include +#include + +class Minecraft; +class Player; +class ItemInstance; +struct lua_State; + +/** + * LuaJIT mod host. Mods live in "mods//main.lua" (or "mods/.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& args, std::string& reply); + std::vector 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; +}; diff --git a/src/main_dedicated.cpp b/src/main_dedicated.cpp index 5e27cd3..87b45be 100755 --- a/src/main_dedicated.cpp +++ b/src/main_dedicated.cpp @@ -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(); diff --git a/src/network/ClientSideNetworkHandler.cpp b/src/network/ClientSideNetworkHandler.cpp index e2b8150..d0fee5f 100755 --- a/src/network/ClientSideNetworkHandler.cpp +++ b/src/network/ClientSideNetworkHandler.cpp @@ -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& a, const std::pair& 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 victims; + for (std::set::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::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; } diff --git a/src/network/ClientSideNetworkHandler.h b/src/network/ClientSideNetworkHandler.h index 57e0d81..e68f58d 100755 --- a/src/network/ClientSideNetworkHandler.h +++ b/src/network/ClientSideNetworkHandler.h @@ -7,6 +7,7 @@ #include "../world/level/LevelConstants.h" #include +#include 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 requestNextChunkIndexList; - std::vector chunksLoaded; + // The world is infinite: only the chunks around the player are kept. + std::set requestedChunks; // asked from the server, data not here yet + std::set loadedChunks; // data received and applied + bool initialLoadDone; + int initialPending; + std::vector > spiral; + int spiralRadius; }; #endif diff --git a/src/network/NetEventCallback.h b/src/network/NetEventCallback.h index db3e22b..3a05a9d 100755 --- a/src/network/NetEventCallback.h +++ b/src/network/NetEventCallback.h @@ -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) {} diff --git a/src/network/Packet.cpp b/src/network/Packet.cpp index d060356..b83d54a 100755 --- a/src/network/Packet.cpp +++ b/src/network/Packet.cpp @@ -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; diff --git a/src/network/Packet.h b/src/network/Packet.h index 3525bd4..d1f6849 100755 --- a/src/network/Packet.h +++ b/src/network/Packet.h @@ -88,6 +88,8 @@ enum MinecraftPacketIds PACKET_SIGNUPDATE, PACKET_ADVENTURESETTINGS, + + PACKET_SETSKIN, /* PACKET_PRELOGIN, PACKET_CHAT, diff --git a/src/network/ServerSideNetworkHandler.cpp b/src/network/ServerSideNetworkHandler.cpp index 7863e37..fb8099a 100755 --- a/src/network/ServerSideNetworkHandler.cpp +++ b/src/network/ServerSideNetworkHandler.cpp @@ -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; diff --git a/src/network/ServerSideNetworkHandler.h b/src/network/ServerSideNetworkHandler.h index c1cb632..d2a2858 100755 --- a/src/network/ServerSideNetworkHandler.h +++ b/src/network/ServerSideNetworkHandler.h @@ -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); diff --git a/src/network/command/CommandServer.cpp b/src/network/command/CommandServer.cpp index 3bcbbc1..3deaa8a 100755 --- a/src/network/command/CommandServer.cpp +++ b/src/network/command/CommandServer.cpp @@ -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) diff --git a/src/network/packet/PacketInclude.h b/src/network/packet/PacketInclude.h index ff884d2..0ae79e8 100755 --- a/src/network/packet/PacketInclude.h +++ b/src/network/packet/PacketInclude.h @@ -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" diff --git a/src/network/packet/SetSkinPacket.h b/src/network/packet/SetSkinPacket.h new file mode 100644 index 0000000..1f48ed7 --- /dev/null +++ b/src/network/packet/SetSkinPacket.h @@ -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/.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__*/ diff --git a/src/world/entity/Entity.cpp b/src/world/entity/Entity.cpp index 47ac1d8..e32694b 100755 --- a/src/world/entity/Entity.cpp +++ b/src/world/entity/Entity.cpp @@ -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; diff --git a/src/world/entity/player/Player.h b/src/world/entity/player/Player.h index 6f69b01..3b2fb5d 100755 --- a/src/world/entity/player/Player.h +++ b/src/world/entity/player/Player.h @@ -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; diff --git a/src/world/level/ChunkPos.h b/src/world/level/ChunkPos.h index 8f3140b..5272f5a 100755 --- a/src/world/level/ChunkPos.h +++ b/src/world/level/ChunkPos.h @@ -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 { diff --git a/src/world/level/Level.cpp b/src/world/level/Level.cpp index 522bad1..a1f3bf9 100755 --- a/src/world/level/Level.cpp +++ b/src/world/level/Level.cpp @@ -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); } // diff --git a/src/world/level/Level.h b/src/world/level/Level.h index e9b9294..d8a2ad9 100755 --- a/src/world/level/Level.h +++ b/src/world/level/Level.h @@ -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& zombies); /*virtual*/ void entityAdded(Entity* e); diff --git a/src/world/level/LevelConstants.cpp b/src/world/level/LevelConstants.cpp index 6a36246..b4a51f6 100644 --- a/src/world/level/LevelConstants.cpp +++ b/src/world/level/LevelConstants.cpp @@ -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; \ No newline at end of file +int LevelConstants::CHUNK_BLOCK_COUNT = LevelConstants::CHUNK_COLUMNS * LevelConstants::LEVEL_HEIGHT; diff --git a/src/world/level/LevelConstants.h b/src/world/level/LevelConstants.h index ed77861..a0d62b9 100755 --- a/src/world/level/LevelConstants.h +++ b/src/world/level/LevelConstants.h @@ -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; -}; \ No newline at end of file +#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; + } +}; diff --git a/src/world/level/MobSpawner.cpp b/src/world/level/MobSpawner.cpp index 5e5dc90..9381562 100755 --- a/src/world/level/MobSpawner.cpp +++ b/src/world/level/MobSpawner.cpp @@ -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 )); } } diff --git a/src/world/level/chunk/ChunkCache.cpp b/src/world/level/chunk/ChunkCache.cpp new file mode 100644 index 0000000..dbfada9 --- /dev/null +++ b/src/world/level/chunk/ChunkCache.cpp @@ -0,0 +1,380 @@ +#include "ChunkCache.h" + +#include +#include +#include + +#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 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& 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& a, const std::pair& 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 > 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 > 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 > 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 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(); +} diff --git a/src/world/level/chunk/ChunkCache.h b/src/world/level/chunk/ChunkCache.h index fbb2d77..0462d00 100755 --- a/src/world/level/chunk/ChunkCache.h +++ b/src/world/level/chunk/ChunkCache.h @@ -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 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 +#include +#include + +#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& 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 ChunkMap; + ChunkMap chunks; + + LevelChunk* emptyChunk; + ChunkSource* source; + ChunkStorage* storage; + Level* level; + + LevelChunk* last; + + int tickCount; + int unloadRadiusCache; + std::vector > spiral; // chunk offsets sorted by distance + int spiralRadius; + unsigned int playerRoundRobin; + std::deque autosaveQueue; +}; + +#endif /*NET_MINECRAFT_WORLD_LEVEL_CHUNK__ChunkCache_H__*/ diff --git a/src/world/level/chunk/ChunkSource.h b/src/world/level/chunk/ChunkSource.h index c1e029f..0cf1b75 100755 --- a/src/world/level/chunk/ChunkSource.h +++ b/src/world/level/chunk/ChunkSource.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 -#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 +#include +#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& 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__*/ diff --git a/src/world/level/chunk/LevelChunk.cpp b/src/world/level/chunk/LevelChunk.cpp index fd61715..528a228 100755 --- a/src/world/level/chunk/LevelChunk.cpp +++ b/src/world/level/chunk/LevelChunk.cpp @@ -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& 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; diff --git a/src/world/level/chunk/LevelChunk.h b/src/world/level/chunk/LevelChunk.h index 8fe7281..65fa412 100755 --- a/src/world/level/chunk/LevelChunk.h +++ b/src/world/level/chunk/LevelChunk.h @@ -16,6 +16,7 @@ class Entity; class LightLayer; class AABB; class TileEntity; +class CompoundTag; typedef std::vector 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& 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; diff --git a/src/world/level/levelgen/RandomLevelSource.cpp b/src/world/level/levelgen/RandomLevelSource.cpp index dbaa87b..09ed7e1 100755 --- a/src/world/level/levelgen/RandomLevelSource.cpp +++ b/src/world/level/levelgen/RandomLevelSource.cpp @@ -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()) diff --git a/src/world/level/levelgen/RandomLevelSource.h b/src/world/level/levelgen/RandomLevelSource.h index e8b88e4..ebdc0a0 100755 --- a/src/world/level/levelgen/RandomLevelSource.h +++ b/src/world/level/levelgen/RandomLevelSource.h @@ -7,20 +7,9 @@ class Biome; class Level; class LevelChunk; -#if 1 || USE_MAP - #include - typedef std::map ChunkMap; -#else - #if defined(__APPLE__) - #include - namespace std { - using namespace __gnu_cxx; - } - #else - #include - #endif - typedef std::hash_map ChunkMap; -#endif +#include +// Keyed by LevelConstants::chunkKey(x, z) +typedef std::map 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); diff --git a/src/world/level/storage/ExternalFileLevelStorage.cpp b/src/world/level/storage/ExternalFileLevelStorage.cpp index 93ee9f1..d31c50c 100755 --- a/src/world/level/storage/ExternalFileLevelStorage.cpp +++ b/src/world/level/storage/ExternalFileLevelStorage.cpp @@ -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::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::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::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* 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 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& levelChunks ) { ChunkStorage::saveAll(level, levelChunks); - int numChunks = savePendingUnsavedChunks(-1); - LOGI("Saving %d additional chunks.\n", numChunks); } #endif /*DEMO_MODE*/ diff --git a/src/world/level/storage/ExternalFileLevelStorage.h b/src/world/level/storage/ExternalFileLevelStorage.h index 9aad448..f817c15 100755 --- a/src/world/level/storage/ExternalFileLevelStorage.h +++ b/src/world/level/storage/ExternalFileLevelStorage.h @@ -7,6 +7,7 @@ #include #include +#include //#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 UnsavedChunkList; - /*public*/ class ExternalFileLevelStorage: public LevelStorage, @@ -54,16 +45,15 @@ public: static bool writeLevelData(const std::string& datFileName, LevelData& dest, const std::vector* players); static void saveLevelData(const std::string& directory, LevelData& levelData, std::vector* 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& 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 regionOrder; + std::map regions; Level* level; int tickCount; int loadedStorageVersion; - UnsavedChunkList unsavedChunkList; - int lastSavedEntitiesTick; }; #endif /*NET_MINECRAFT_WORLD_LEVEL_STORAGE__ExternalFileLevelStorage_H__*/ diff --git a/src/world/level/storage/RegionFile.cpp b/src/world/level/storage/RegionFile.cpp index 3edecce..cf08087 100755 --- a/src/world/level/storage/RegionFile.cpp +++ b/src/world/level/storage/RegionFile.cpp @@ -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]; diff --git a/src/world/level/storage/RegionFile.h b/src/world/level/storage/RegionFile.h index 3d743ef..2b9e1f2 100755 --- a/src/world/level/storage/RegionFile.h +++ b/src/world/level/storage/RegionFile.h @@ -1,31 +1,38 @@ -#ifndef NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__ -#define NET_MINECRAFT_WORLD_LEVEL_STORAGE__RegionFile_H__ - -#include -#include -#include "../../../raknet/BitStream.h" - -typedef std::map 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 +#include +#include "../../../raknet/BitStream.h" + +typedef std::map 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__*/ diff --git a/src/world/level/tile/Tile.cpp b/src/world/level/tile/Tile.cpp index 6736bc7..b4948ba 100755 --- a/src/world/level/tile/Tile.cpp +++ b/src/world/level/tile/Tile.cpp @@ -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; diff --git a/src/world/level/tile/entity/NetherReactorTileEntity.cpp b/src/world/level/tile/entity/NetherReactorTileEntity.cpp index 5b4728a..07a89c1 100755 --- a/src/world/level/tile/entity/NetherReactorTileEntity.cpp +++ b/src/world/level/tile/entity/NetherReactorTileEntity.cpp @@ -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()); diff --git a/tools/convert-music.ps1 b/tools/convert-music.ps1 new file mode 100644 index 0000000..1432469 --- /dev/null +++ b/tools/convert-music.ps1 @@ -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 + } +}