diff --git a/.gitignore b/.gitignore index 028faf9..5465697 100644 --- a/.gitignore +++ b/.gitignore @@ -200,10 +200,3 @@ 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 df8b711..b978db0 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,6 @@ 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 @@ -100,16 +99,6 @@ 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" @@ -207,7 +196,6 @@ 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" @@ -229,7 +217,6 @@ file(GLOB SERVER_SOURCES "src/world/phys/HitResult.cpp" "src/commands/*.cpp" - "src/lua/*.cpp" ) file(GLOB CLIENT_SOURCES @@ -315,11 +302,10 @@ 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 "${stb_SOURCE_DIR}/stb_vorbis.c") + list(APPEND CLIENT_SOURCES glad/src/glad.c) endif() # Server @@ -332,13 +318,7 @@ 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} 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" -) +target_link_libraries("${PROJECT_NAME}-server" ${CMAKE_THREAD_LIBS_INIT} ${EXTRA_LIBS}) add_executable(${PROJECT_NAME} ${CLIENT_SOURCES}) @@ -353,7 +333,6 @@ target_include_directories(${PROJECT_NAME} PUBLIC "${CMAKE_SOURCE_DIR}/src" "${openal_SOURCE_DIR}/include" "${glfw_SOURCE_DIR}/include" - "${stb_SOURCE_DIR}" "lib/include" ) @@ -402,7 +381,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} luajit) +target_link_libraries(${PROJECT_NAME} zlib ${PNG_LIB} OpenAL::OpenAL glfw ${EXTRA_LIBS}) if (OpenSSL_FOUND) target_link_libraries(${PROJECT_NAME} OpenSSL::SSL OpenSSL::Crypto) @@ -423,8 +402,6 @@ 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 9b2fc0c..1d4caa8 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # MinecraftPE > [!Warning] -> [Github repository](https://github.com/Minecraft-PE-0-6-1/minecraft-pe-0.6.1-on-all) **isnt main**. All issues and pull requests should be send in [Gitea Repository](https://gitea.sffnetwork.ru/Kolyah35/minecraft-pe-0.6.1). +> [Github repository](https://github.com/Minecraft-PE-0-6-1/minecraft-pe-0.6.1-on-all) **isnt main**. All issues and pull requests should be send in [Gitea Repository](https://gitea.sffempire.ru/Kolyah35/minecraft-pe-0.6.1). -> [!Note] -> There is unofficial (not related to Kolyah35 and InviseDivine) discord server, where you can report bugs or send feedback https://discord.gg/udYrbNDfDH +> [!Important] +> We have a discord server, where you can report bugs or send feedback https://discord.gg/c58YesBxve Source code for **Minecraft Pocket Edition 0.6.1 alpha** with various fixes and improvements. @@ -17,32 +17,13 @@ This project aims to preserve and improve this early version of Minecraft PE. # Screenshots

-menu -settings -worlds -gameplay +menu +settings +worlds +gameplay

- -# 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 deleted file mode 100644 index 5d1f4c0..0000000 --- a/cmake/LuaJIT.cmake +++ /dev/null @@ -1,70 +0,0 @@ -# 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 deleted file mode 100644 index aef7319..0000000 Binary files a/data/images/skins/blonde.png and /dev/null differ diff --git a/data/images/skins/green.png b/data/images/skins/green.png deleted file mode 100644 index 7a9b1fe..0000000 Binary files a/data/images/skins/green.png and /dev/null differ diff --git a/data/images/skins/ninja.png b/data/images/skins/ninja.png deleted file mode 100644 index 9976e3a..0000000 Binary files a/data/images/skins/ninja.png and /dev/null differ diff --git a/data/images/skins/orange.png b/data/images/skins/orange.png deleted file mode 100644 index 8f9ab49..0000000 Binary files a/data/images/skins/orange.png and /dev/null differ diff --git a/data/images/skins/pink.png b/data/images/skins/pink.png deleted file mode 100644 index 9df5556..0000000 Binary files a/data/images/skins/pink.png and /dev/null differ diff --git a/data/images/skins/purple.png b/data/images/skins/purple.png deleted file mode 100644 index e068bc2..0000000 Binary files a/data/images/skins/purple.png and /dev/null differ diff --git a/data/images/skins/red.png b/data/images/skins/red.png deleted file mode 100644 index adde5ca..0000000 Binary files a/data/images/skins/red.png and /dev/null differ diff --git a/data/images/skins/snow.png b/data/images/skins/snow.png deleted file mode 100644 index 1a5b305..0000000 Binary files a/data/images/skins/snow.png and /dev/null differ diff --git a/data/images/skins/steve.png b/data/images/skins/steve.png deleted file mode 100644 index 555fb11..0000000 Binary files a/data/images/skins/steve.png and /dev/null differ diff --git a/data/images/skins/yellow.png b/data/images/skins/yellow.png deleted file mode 100644 index 66692d9..0000000 Binary files a/data/images/skins/yellow.png and /dev/null differ diff --git a/lua/prelude.lua b/lua/prelude.lua deleted file mode 100644 index fb6483c..0000000 --- a/lua/prelude.lua +++ /dev/null @@ -1,404 +0,0 @@ --- ============================================================================ --- MinecraftPE Lua API (LuaJIT) --- This file is loaded by the game before any mod. It builds the friendly --- `mc` API on top of the native primitives (mc._*) that the game provides. --- Documentation: mods/README.md --- ============================================================================ - -local mc = mc -mc.VERSION = "1.0" - -local floor, max, min = math.floor, math.max, math.min - --- ---------------------------------------------------------------- utilities -mc.util = {} - -function mc.util.split(s, sep) - local out = {} - sep = sep or "%s+" - for piece in string.gmatch(s, "([^" .. (sep == "%s+" and "%s" or sep) .. "]+)") do - out[#out + 1] = piece - end - return out -end - -function mc.util.copy(t) - local c = {} - for k, v in pairs(t) do c[k] = v end - return c -end - -local function serialize(v, indent) - local t = type(v) - if t == "number" or t == "boolean" then return tostring(v) end - if t == "string" then return string.format("%q", v) end - if t == "table" then - local parts = {} - for k, val in pairs(v) do - parts[#parts + 1] = "[" .. serialize(k) .. "]=" .. serialize(val) - end - return "{" .. table.concat(parts, ",") .. "}" - end - return "nil" -end - ---- Saves a plain Lua table (numbers, strings, booleans, tables) to a file. -function mc.save_table(path, tbl) - local f, err = io.open(path, "w") - if not f then return false, err end - f:write("return ", serialize(tbl)) - f:close() - return true -end - ---- Loads a table written by mc.save_table, or returns `default`. -function mc.load_table(path, default) - local chunk = loadfile(path) - if not chunk then return default end - setfenv(chunk, {}) - local ok, res = pcall(chunk) - if ok then return res end - return default -end - -function mc.log(...) - local parts = {} - for i = 1, select("#", ...) do parts[i] = tostring((select(i, ...))) end - mc._log(table.concat(parts, " ")) -end - --- ------------------------------------------------------------------ blocks -local BLOCKS = { - [0] = "air", [1] = "stone", [2] = "grass", [3] = "dirt", [4] = "cobblestone", [5] = "planks", - [6] = "sapling", [7] = "bedrock", [8] = "flowing_water", [9] = "water", [10] = "flowing_lava", - [11] = "lava", [12] = "sand", [13] = "gravel", [14] = "gold_ore", [15] = "iron_ore", - [16] = "coal_ore", [17] = "log", [18] = "leaves", [20] = "glass", [21] = "lapis_ore", - [22] = "lapis_block", [24] = "sandstone", [26] = "bed", [30] = "cobweb", [31] = "tallgrass", - [35] = "wool", [37] = "dandelion", [38] = "rose", [39] = "brown_mushroom", [40] = "red_mushroom", - [41] = "gold_block", [42] = "iron_block", [43] = "double_slab", [44] = "slab", [45] = "bricks", - [46] = "tnt", [47] = "bookshelf", [48] = "mossy_cobblestone", [49] = "obsidian", [50] = "torch", - [51] = "fire", [53] = "oak_stairs", [54] = "chest", [56] = "diamond_ore", [57] = "diamond_block", - [58] = "crafting_table", [59] = "wheat", [60] = "farmland", [61] = "furnace", [62] = "lit_furnace", - [63] = "sign", [64] = "wooden_door", [65] = "ladder", [67] = "stone_stairs", [68] = "wall_sign", - [71] = "iron_door", [73] = "redstone_ore", [74] = "lit_redstone_ore", [78] = "snow_layer", - [79] = "ice", [80] = "snow", [81] = "cactus", [82] = "clay", [83] = "reeds", [85] = "fence", - [86] = "pumpkin", [87] = "netherrack", [89] = "glowstone", [91] = "jack_o_lantern", - [96] = "trapdoor", [98] = "stonebrick", [102] = "glass_pane", [103] = "melon", [105] = "melon_stem", - [107] = "fence_gate", [108] = "brick_stairs", [109] = "stonebrick_stairs", [112] = "nether_brick", - [114] = "nether_brick_stairs", [128] = "sandstone_stairs", [129] = "emerald_ore", - [133] = "emerald_block", [155] = "quartz_block", [156] = "quartz_stairs", [245] = "stonecutter", - [246] = "glowing_obsidian", [247] = "nether_reactor", -} - -local ALIASES = { - rock = 1, smooth_stone = 1, grass_block = 2, cobble = 4, wood = 5, wood_planks = 5, oak_planks = 5, - planks = 5, sapling = 6, adminium = 7, bed_rock = 7, water = 9, still_water = 9, stationary_water = 9, - lava = 11, still_lava = 11, stationary_lava = 11, flowing_water = 8, flowing_lava = 10, - gold = 14, iron = 15, coal = 16, trunk = 17, tree = 17, wood_log = 17, oak_log = 17, leaf = 18, - leaves = 18, lapis = 21, sandstone = 24, web = 30, grass_plant = 31, cloth = 35, flower = 37, - yellow_flower = 37, red_flower = 38, goldblock = 41, ironblock = 42, brick = 45, bricks = 45, - mossy = 48, mossy_cobble = 48, moss = 48, obsidian = 49, torch = 50, fire = 51, chest = 54, - diamond = 56, workbench = 58, crafting = 58, table = 58, furnace = 61, ladder = 65, ice = 79, - snowblock = 80, snow_block = 80, cactus = 81, clay = 82, sugarcane = 83, fence = 85, glowstone = 89, - lightstone = 89, netherrack = 87, hell = 87, stonebricks = 98, stone_brick = 98, stone_bricks = 98, - melon = 103, quartz = 155, door = 64, iron_door = 71, tnt = 46, bookshelf = 47, books = 47, - glass = 20, sand = 12, gravel = 13, dirt = 3, stone = 1, grass = 2, bedrock = 7, - pane = 102, trap_door = 96, pumpkin = 86, lantern = 91, stair = 53, stairs = 53, double_step = 43, - step = 44, half_slab = 44, slab = 44, double_slab = 43, farmland = 60, soil = 60, -} - -local WOOL = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", - "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" } -local WOOL_DATA = {} -for i, name in ipairs(WOOL) do - WOOL_DATA[name] = i - 1 - ALIASES[name .. "_wool"] = { 35, i - 1 } -end - -local NAME_TO_ID = {} -for id, name in pairs(BLOCKS) do NAME_TO_ID[name] = id end - -mc.block = { ids = NAME_TO_ID, names = BLOCKS } - ---- Name of a block id ("stone"), or the number as a string. -function mc.block.name(id) - return BLOCKS[id] or tostring(id) -end - ---- Parses "stone", "35:14", "red_wool", "log:1" -> id, data (data is nil when not given) -function mc.block.parse(text) - text = string.lower(text) - local nameOrId, data = string.match(text, "^([%w_]+):(%d+)$") - if nameOrId then data = tonumber(data) else nameOrId = text end - local id = tonumber(nameOrId) - if not id then - local alias = ALIASES[nameOrId] - if type(alias) == "table" then - id, data = alias[1], data or alias[2] - else - id = alias or NAME_TO_ID[nameOrId] - end - end - if not id or id < 0 or id > 255 then return nil end - return id, data -end - --- Blocks that are not solid ground (used by e.g. //green, //naturalize, //ascend) -mc.block.AIR = 0 - --- ------------------------------------------------------------------- items -mc.item = { - stick = 280, compass = 345, wooden_axe = 271, wooden_pickaxe = 270, wooden_shovel = 269, - wooden_sword = 268, stone_axe = 275, iron_axe = 258, diamond_axe = 279, flint_and_steel = 259, - apple = 260, bow = 261, arrow = 262, coal = 263, diamond = 264, iron_ingot = 265, gold_ingot = 266, - bucket = 325, water_bucket = 326, lava_bucket = 327, clock = 347, paper = 339, book = 340, -} - -mc.mob = { chicken = 10, cow = 11, pig = 12, sheep = 13, zombie = 32, creeper = 33, - skeleton = 34, spider = 35, pig_zombie = 36 } - --- ------------------------------------------------------------------ players -local Player = {} -Player.__index = Player -local playerCache = {} - -local function getPlayer(id) - if not id then return nil end - local p = playerCache[id] - if not p then - local name = mc._pname(id) - if not name then return nil end - p = setmetatable({ id = id, name = name, data = {} }, Player) - playerCache[id] = p - end - return p -end -mc._player = getPlayer - -function Player:__tostring() return "Player(" .. self.name .. ")" end - ---- Feet position: x, y, z -function Player:pos() local x, y, z = mc._ppos(self.id); return x, y, z end ---- Block the feet are in -function Player:block_pos() - local x, y, z = mc._ppos(self.id) - return floor(x), floor(y), floor(z) -end ---- yaw, pitch in degrees -function Player:look() local _, _, _, yaw, pitch = mc._ppos(self.id); return yaw, pitch end ---- Horizontal facing as 0..3 (south, west, north, east) and its unit vector -function Player:facing() - local yaw = self:look() - local dir = floor(((yaw % 360) + 45) / 90) % 4 - local vec = { [0] = { 0, 1 }, [1] = { -1, 0 }, [2] = { 0, -1 }, [3] = { 1, 0 } } - return dir, vec[dir][1], vec[dir][2] -end -function Player:teleport(x, y, z, yaw, pitch) mc._pteleport(self.id, x, y, z, yaw, pitch) end -function Player:say(...) - local parts = {} - for i = 1, select("#", ...) do parts[i] = tostring((select(i, ...))) end - local text = table.concat(parts, " ") - for line in string.gmatch(text .. "\n", "(.-)\n") do - if line ~= "" then mc._pmsg(self.id, line) end - end -end -function Player:is_op() return mc._pop(self.id) end ---- id, data, count of the held item (0,0,0 when empty) -function Player:held() return mc._pheld(self.id) end -function Player:give(id, count, data) mc._pgive(self.id, id, count or 1, data or 0) end ---- 0 = survival, 1 = creative -function Player:gamemode() return mc._pgamemode() end ---- x, y, z, face of the block the player is looking at, or nil -function Player:target(distance) return mc._ptrace(self.id, distance or 128) end -function Player:is_online() return mc._pname(self.id) ~= nil end - -mc.Player = Player - -function mc.players() - local list = {} - for i, id in ipairs(mc._players()) do list[i] = getPlayer(id) end - return list -end - -function mc.player(name) - name = string.lower(name) - for _, id in ipairs(mc._players()) do - local p = getPlayer(id) - if p and string.lower(p.name) == name then return p end - end - return nil -end - -function mc.broadcast(text) mc._broadcast(text) end - --- -------------------------------------------------------------------- world -mc.world = {} -local W = mc.world - -W.get_block = mc._get_block -W.set_block = mc._set_block ---- Re-sends/relights everything written with silent set_block calls -W.flush = mc._flush -W.is_loaded = mc._loaded -W.ensure_loaded = mc._ensure -W.seed = mc._seed -W.explode = mc._explode -W.spawn_mob = mc._spawn_mob -W.drop_item = mc._drop_item -W.butcher = mc._butcher -W.height = mc._solid_height -W.get_time = mc._get_time -W.set_time = mc._set_time - --- ---------------------------------------------------------------- scheduler -local tasks, nextTask, tickCount = {}, 1, 0 -mc.tick_count = 0 - -function mc.after(ticks, fn) - local id = nextTask; nextTask = nextTask + 1 - tasks[id] = { at = tickCount + max(1, ticks), fn = fn } - return id -end - -function mc.every(ticks, fn) - local id = nextTask; nextTask = nextTask + 1 - tasks[id] = { at = tickCount + max(1, ticks), fn = fn, period = max(1, ticks) } - return id -end - -function mc.cancel(id) tasks[id] = nil end - --- ------------------------------------------------------------------- events -local handlers = {} - ---- mc.on("block_break", function(player, x, y, z, tile) return false end) ---- Events: start, stop, tick, join, leave, chat, block_break, use_item ---- Returning false from a cancellable event (chat, block_break, use_item) cancels it. -function mc.on(event, fn) - handlers[event] = handlers[event] or {} - table.insert(handlers[event], fn) -end - -local function report(modName, err) - mc._log("error in handler: " .. tostring(err)) -end - -function mc._fire(event, pid, ...) - local list = handlers[event] - if not list then return true end - local first = pid - if pid ~= nil then first = getPlayer(pid) end - local result = true - for i = 1, #list do - local ok, res = xpcall(list[i], debug.traceback, first, ...) - if not ok then - report(nil, res) - elseif res == false then - result = false - end - end - if event == "leave" and pid then playerCache[pid] = nil end - return result -end - -function mc._tick() - tickCount = tickCount + 1 - mc.tick_count = tickCount - for id, task in pairs(tasks) do - if task.at <= tickCount then - if task.period then task.at = tickCount + task.period else tasks[id] = nil end - local ok, err = xpcall(task.fn, debug.traceback) - if not ok then report(nil, err) end - end - end - if handlers.tick then mc._fire("tick") end -end - --- ----------------------------------------------------------------- commands -local commands = {} - ---- mc.command("home", { description = "...", usage = "/home", op = false }, function(ctx) ... end) ---- Names are what the player types after the first slash, so WorldEdit's "//set" is "/set". -function mc.command(name, opts, fn) - if type(opts) == "function" then fn, opts = opts, {} end - commands[string.lower(name)] = { fn = fn, opts = opts or {}, name = name } -end - -function mc._command_names() - local names = {} - for name in pairs(commands) do names[#names + 1] = name end - table.sort(names) - return names -end - -function mc._run_command(pid, name, args) - local cmd = commands[string.lower(name)] - if not cmd then return false end - local player = getPlayer(pid) - if cmd.opts.op and not player:is_op() then - return true, "You are not allowed to use this command." - end - local replies = {} - local ctx = { - player = player, args = args, name = name, - reply = function(_, ...) player:say(...) end, - } - setmetatable(ctx, { __index = function(_, k) return nil end }) - local ok, res = xpcall(cmd.fn, debug.traceback, ctx) - if not ok then - mc._log("command /" .. name .. " failed: " .. tostring(res)) - return true, "Command failed: " .. tostring(res):match("^[^\n]*") - end - if type(res) == "string" then return true, res end - return true -end - --- ------------------------------------------------------------------- mods -mc.mods = {} - -local function listDir(dir) - return mc._listdir and mc._listdir(dir) or {} -end - -local function loadMod(name, dir, file) - local env = setmetatable({}, { __index = _G }) - env.MOD = { name = name, dir = dir } - env.require = function(m) - local path = dir .. "/" .. m:gsub("%.", "/") .. ".lua" - local chunk = loadfile(path) - if chunk then - setfenv(chunk, env) - return chunk() - end - return require(m) - end - local chunk, err = loadfile(file) - if not chunk then - mc._log("cannot load mod '" .. name .. "': " .. tostring(err)) - return - end - setfenv(chunk, env) - local ok, res = xpcall(chunk, debug.traceback) - if not ok then - mc._log("mod '" .. name .. "' failed: " .. tostring(res)) - return - end - mc.mods[name] = env.MOD - mc._log("loaded mod '" .. name .. "'") -end - -function mc._load_mods() - local entries = listDir("mods") - table.sort(entries, function(a, b) return a.name < b.name end) - for _, e in ipairs(entries) do - if e.dir then - local main = "mods/" .. e.name .. "/main.lua" - local f = io.open(main, "r") - if f then f:close(); loadMod(e.name, "mods/" .. e.name, main) end - elseif e.name:match("%.lua$") then - loadMod((e.name:gsub("%.lua$", "")), "mods", "mods/" .. e.name) - end - end - mc._fire("start") - for _, id in ipairs(mc._players()) do mc._fire("join", id) end -end diff --git a/mods/README.md b/mods/README.md deleted file mode 100644 index a083123..0000000 --- a/mods/README.md +++ /dev/null @@ -1,120 +0,0 @@ -# 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 deleted file mode 100644 index 1f4a9bb..0000000 --- a/mods/hello.lua +++ /dev/null @@ -1,22 +0,0 @@ --- 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 deleted file mode 100644 index 3d6ecce..0000000 --- a/mods/worldedit/lib.lua +++ /dev/null @@ -1,450 +0,0 @@ --- 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 deleted file mode 100644 index 6d8ca1d..0000000 --- a/mods/worldedit/main.lua +++ /dev/null @@ -1,1574 +0,0 @@ --- 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 deleted file mode 100644 index b1e78f9..0000000 --- a/package-windows.ps1 +++ /dev/null @@ -1,76 +0,0 @@ -<# - 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 e9394c5..f97ea36 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 = 10; - const int NetworkProtocolLowestSupportedVersion = 10; + const int NetworkProtocolVersion = 9; + const int NetworkProtocolLowestSupportedVersion = 9; const int GameProtocolVersion = 1; const int GameProtocolLowestSupportedVersion = 1; diff --git a/src/client/Minecraft.cpp b/src/client/Minecraft.cpp index eba68a1..ded2191 100755 --- a/src/client/Minecraft.cpp +++ b/src/client/Minecraft.cpp @@ -3,7 +3,6 @@ #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" @@ -224,7 +223,6 @@ Minecraft::~Minecraft() screen = NULL; } #endif - LuaEngine::get().stop(); if (level != NULL) { level->saveGame(); if (level->getChunkSource()) @@ -332,8 +330,6 @@ void Minecraft::leaveGame(bool renameLevel /*=false*/) level->getChunkSource()->saveAll(true); } - LuaEngine::get().stop(); - LOGI("Clearing levels\n"); cameraTargetPlayer = NULL; @@ -379,22 +375,14 @@ void Minecraft::prepareLevel(const std::string& title) { if (!level->isNew()) level->setUpdateLights(false); - // 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 Max = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH; int pp = 0; - for (int cx = spawnCx - PrepareRadius; cx <= spawnCx + PrepareRadius; cx++) { - for (int cz = spawnCz - PrepareRadius; cz <= spawnCz + PrepareRadius; cz++) { - progressStagePercentage = 100 * pp++ / Max; + 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); B.start(); - level->getChunk(cx, cz); + level->getTile(x, 64, z); B.stop(); L.start(); if (level->isNew()) @@ -407,12 +395,11 @@ void Minecraft::prepareLevel(const std::string& title) { level->setUpdateLights(true); C.start(); + for (int x = 0; x < LevelConstants::CHUNK_CACHE_WIDTH; x++) { - std::vector loadedChunks; - level->getChunkSource()->getLoadedChunks(loadedChunks); - for (unsigned int i = 0; i < loadedChunks.size(); i++) + for (int z = 0; z < LevelConstants::CHUNK_CACHE_WIDTH; z++) { - LevelChunk* chunk = loadedChunks[i]; + LevelChunk* chunk = level->getChunk(x, z); if (chunk && !chunk->createdFromSave) { chunk->unsaved = false; @@ -425,6 +412,7 @@ 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(); @@ -582,10 +570,6 @@ 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) { @@ -1489,8 +1473,6 @@ 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); } @@ -1511,11 +1493,6 @@ 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 0092c50..8009d64 100755 --- a/src/client/gamemode/GameMode.cpp +++ b/src/client/gamemode/GameMode.cpp @@ -16,7 +16,6 @@ #include "../renderer/LevelRenderer.h" #endif #include "../../world/level/material/Material.h" -#include "../../lua/LuaEngine.h" GameMode::GameMode( Minecraft* minecraft) : minecraft(minecraft), @@ -60,9 +59,6 @@ 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) { @@ -93,8 +89,6 @@ 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 8eae25f..9d3e874 100644 --- a/src/client/gui/screens/ConsoleScreen.cpp +++ b/src/client/gui/screens/ConsoleScreen.cpp @@ -9,17 +9,6 @@ #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 @@ -74,11 +63,6 @@ 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); @@ -105,62 +89,6 @@ 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 80fd859..f0c1fd5 100644 --- a/src/client/gui/screens/ConsoleScreen.h +++ b/src/client/gui/screens/ConsoleScreen.h @@ -25,7 +25,6 @@ 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 738b513..29ccf44 100755 --- a/src/client/player/LocalPlayer.cpp +++ b/src/client/player/LocalPlayer.cpp @@ -370,18 +370,9 @@ 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 - if (!hasChosenSkin) new CThread(fetchSkinForPlayer, this); + new CThread(fetchSkinForPlayer, this); new CThread(fetchCapeForPlayer, this); } #endif diff --git a/src/client/renderer/Chunk.cpp b/src/client/renderer/Chunk.cpp index 0d98df5..527508a 100755 --- a/src/client/renderer/Chunk.cpp +++ b/src/client/renderer/Chunk.cpp @@ -99,14 +99,6 @@ 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 4b804a5..1ce3ffd 100755 --- a/src/client/renderer/LevelRenderer.cpp +++ b/src/client/renderer/LevelRenderer.cpp @@ -69,8 +69,7 @@ LevelRenderer::LevelRenderer( Minecraft* mc) destroyProgress(0) { #ifdef OPENGL_ES - // enough render chunks for the largest possible view distance (400 blocks, see allChanged) - int maxChunksWidth = 400 / CHUNK_SIZE + 1; + int maxChunksWidth = 2 * LevelConstants::LEVEL_WIDTH / CHUNK_SIZE + 1; numListsOrBuffers = maxChunksWidth * maxChunksWidth * (128/CHUNK_SIZE) * 3; chunkBuffers = new GLuint[numListsOrBuffers]; glGenBuffers2(numListsOrBuffers, chunkBuffers); @@ -210,14 +209,6 @@ 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 deleted file mode 100644 index 366a635..0000000 --- a/src/client/sound/MusicPlayer.cpp +++ /dev/null @@ -1,228 +0,0 @@ -#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 deleted file mode 100644 index bb83702..0000000 --- a/src/client/sound/MusicPlayer.h +++ /dev/null @@ -1,48 +0,0 @@ -#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 d6e43d9..2f847fb 100755 --- a/src/client/sound/SoundEngine.cpp +++ b/src/client/sound/SoundEngine.cpp @@ -169,9 +169,6 @@ 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 3d2220e..bf3d131 100755 --- a/src/client/sound/SoundEngine.h +++ b/src/client/sound/SoundEngine.h @@ -17,10 +17,6 @@ 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; @@ -33,10 +29,6 @@ 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 b82a640..16b331c 100644 --- a/src/commands/CommandManager.cpp +++ b/src/commands/CommandManager.cpp @@ -12,7 +12,6 @@ #include "network/packet/ChatPacket.h" #include "network/RakNetInstance.h" #include "world/level/Level.h" -#include "lua/LuaEngine.h" CommandManager::CommandManager() { registerAllCommands(); @@ -32,9 +31,6 @@ 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; } @@ -49,20 +45,15 @@ 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 deleted file mode 100644 index d3aad99..0000000 --- a/src/lua/LuaEngine.cpp +++ /dev/null @@ -1,628 +0,0 @@ -#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 deleted file mode 100644 index d5049d6..0000000 --- a/src/lua/LuaEngine.h +++ /dev/null @@ -1,50 +0,0 @@ -#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 87b45be..5e27cd3 100755 --- a/src/main_dedicated.cpp +++ b/src/main_dedicated.cpp @@ -91,22 +91,16 @@ int main(int numArguments, char* pszArgs[]) { } port = std::stoi(findStringInConfig("port", propString)); + worldSize = std::stoi(findStringInConfig("world-size", propString)); - // 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; + if (worldSize < 16 || worldSize > 32) { + throw std::runtime_error("Incorrect world size."); } - 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); @@ -122,7 +116,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::VIEW_DISTANCE_CHUNKS); + printf("%d %s %s %d %d\n", port, cachePath.c_str(), externalPath.c_str(), gamemode, LevelConstants::CHUNK_CACHE_WIDTH); } else { std::ofstream defaultProperties("server.properties"); @@ -138,7 +132,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 << "view-distance=10" << std::endl; + buffer << "world-size=16" << std::endl; defaultProperties << buffer.str(); diff --git a/src/network/ClientSideNetworkHandler.cpp b/src/network/ClientSideNetworkHandler.cpp index d0fee5f..e2b8150 100755 --- a/src/network/ClientSideNetworkHandler.cpp +++ b/src/network/ClientSideNetworkHandler.cpp @@ -43,10 +43,12 @@ ClientSideNetworkHandler::ClientSideNetworkHandler(Minecraft* minecraft, IRakNet : minecraft(minecraft), raknetInstance(raknetInstance), level(NULL), - initialLoadDone(false), - initialPending(0), - spiralRadius(-1) + requestNextChunkPosition(0), + requestNextChunkIndex(0) { + NumRequestChunks = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH; + requestNextChunkIndexList.resize(NumRequestChunks); + chunksLoaded.resize(NumRequestChunks); rakPeer = raknetInstance->getPeer(); } @@ -54,93 +56,35 @@ ClientSideNetworkHandler::~ClientSideNetworkHandler() { } -void ClientSideNetworkHandler::requestChunk(int x, int z) +void ClientSideNetworkHandler::requestNextChunk() { - const long long key = LevelConstants::chunkKey(x, z); - if (requestedChunks.count(key) || loadedChunks.count(key)) return; + if (requestNextChunkIndex < NumRequestChunks) + { + IntPair& chunk = requestNextChunkIndexList[requestNextChunkIndex]; + RequestChunkPacket packet(chunk.x, chunk.y); + raknetInstance->send(packet); - RequestChunkPacket packet(x, z); - raknetInstance->send(packet); - requestedChunks.insert(key); + //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)); } bool ClientSideNetworkHandler::isChunkLoaded(int x, int z) { - 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()); + 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; } - - // 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(); + return chunksLoaded[x * LevelConstants::CHUNK_CACHE_WIDTH + z]; + //return areAllChunksLoaded(); } void ClientSideNetworkHandler::onConnect(const RakNet::RakNetGUID& hostGuid) @@ -160,8 +104,10 @@ void ClientSideNetworkHandler::onUnableToConnect() void ClientSideNetworkHandler::onDisconnect(const RakNet::RakNetGUID& guid) { - clearChunksLoaded(); - + 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; + // TODO: Good disconnecting LOGI("onDisconnect\n"); if (level) @@ -228,8 +174,18 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, StartGam } #endif - // The world is infinite, the chunk cache width sent by the server is a legacy field. - clearChunksLoaded(); + // @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); const std::string& levelId = LevelStorageSource::TempLevelId; LevelStorageSource* storageSource = minecraft->getLevelSource(); @@ -543,7 +499,6 @@ 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); @@ -551,6 +506,15 @@ 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); } } @@ -591,14 +555,6 @@ 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()) { @@ -716,11 +672,66 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ChunkDat //chunk->terrainPopulated = true; chunk->unsaved = false; - loadedChunks.insert(chunkKey); + chunksLoaded[packet->x * LevelConstants::CHUNK_CACHE_WIDTH + packet->z] = true; - if (requested && !initialLoadDone && initialPending > 0 && --initialPending == 0) { - finishInitialLoad(); + 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(); } + 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) @@ -729,26 +740,8 @@ void ClientSideNetworkHandler::levelGenerated(Level* level) ReadyPacket packet(ReadyPacket::READY_CLIENTGENERATION); raknetInstance->send(packet); -#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(); + arrangeRequestChunkOrder(); + requestNextChunk(); } void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, PlayerEquipmentPacket* packet) @@ -1024,28 +1017,12 @@ 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() { - requestedChunks.clear(); - loadedChunks.clear(); - initialLoadDone = false; - initialPending = 0; + // 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; + } } diff --git a/src/network/ClientSideNetworkHandler.h b/src/network/ClientSideNetworkHandler.h index e68f58d..57e0d81 100755 --- a/src/network/ClientSideNetworkHandler.h +++ b/src/network/ClientSideNetworkHandler.h @@ -7,7 +7,6 @@ #include "../world/level/LevelConstants.h" #include -#include class Minecraft; class Level; @@ -82,17 +81,15 @@ 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; @@ -103,14 +100,13 @@ private: RakNet::RakNetGUID serverGuid; BlockUpdateList bufferedBlockUpdates; + int requestNextChunkPosition; - // 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; + int NumRequestChunks; + + int requestNextChunkIndex; + std::vector requestNextChunkIndexList; + std::vector chunksLoaded; }; #endif diff --git a/src/network/NetEventCallback.h b/src/network/NetEventCallback.h index 3a05a9d..db3e22b 100755 --- a/src/network/NetEventCallback.h +++ b/src/network/NetEventCallback.h @@ -52,7 +52,6 @@ class ContainerSetDataPacket; class ContainerSetContentPacket; class WantCreatePacket; class ChatPacket; -class SetSkinPacket; class SignUpdatePacket; class Minecraft; class Level; @@ -120,7 +119,6 @@ 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 b83d54a..d060356 100755 --- a/src/network/Packet.cpp +++ b/src/network/Packet.cpp @@ -177,9 +177,6 @@ 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 d1f6849..3525bd4 100755 --- a/src/network/Packet.h +++ b/src/network/Packet.h @@ -88,8 +88,6 @@ 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 fb8099a..7863e37 100755 --- a/src/network/ServerSideNetworkHandler.cpp +++ b/src/network/ServerSideNetworkHandler.cpp @@ -38,7 +38,6 @@ #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__) @@ -170,7 +169,6 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, MessageP return sendPrivate(resp, source); } - if (LuaEngine::get().onChat(player, msg)) return; displayGameMessage("<" + player->name + "> " + msg); } @@ -187,7 +185,6 @@ 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); } @@ -209,7 +206,6 @@ 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"; @@ -288,9 +284,6 @@ 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); @@ -359,11 +352,6 @@ 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); @@ -376,7 +364,6 @@ 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 @@ -398,9 +385,7 @@ 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, @@ -503,13 +488,6 @@ 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); @@ -661,31 +639,6 @@ 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) @@ -783,21 +736,6 @@ 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 d2a2858..c1cb632 100755 --- a/src/network/ServerSideNetworkHandler.h +++ b/src/network/ServerSideNetworkHandler.h @@ -48,7 +48,6 @@ 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 3deaa8a..3bcbbc1 100755 --- a/src/network/command/CommandServer.cpp +++ b/src/network/command/CommandServer.cpp @@ -233,8 +233,12 @@ 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 0ae79e8..ff884d2 100755 --- a/src/network/packet/PacketInclude.h +++ b/src/network/packet/PacketInclude.h @@ -9,7 +9,6 @@ #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 deleted file mode 100644 index 1f48ed7..0000000 --- a/src/network/packet/SetSkinPacket.h +++ /dev/null @@ -1,38 +0,0 @@ -#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 e32694b..47ac1d8 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); - // The world is infinite, only keep the position inside the coordinate system + // Add a small padding if standing next to the world edges const float padding = bbWidth * 0.5f + 0.001f; - 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); + xx = Mth::clamp(xx, padding, (float)LevelConstants::LEVEL_WIDTH - padding); + zz = Mth::clamp(zz, 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 3b2fb5d..6f69b01 100755 --- a/src/world/entity/player/Player.h +++ b/src/world/entity/player/Player.h @@ -164,7 +164,6 @@ 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 5272f5a..8f3140b 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 x < rhs.x || (x == rhs.x && z < rhs.z); + return hashCode() < rhs.hashCode(); } float distanceToSqr(const Entity* e) const { diff --git a/src/world/level/Level.cpp b/src/world/level/Level.cpp index a1f3bf9..522bad1 100755 --- a/src/world/level/Level.cpp +++ b/src/world/level/Level.cpp @@ -281,7 +281,8 @@ 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 (hasChunk(xp, zp)) + if (xp >= 0 && xp < LevelConstants::CHUNK_CACHE_WIDTH && + zp >= 0 && zp < LevelConstants::CHUNK_CACHE_WIDTH) _chunksToPoll.insert(ChunkPos(xp, zp)); } } @@ -430,13 +431,17 @@ bool Level::findPath(Path* path, Entity* from, int xBest, int yBest, int zBest, /*protected*/ void Level::setInitialSpawn() { isFindingSpawn = true; - // The world is infinite: start looking for dry land around the origin. - int xSpawn = 0; + int xSpawn = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH / 2; // (Level.MAX_LEVEL_SIZE - 100) * 0; int ySpawn = 64; - int zSpawn = 0; + int zSpawn = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_DEPTH / 2; // (Level.MAX_LEVEL_SIZE - 100) * 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; @@ -452,6 +457,11 @@ 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); @@ -937,8 +947,10 @@ 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)) { - HitResult r = tile->clip(this, xTile0, yTile0, zTile0, a, b); - if (r.isHit()) return r; + 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; + } } } return HitResult(); @@ -1010,12 +1022,7 @@ bool Level::addEntity(Entity* e) { if (e->isPlayer() && std::find(players.begin(), players.end(), e) == players.end()) { players.push_back( (Player*) 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; - } + getChunk(xc, zc)->addEntity(e); entities.push_back(e); entityIdLookup[e->entityId] = e; entityAdded(e); @@ -2243,20 +2250,9 @@ void Level::setNightMode( bool isNightMode ) { } bool Level::inRange( int x, int y, int z ) { - return x > -LevelConstants::LEVEL_WIDTH && x < LevelConstants::LEVEL_WIDTH + return x >= 0 && x < LevelConstants::LEVEL_WIDTH && y >= 0 && y < LevelConstants::LEVEL_HEIGHT - && 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); + && z >= 0 && z < LevelConstants::LEVEL_DEPTH; } // diff --git a/src/world/level/Level.h b/src/world/level/Level.h index d8a2ad9..e9b9294 100755 --- a/src/world/level/Level.h +++ b/src/world/level/Level.h @@ -274,7 +274,6 @@ 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 b4a51f6..6a36246 100644 --- a/src/world/level/LevelConstants.cpp +++ b/src/world/level/LevelConstants.cpp @@ -1,14 +1,10 @@ #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; -// 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::LEVEL_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH * CHUNK_WIDTH; +int LevelConstants::LEVEL_DEPTH = LevelConstants::CHUNK_CACHE_WIDTH * CHUNK_DEPTH; int LevelConstants::CHUNK_COLUMNS = LevelConstants::CHUNK_WIDTH * LevelConstants::CHUNK_DEPTH; -int LevelConstants::CHUNK_BLOCK_COUNT = LevelConstants::CHUNK_COLUMNS * LevelConstants::LEVEL_HEIGHT; +int LevelConstants::CHUNK_BLOCK_COUNT = LevelConstants::CHUNK_COLUMNS * LevelConstants::LEVEL_HEIGHT; \ No newline at end of file diff --git a/src/world/level/LevelConstants.h b/src/world/level/LevelConstants.h index a0d62b9..ed77861 100755 --- a/src/world/level/LevelConstants.h +++ b/src/world/level/LevelConstants.h @@ -1,22 +1,14 @@ -#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; - } -}; +#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 diff --git a/src/world/level/MobSpawner.cpp b/src/world/level/MobSpawner.cpp index 9381562..5e5dc90 100755 --- a/src/world/level/MobSpawner.cpp +++ b/src/world/level/MobSpawner.cpp @@ -38,20 +38,12 @@ 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 the chunks around every player, and disable Monster spawning this tick + // Spawn friendlies == loop over whole map, and disable Monster spawning this tick if (spawnFriendlies) { spawnEnemies = 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)); - } - } + for (int i = 0; i < 256; ++i) + chunksToPoll.insert( std::make_pair( ChunkPos(i>>4, i&15), false) ); + } else { // Only spawn mobs, check around one player per tick (@todo: optimize the "count instances of"?) static unsigned int _pid = 0; @@ -65,7 +57,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 (level->hasChunk(cx, cz)) + if (cx >= 0 && cx < 16 && cz >= 0 && cz < 16) 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 deleted file mode 100644 index dbfada9..0000000 --- a/src/world/level/chunk/ChunkCache.cpp +++ /dev/null @@ -1,380 +0,0 @@ -#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 0462d00..fbb2d77 100755 --- a/src/world/level/chunk/ChunkCache.h +++ b/src/world/level/chunk/ChunkCache.h @@ -1,87 +1,270 @@ -#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__*/ +#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__*/ diff --git a/src/world/level/chunk/ChunkSource.h b/src/world/level/chunk/ChunkSource.h index 0cf1b75..c1e029f 100755 --- a/src/world/level/chunk/ChunkSource.h +++ b/src/world/level/chunk/ChunkSource.h @@ -1,56 +1,46 @@ -#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__*/ +#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__*/ diff --git a/src/world/level/chunk/LevelChunk.cpp b/src/world/level/chunk/LevelChunk.cpp index 528a228..fd61715 100755 --- a/src/world/level/chunk/LevelChunk.cpp +++ b/src/world/level/chunk/LevelChunk.cpp @@ -9,7 +9,6 @@ #include "../tile/entity/TileEntity.h" #include "../tile/EntityTile.h" #include "../LevelConstants.h" -#include "../../../nbt/CompoundTag.h" /*static*/ bool LevelChunk::touchedSky = false; @@ -42,13 +41,7 @@ LevelChunk::LevelChunk( Level* level, unsigned char* blocks, int x, int z ) LevelChunk::~LevelChunk() { - //delete blocks; (see deleteBlockData) - delete[] heightmap; - delete[] updateMap; - if (pendingData) { - pendingData->deleteChildren(); - delete pendingData; - } + //delete blocks; } void LevelChunk::init() @@ -56,8 +49,6 @@ 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; @@ -546,23 +537,6 @@ 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 65fa412..8fe7281 100755 --- a/src/world/level/chunk/LevelChunk.h +++ b/src/world/level/chunk/LevelChunk.h @@ -16,7 +16,6 @@ class Entity; class LightLayer; class AABB; class TileEntity; -class CompoundTag; typedef std::vector EntityList; class LevelChunk @@ -100,12 +99,6 @@ 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); @@ -132,10 +125,6 @@ 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 09ed7e1..dbaa87b 100755 --- a/src/world/level/levelgen/RandomLevelSource.cpp +++ b/src/world/level/levelgen/RandomLevelSource.cpp @@ -537,13 +537,9 @@ 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; - const long long hashedPos = LevelConstants::chunkKey(xOffs, zOffs); + int hashedPos = ChunkPos::hashCode(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 ebdc0a0..e8b88e4 100755 --- a/src/world/level/levelgen/RandomLevelSource.h +++ b/src/world/level/levelgen/RandomLevelSource.h @@ -7,9 +7,20 @@ class Biome; class Level; class LevelChunk; -#include -// Keyed by LevelConstants::chunkKey(x, z) -typedef std::map ChunkMap; +#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 "../chunk/ChunkSource.h" @@ -33,7 +44,6 @@ 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 d31c50c..93ee9f1 100755 --- a/src/world/level/storage/ExternalFileLevelStorage.cpp +++ b/src/world/level/storage/ExternalFileLevelStorage.cpp @@ -8,7 +8,6 @@ #include "ExternalFileLevelStorage.h" #include "FolderMethods.h" #include "../chunk/LevelChunk.h" -#include "../chunk/ChunkSource.h" #include "../Level.h" #include "../LevelConstants.h" #include "platform/log.h" @@ -83,7 +82,10 @@ 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) { @@ -107,53 +109,10 @@ ExternalFileLevelStorage::ExternalFileLevelStorage(const std::string& levelId, c ExternalFileLevelStorage::~ExternalFileLevelStorage() { - closeRegions(); + delete regionFile; 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); } @@ -382,6 +341,10 @@ 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; @@ -394,15 +357,61 @@ 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) { - RegionFile* region = getRegion(levelChunk->x, levelChunk->z); - if (!region) - return; + if (!regionFile) + { + regionFile = new RegionFile(levelPath); + if (!regionFile->open()) + { + delete regionFile; + regionFile = NULL; + return; + } + } // Write chunk RakNet::BitStream chunkData; @@ -414,68 +423,29 @@ void ExternalFileLevelStorage::save(Level* level, LevelChunk* levelChunk) chunkData.Write((const char*)levelChunk->updateMap, LevelConstants::CHUNK_COLUMNS); - // Flags: bit 0 = the terrain decorations (trees, ores, ...) were placed - unsigned char flags = levelChunk->terrainPopulated ? 1 : 0; - chunkData.Write((const char*)&flags, 1); + regionFile->writeChunk(levelChunk->x, levelChunk->z, chunkData); - // Entities and tile entities that live in this chunk - if (!level->isClientSide) { - CompoundTag base; - ListTag* entityTags = new ListTag(); - ListTag* tileEntityTags = new ListTag(); + // Write entities - 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) { - RegionFile* region = getRegion(x, z); - if (!region) - return NULL; + if (!regionFile) + { + regionFile = new RegionFile(levelPath); + if (!regionFile->open()) + { + delete regionFile; + regionFile = NULL; + return NULL; + } + } RakNet::BitStream* chunkData = NULL; - if (!region->readChunk(x & 31, z & 31, &chunkData)) + if (!regionFile->readChunk(x, z, &chunkData)) { //LOGI("Failed to read data for %d, %d\n", x, z); return NULL; @@ -493,37 +463,47 @@ 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); - // 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; - } + // RakDataInput dis(*chunkData); + // Tag* tmp = Tag::readNamedTag(&dis); + // if (tmp && tmp->getId() == Tag::TAG_Compound) { + // CompoundTag* tag = (CompoundTag*) 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 tmp; + // } + //} 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) @@ -531,39 +511,104 @@ 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 - changed |= LevelConverters::ReplaceUnavailableBlocks(levelChunk); + //if (loadedStorageVersion > SharedConstants::StorageVersion) + changed |= LevelConverters::ReplaceUnavailableBlocks(levelChunk); levelChunk->recalcHeightmap(); levelChunk->unsaved = changed; - levelChunk->terrainPopulated = populated; + levelChunk->terrainPopulated = true; levelChunk->createdFromSave = true; return levelChunk; } -// Imports the global entities.dat that older versions of the game wrote. +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); +} + void ExternalFileLevelStorage::loadEntities(Level* level, LevelChunk* chunk) { - const std::string path = levelPath + "/entities.dat"; - FILE* fp = fopen(path.c_str(), "rb"); - if (!fp) return; + 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); - 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); + int left = getRemainingFileSize(fp); + if (numBytes <= left && numBytes > 0) { + unsigned char* buf = new unsigned char[numBytes]; - int left = getRemainingFileSize(fp); - if (numBytes <= left && numBytes > 0) { - unsigned char* buf = new unsigned char[numBytes]; + fread(buf, 1, numBytes, fp); - fread(buf, 1, numBytes, fp); + RakNet::BitStream stream(buf, numBytes, false); + RakDataInput dis(stream); - RakNet::BitStream stream(buf, numBytes, false); - RakDataInput dis(stream); - - CompoundTag* tag = NbtIo::read(&dis); - if (tag) { + CompoundTag* tag = NbtIo::read(&dis); + // + // Read Entity:es + // if (tag->contains("Entities", Tag::TAG_List)) { ListTag* entityTags = tag->getList("Entities"); for (int i = 0; i < entityTags->size(); ++i) { @@ -578,6 +623,9 @@ 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) { @@ -588,35 +636,67 @@ void ExternalFileLevelStorage::loadEntities(Level* level, LevelChunk* chunk) { } CompoundTag* et = (CompoundTag*)_et; if (TileEntity* e = TileEntity::loadStatic(et)) { - LevelChunk* lc = level->getChunkAt(e->x, e->z); - if (lc && !lc->hasTileEntityAt(e)) { - lc->addTileEntity(e); + + 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); } 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; - } - 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()); + delete[] buf; + } + LOGI("header: %s, version: %d, bytes: %d (remaining: %d)\n", header, version, numBytes, left); + + //fread(stream.GetData(), 1, numBytes, fp); + fclose(fp); + } } void ExternalFileLevelStorage::saveGame(Level* level) { - if (level && level->getChunkSource()) - level->getChunkSource()->saveAll(true); + 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; } 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 f817c15..9aad448 100755 --- a/src/world/level/storage/ExternalFileLevelStorage.h +++ b/src/world/level/storage/ExternalFileLevelStorage.h @@ -7,7 +7,6 @@ #include #include -#include //#include "com/mojang/nbt/CompoundTag.h" #include "LevelStorage.h" @@ -17,6 +16,16 @@ 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, @@ -45,15 +54,16 @@ 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); - // 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). + // @note, loadEntities and saveEntities dont use second parameter void loadEntities(Level* level, LevelChunk* levelChunk); + void saveEntities(Level* level, LevelChunk* levelChunk); void saveGame(Level* level); void saveAll(Level* level, std::vector& levelChunks); @@ -73,20 +83,17 @@ public: virtual void tick(); virtual void flush() {} private: - RegionFile* getRegion(int chunkX, int chunkZ); - void closeRegions(); - std::string levelId; std::string levelPath; LevelData* loadedLevelData; - - // Open region files, least recently used first - std::list regionOrder; - std::map regions; + RegionFile* regionFile; + RegionFile* entitiesFile; 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 cf08087..3edecce 100755 --- a/src/world/level/storage/RegionFile.cpp +++ b/src/world/level/storage/RegionFile.cpp @@ -13,27 +13,12 @@ static void logAssert(int actual, int expected) { } } -/*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) +RegionFile::RegionFile(const std::string& basePath) : file(NULL) { - filename = fileNameFor(basePath, regionX, regionZ); + filename = basePath; + filename += "/"; + filename += REGION_DAT_NAME; offsets = new int[SECTOR_INTS]; @@ -111,7 +96,6 @@ 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) @@ -143,7 +127,6 @@ 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 2b9e1f2..3d743ef 100755 --- a/src/world/level/storage/RegionFile.h +++ b/src/world/level/storage/RegionFile.h @@ -1,38 +1,31 @@ -#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__*/ +#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__*/ diff --git a/src/world/level/tile/Tile.cpp b/src/world/level/tile/Tile.cpp index b4948ba..6736bc7 100755 --- a/src/world/level/tile/Tile.cpp +++ b/src/world/level/tile/Tile.cpp @@ -512,7 +512,16 @@ 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; - // The world is infinite, there is no edge whose outer faces could be skipped + // 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; // 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 07a89c1..5b4728a 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 <= -LevelConstants::LEVEL_WIDTH || enemyPosition.z <= -LevelConstants::LEVEL_DEPTH || enemyPosition.x >= LevelConstants::LEVEL_WIDTH || enemyPosition.z >= LevelConstants::LEVEL_DEPTH) { + while(enemyPosition.x < 0 || enemyPosition.z < 0 || 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 <= -LevelConstants::LEVEL_WIDTH || itemPosition.z <= -LevelConstants::LEVEL_DEPTH || itemPosition.x >= LevelConstants::LEVEL_WIDTH || itemPosition.z >= LevelConstants::LEVEL_DEPTH) { + while(itemPosition.x < 0 || itemPosition.z < 0 || 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 deleted file mode 100644 index 1432469..0000000 --- a/tools/convert-music.ps1 +++ /dev/null @@ -1,23 +0,0 @@ -<# - 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 - } -}