Compare commits

..

45 commits

Author SHA1 Message Date
110cb2a896 Infinite world, LuaJIT mod API, WorldEdit port, skins and music
- Infinite world: streamed chunk cache, multi-region storage (old chunks.dat
  still loads), per-chunk entity/tile entity persistence, client chunk
  streaming, protocol version 10, view-distance server property
- LuaJIT mod host (mods/, lua/prelude.lua) with events, commands, world and
  player API; WorldEdit command set ported to it (mods/worldedit)
- /skin command, SetSkinPacket and bundled skins
- OGG music player (data/music is ignored, tools/convert-music.ps1)
- package-windows.ps1 builds client and dedicated server for Windows

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 21:08:09 +03:00
Nikolai Nevzorov
db9f6c9f32 🤦 2026-09-22 20:52:44 +02:00
Nikolai Nevzorov
567769a74f Обновить README.md 2026-09-22 20:52:17 +02:00
Nikolai Nevzorov
a16863041c Update README.md 2026-08-26 13:12:32 +02:00
Kolyah35
b032a8df7c FIX: char '1' work like backspace on android 2026-07-29 22:22:35 +03:00
Kolyah35
9987ab63b4 FIX: door item spawn in creative mode 2026-07-29 20:24:11 +03:00
InviseDivine
a489435cc5 AAAAAAAAAAAAAAA 2026-07-27 22:41:21 +02:00
InviseDivine
6767011d50 123123 2026-07-27 22:12:21 +02:00
InviseDivine
db4683f62a 1 2026-07-27 22:07:44 +02:00
Kolyah35
61ff4835ea FIX: commands and multiplayer crashes 2026-07-27 17:55:40 +03:00
Kolyah35
1f252ac4b3 FIX: grass color | small improvements 2026-07-26 20:43:02 +03:00
InviseDivine
7104ba93ae FIX: Grass color and egg red rectangle 2026-07-21 17:28:42 +02:00
InviseDivine
5ef00eee9f FIX: Grass tint only on IOS 2026-07-21 15:28:17 +02:00
InviseDivine
9a743b9aea FIX: Steve skin hand, containers open in creative, crash when downfalls is nullptr, build on android (hope) 2026-07-21 14:43:37 +02:00
InviseDivine
d7a51b09f1 FIX: MessagePacket instead of ChatPacket 2026-07-21 13:03:22 +02:00
InviseDivine
6452eacb34 Merge branch 'main' of https://gitea.sffempire.ru/Kolyah35/minecraft-pe-0.6.1 2026-07-21 12:35:35 +02:00
InviseDivine
47cab7d66b FIX: Melon seeds name 2026-07-21 12:35:34 +02:00
Kolyah35
09cc2ceee4 hopefully fixed web world creation 2026-07-20 23:35:32 +03:00
Kolyah35
7620d49489 I should go sleep ig 2026-07-20 23:14:59 +03:00
Kolyah35
381ef354c6 wtfffffff with git 2026-07-20 23:14:21 +03:00
Kolyah35
8be6e381d8 ok i was wrong 2026-07-20 23:12:34 +03:00
Kolyah35
3ab30eefa4 Revert "hopefully fixed ios build"
This reverts commit 92f972d320.
2026-07-20 23:10:28 +03:00
Kolyah35
325ab94a64 Revert "fuck i forgot ro remove tinted side option too"
This reverts commit c616546e1e.
2026-07-20 23:10:25 +03:00
Kolyah35
9434a48ae7 Revert "help me"
This reverts commit 79be815827.
2026-07-20 23:10:21 +03:00
Kolyah35
79be815827 help me 2026-07-20 23:01:12 +03:00
Kolyah35
c616546e1e fuck i forgot ro remove tinted side option too 2026-07-20 22:56:20 +03:00
Kolyah35
92f972d320 hopefully fixed ios build 2026-07-20 22:53:31 +03:00
Kolyah35
980fc2ccfb fix build!! 2026-07-20 22:48:38 +03:00
Nikolai Nevzorov
3b82c519d0 Merge pull request 'Add icon for win32' (#18) from yefeng/minecraft-pe-0.6.1:main into main
Reviewed-on: https://gitea.sffempire.ru/Kolyah35/minecraft-pe-0.6.1/pulls/18
2026-07-20 21:41:45 +02:00
Kolyah35
002bb40aae FIX: OpenAL error loop 2026-07-20 22:25:18 +03:00
Nikolai Nevzorov
6f4a07a306 Merge pull request 'Style changes' (#27) from Dram27-fix-settings-scrolling into main
Reviewed-on: https://gitea.sffempire.ru/Kolyah35/minecraft-pe-0.6.1/pulls/27
2026-07-20 21:14:57 +02:00
Nikolai Nevzorov
d5a3871f56 Merge pull request 'fix-settings-scrolling' (#24) from Dram27/minecraft-pe-0.6.1:fix-settings-scrolling into main
Reviewed-on: https://gitea.sffempire.ru/Kolyah35/minecraft-pe-0.6.1/pulls/24
2026-07-20 21:13:41 +02:00
Kolyah35
0c32f620af Sorry, apple users, I'm temporary removing foliage tinting 2026-07-20 22:11:41 +03:00
Kolyah35
93bf97a15e Style changes 2026-07-20 20:05:29 +03:00
deepfriedwaffles
0ee809daf1 Added new sources to xcodeproj so it can compile again
pull request opened and merged by me [obama giving medal to himself gif]
2026-07-20 18:12:11 +02:00
deepfriedwaffles
a048a51300 Added new sources to xcodeproj so it can compile again 2026-07-20 11:53:20 -04:00
InviseDivine
365d8a10da Update README.md 2026-07-20 17:25:02 +02:00
Nikolai Nevzorov
3940c9ce1b Update README.MD 2026-07-20 16:22:56 +02:00
InviseDivine
156849eeb6 Update README.md 2026-07-20 15:56:21 +02:00
InviseDivine
6a8b192024 Update README.md 2026-07-20 15:45:27 +02:00
Kolyah35
ce8ca15c56 FIX: android entity shadows 2026-07-20 15:37:19 +03:00
Dram27
b3561e773d Fix to prevent text overlap in options list during scroll 2026-04-26 16:12:56 +02:00
Dram27
162ec7adfa Fix bottom settings overlapping with Credits button 2026-04-26 16:00:44 +02:00
Dram27
4cfaa43d77 Added scroll with wheel on PC and touch scroll on Android/IOS 2026-04-26 15:47:52 +02:00
yefengeeeeeeeeeee
f1e8932fbd Add icon for win32 2026-03-28 18:12:34 +08:00
127 changed files with 5716 additions and 1846 deletions

7
.gitignore vendored
View file

@ -200,3 +200,10 @@ games/
vcpkg_installed/
.cache/
conan/
# Local build output and test scratch
dist/
_test/
# Music (converted from your own FLAC files with tools/convert-music.ps1)
data/music/*.ogg

View file

@ -3,10 +3,12 @@ project(MinecraftPE)
include(cmake/CPM.cmake)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD 14)
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
@ -15,7 +17,9 @@ endif()
enum_option(PLATFORM "Desktop;Web" "Platform to build for.")
find_package(Threads REQUIRED)
if(NOT EMSCRIPTEN)
find_package(Threads REQUIRED)
endif()
find_package(OpenSSL)
if (${PLATFORM} STREQUAL "Desktop")
@ -33,11 +37,9 @@ if (${PLATFORM} STREQUAL "Desktop")
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
include_directories(misc/windows)
set(EXTRA_LIBS ws2_32 winhttp)
add_definitions(-DLUA_DL_DLL=1)
elseif(UNIX)
find_library(pthread NAMES pthread)
set(EXTRA_LIBS pthread m)
add_definitions(-DLUA_USE_DLOPEN=1)
endif()
elseif (${PLATFORM} STREQUAL "Web")
@ -96,45 +98,15 @@ else()
"GLFW_BUILD_TESTS OFF"
"GLFW_BUILD_DOCS OFF"
)
endif()
CPMAddPackage("gh:halx99/sol2#support-lua-5.5")
CPMAddPackage("gh:lua/lua#master")
add_library(
lua STATIC
${lua_SOURCE_DIR}/lapi.c
${lua_SOURCE_DIR}/lauxlib.c
${lua_SOURCE_DIR}/lbaselib.c
${lua_SOURCE_DIR}/lcode.c
${lua_SOURCE_DIR}/lcorolib.c
${lua_SOURCE_DIR}/lctype.c
${lua_SOURCE_DIR}/ldblib.c
${lua_SOURCE_DIR}/ldebug.c
${lua_SOURCE_DIR}/ldo.c
${lua_SOURCE_DIR}/ldump.c
${lua_SOURCE_DIR}/lfunc.c
${lua_SOURCE_DIR}/lgc.c
${lua_SOURCE_DIR}/linit.c
${lua_SOURCE_DIR}/liolib.c
${lua_SOURCE_DIR}/llex.c
${lua_SOURCE_DIR}/lmathlib.c
${lua_SOURCE_DIR}/lmem.c
${lua_SOURCE_DIR}/loadlib.c
${lua_SOURCE_DIR}/lobject.c
${lua_SOURCE_DIR}/lopcodes.c
${lua_SOURCE_DIR}/loslib.c
${lua_SOURCE_DIR}/lparser.c
${lua_SOURCE_DIR}/lstate.c
${lua_SOURCE_DIR}/lstring.c
${lua_SOURCE_DIR}/lstrlib.c
${lua_SOURCE_DIR}/ltable.c
${lua_SOURCE_DIR}/ltablib.c
${lua_SOURCE_DIR}/ltm.c
${lua_SOURCE_DIR}/lua.c
${lua_SOURCE_DIR}/lundump.c
${lua_SOURCE_DIR}/lutf8lib.c
${lua_SOURCE_DIR}/lvm.c
${lua_SOURCE_DIR}/lzio.c
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()
@ -235,6 +207,7 @@ file(GLOB SERVER_SOURCES
"src/world/level/biome/Biome.cpp"
"src/world/level/biome/BiomeSource.cpp"
"src/world/level/chunk/ChunkCache.cpp"
"src/world/level/chunk/LevelChunk.cpp"
"src/world/level/dimension/Dimension.cpp"
@ -256,8 +229,7 @@ file(GLOB SERVER_SOURCES
"src/world/phys/HitResult.cpp"
"src/commands/*.cpp"
"src/plugins/*.cpp"
"src/lua/*.cpp"
)
file(GLOB CLIENT_SOURCES
@ -343,30 +315,36 @@ file(GLOB CLIENT_SOURCES
"src/main.cpp"
"src/commands/*.cpp"
"src/plugins/*.cpp"
"src/lua/*.cpp"
)
if (${PLATFORM} STREQUAL "Desktop")
list(APPEND CLIENT_SOURCES glad/src/glad.c)
list(APPEND CLIENT_SOURCES glad/src/glad.c "${stb_SOURCE_DIR}/stb_vorbis.c")
endif()
# Server
add_executable("${PROJECT_NAME}-server" ${SERVER_SOURCES})
set_target_properties("${PROJECT_NAME}-server" PROPERTIES ENABLE_EXPORTS TRUE)
target_compile_definitions("${PROJECT_NAME}-server" PUBLIC "STANDALONE_SERVER" "SERVER_PROFILER")
target_include_directories("${PROJECT_NAME}-server" PUBLIC
"${CMAKE_SOURCE_DIR}/src/"
"${lua_SOURCE_DIR}/"
"project/lib_projects/raknet/jni/RaknetSources"
)
target_link_libraries("${PROJECT_NAME}-server" ${CMAKE_THREAD_LIBS_INIT} ${EXTRA_LIBS} lua sol2::sol2)
target_link_libraries("${PROJECT_NAME}-server" ${CMAKE_THREAD_LIBS_INIT} ${EXTRA_LIBS} luajit)
# Lua API (prelude) and bundled mods are shipped next to the executables
add_custom_command(TARGET "${PROJECT_NAME}-server" POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/lua" "$<TARGET_FILE_DIR:${PROJECT_NAME}-server>/lua"
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/mods" "$<TARGET_FILE_DIR:${PROJECT_NAME}-server>/mods"
)
add_executable(${PROJECT_NAME} ${CLIENT_SOURCES})
set_target_properties(${PROJECT_NAME} PROPERTIES ENABLE_EXPORTS TRUE)
if(WIN32)
target_sources(${PROJECT_NAME} PRIVATE data/images/pe.rc)
endif()
target_compile_definitions(${PROJECT_NAME} PUBLIC ${PLATFORM_CPP})
@ -375,9 +353,8 @@ target_include_directories(${PROJECT_NAME} PUBLIC
"${CMAKE_SOURCE_DIR}/src"
"${openal_SOURCE_DIR}/include"
"${glfw_SOURCE_DIR}/include"
"${stb_SOURCE_DIR}"
"lib/include"
"${lua_SOURCE_DIR}/"
)
if(${PLATFORM} MATCHES "Web")
@ -425,7 +402,7 @@ endif()
# Client
target_compile_definitions(${PROJECT_NAME} PUBLIC "OPENGL_ES" "NO_EGL" ${PLATFORM})
target_link_libraries(${PROJECT_NAME} zlib ${PNG_LIB} OpenAL::OpenAL glfw ${EXTRA_LIBS} lua sol2::sol2)
target_link_libraries(${PROJECT_NAME} zlib ${PNG_LIB} OpenAL::OpenAL glfw ${EXTRA_LIBS} luajit)
if (OpenSSL_FOUND)
target_link_libraries(${PROJECT_NAME} OpenSSL::SSL OpenSSL::Crypto)
@ -446,6 +423,8 @@ if(NOT ${PLATFORM} MATCHES "Web")
TARGET ${PROJECT_NAME}
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/data" $<TARGET_FILE_DIR:${PROJECT_NAME}>/data
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/lua" $<TARGET_FILE_DIR:${PROJECT_NAME}>/lua
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/mods" $<TARGET_FILE_DIR:${PROJECT_NAME}>/mods
)
else()
add_custom_command(

View file

@ -1,31 +1,47 @@
# MinecraftPE
> [!Warning]
> Github repository **isnt main**. All issues and pull requests should be send in [Gitea Repository](https://gitea.sffempire.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.sffnetwork.ru/Kolyah35/minecraft-pe-0.6.1).
> [!Important]
> We have a discord server, where you can report bugs or send feedback https://discord.gg/c58YesBxve
> [!Note]
> There is unofficial (not related to Kolyah35 and InviseDivine) discord server, where you can report bugs or send feedback https://discord.gg/udYrbNDfDH
Source code for **Minecraft Pocket Edition 0.6.1 alpha** with various fixes and improvements.
This project aims to preserve and improve this early version of Minecraft PE.
# TODO / Roadmap
- [x] Add platform GLFW
- [x] Compile for Linux
- [x] Compile for android aarch64
- [x] Touch control improvements
- [ ] Screen fixes
- [ ] Rewrite platform logic
- [x] Fix sound
- [x] Do a server connection GUI
- [ ] Controller support
- [x] Minecraft server hosting
- [x] Screen fixess
- [x] Fix fog
- [x] Add sprinting
- [x] Chat (semi working) and commands
- [x] Implementing options
- [x] Better F3
# Features
- Support for modern IOS and Android, Linux, Web
- Improved Dedicated Server (Windows build, anticheat, commands, etc)
- Features from Beta version of Minecraft (Grass tint, Beta sky, Smooth lighting, etc) and other tweaks
# Screenshots
<p align="center">
<img width="49%" alt="menu" src="https://sffnetwork.ru/mcpe-screenshots/menu.png" />
<img width="49%" alt="settings" src="https://sffnetwork.ru/mcpe-screenshots/settings.png" />
<img width="49%" alt="worlds" src="https://sffnetwork.ru/mcpe-screenshots/worlds.png" />
<img width="49%" alt="gameplay" src="https://sffnetwork.ru/mcpe-screenshots/gameplay.png" />
</p>
# This fork: infinite world, Lua mods, WorldEdit, skins, music
- **Infinite world** - chunks are generated, saved (region files `r.<x>.<z>.dat`, old `chunks.dat` worlds still load) and unloaded around the players. Dedicated server: `view-distance=<chunks>` in `server.properties` (the old `world-size` is ignored). Multiplayer protocol version is now 10.
- **Lua mods (LuaJIT)** - drop mods into `mods/`, see [mods/README.md](mods/README.md) for the API (events, commands, world/player access, scheduler).
- **WorldEdit** - [mods/worldedit](mods/worldedit) is a port of EngineHub's WorldEdit command set to that API (`//wand`, `//set`, `//sphere`, `//copy`, `//paste`, `/undo`, brushes, ...).
- **Skins** - `data/images/skins/*.png` (64x32 or 64x64). `/skin list`, `/skin <name>` in the chat console; other players see the skin you pick. Drop a `<username>.png` there to override the skin of that player.
- **Music** - the `.ogg` files in `data/music` are played in random order (volume: Music slider). Use `tools/convert-music.ps1` to convert your own FLAC/MP3 files.
## Windows build (client + server)
```powershell
.\package-windows.ps1 # needs Visual Studio 2022 (C++) and CMake
```
Result: `dist\MinecraftPE-win64` (client) and `dist\MinecraftPE-server-win64` (dedicated server, `start-server.bat`).
The script limits the compiler parallelism because OpenAL Soft needs a lot of memory (`-Jobs 2` for small machines), and
trusts the dependency checkouts for git ("dubious ownership" on drives that do not store file owners).
# Build
@ -79,8 +95,14 @@ cmake --build .
```
C:\android-ndk-r14b
```
3. Install **Build tools 35** with [SDKManager](https://dl.google.com/android/repository/commandlinetools-win-15859902_latest.zip) (build-tools should be in AppData):
3. Run the build script:
```powershell
sdkmanager "build-tools;35.0.0" --sdk_root="%LocalAppData%\Android\Sdk"
sdkmanager "build-tools;android-36" --sdk_root="%LocalAppData%\Android\Sdk"
```
4. Run the build script:
```powershell
# Full build (NDK + Java + APK + install)
@ -154,7 +176,6 @@ cmake --build .
```bash
35.0.0
33.0.2
```
6. Download **Android NDK r14b**:
@ -200,7 +221,7 @@ cmake --build .
```
## iOS
### Xcode
> [Note!]
> [!Note]
> There's a precompiled IPA artifact in the GitHub mirror under Actions for those who either don't have Macs or don't want to build themself. But if you want to build youself, you'll need a Mac with Xcode. Download Xcode from the Mac App Store.
### 1. Clone

70
cmake/LuaJIT.cmake Normal file
View file

@ -0,0 +1,70 @@
# Builds LuaJIT (static) from source and exposes it as the imported target "luajit".
#
# * MSVC: runs LuaJIT's own msvcbuild.bat inside the matching Visual Studio environment
# * others: runs LuaJIT's Makefile (make / mingw32-make)
CPMAddPackage(
NAME "luajit"
GIT_REPOSITORY "https://github.com/LuaJIT/LuaJIT.git"
GIT_TAG "dd3b24369ddfaa83c78cd6fdd91d157c8968ec8d"
DOWNLOAD_ONLY YES
)
set(LUAJIT_SRC "${luajit_SOURCE_DIR}/src")
if (MSVC)
set(LUAJIT_LIB "${LUAJIT_SRC}/lua51.lib")
# <VS>/VC/Tools/MSVC/<ver>/bin/Hostx64/x64/cl.exe -> <VS>/VC/Auxiliary/Build/vcvarsall.bat
get_filename_component(_cl_dir "${CMAKE_C_COMPILER}" DIRECTORY)
get_filename_component(_vc_root "${_cl_dir}/../../../../../.." ABSOLUTE)
set(_vcvars "${_vc_root}/Auxiliary/Build/vcvarsall.bat")
if (NOT EXISTS "${_vcvars}")
message(FATAL_ERROR "vcvarsall.bat not found at ${_vcvars}")
endif()
if (CMAKE_SIZEOF_VOID_P EQUAL 8)
set(_vcarch x64)
else()
set(_vcarch x86)
endif()
file(TO_NATIVE_PATH "${_vcvars}" _vcvars_native)
file(TO_NATIVE_PATH "${LUAJIT_SRC}" _src_native)
file(TO_NATIVE_PATH "${CMAKE_BINARY_DIR}/build_luajit.bat" _bat_native)
# LuaJIT needs the Visual Studio command line environment, so run it from a batch file
# (msvcbuild.bat runs the tools it just built by bare name, which needs the current directory in the search path)
set(_bat "@echo off\r\nset NoDefaultCurrentDirectoryInExePath=\r\n")
string(APPEND _bat "call \"${_vcvars_native}\" ${_vcarch} || exit /b 1\r\n")
string(APPEND _bat "cd /d \"${_src_native}\" || exit /b 1\r\n")
string(APPEND _bat "call .\\msvcbuild.bat static || exit /b 1\r\n")
file(WRITE "${CMAKE_BINARY_DIR}/build_luajit.bat" "${_bat}")
add_custom_command(
OUTPUT "${LUAJIT_LIB}"
COMMAND cmd /c "${_bat_native}"
WORKING_DIRECTORY "${LUAJIT_SRC}"
COMMENT "Building LuaJIT"
VERBATIM
)
else()
set(LUAJIT_LIB "${LUAJIT_SRC}/libluajit.a")
find_program(_make NAMES make gmake mingw32-make REQUIRED)
add_custom_command(
OUTPUT "${LUAJIT_LIB}"
COMMAND "${_make}" BUILDMODE=static
WORKING_DIRECTORY "${LUAJIT_SRC}"
COMMENT "Building LuaJIT"
VERBATIM
)
endif()
add_custom_target(luajit_build DEPENDS "${LUAJIT_LIB}")
add_library(luajit STATIC IMPORTED GLOBAL)
set_target_properties(luajit PROPERTIES
IMPORTED_LOCATION "${LUAJIT_LIB}"
INTERFACE_INCLUDE_DIRECTORIES "${LUAJIT_SRC}"
)
add_dependencies(luajit luajit_build)

BIN
data/images/pe.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

1
data/images/pe.rc Normal file
View file

@ -0,0 +1 @@
IDI_ICON1 ICON "pe.ico"

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

BIN
data/images/skins/green.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

BIN
data/images/skins/ninja.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

BIN
data/images/skins/pink.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

BIN
data/images/skins/red.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

BIN
data/images/skins/snow.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

BIN
data/images/skins/steve.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

View file

@ -1020,5 +1020,5 @@ desc.netherbrickitem=Used to form blocks of Nether bricks.
desc.netherquartz=Quartz from the Nether, used to create Blocks of Quartz.
desc.quartzblock=Decorative block, used to create other kinds of Quartz blocks.
desc.stonecutter=For crafting stoneblocks.
desc.seedsmelon=Allows for more melons.
desc.seeds_melon=Allows for more melons.
desc.tile.melon=Can be cut up and eaten.

404
lua/prelude.lua Normal file
View file

@ -0,0 +1,404 @@
-- ============================================================================
-- MinecraftPE Lua API (LuaJIT)
-- This file is loaded by the game before any mod. It builds the friendly
-- `mc` API on top of the native primitives (mc._*) that the game provides.
-- Documentation: mods/README.md
-- ============================================================================
local mc = mc
mc.VERSION = "1.0"
local floor, max, min = math.floor, math.max, math.min
-- ---------------------------------------------------------------- utilities
mc.util = {}
function mc.util.split(s, sep)
local out = {}
sep = sep or "%s+"
for piece in string.gmatch(s, "([^" .. (sep == "%s+" and "%s" or sep) .. "]+)") do
out[#out + 1] = piece
end
return out
end
function mc.util.copy(t)
local c = {}
for k, v in pairs(t) do c[k] = v end
return c
end
local function serialize(v, indent)
local t = type(v)
if t == "number" or t == "boolean" then return tostring(v) end
if t == "string" then return string.format("%q", v) end
if t == "table" then
local parts = {}
for k, val in pairs(v) do
parts[#parts + 1] = "[" .. serialize(k) .. "]=" .. serialize(val)
end
return "{" .. table.concat(parts, ",") .. "}"
end
return "nil"
end
--- Saves a plain Lua table (numbers, strings, booleans, tables) to a file.
function mc.save_table(path, tbl)
local f, err = io.open(path, "w")
if not f then return false, err end
f:write("return ", serialize(tbl))
f:close()
return true
end
--- Loads a table written by mc.save_table, or returns `default`.
function mc.load_table(path, default)
local chunk = loadfile(path)
if not chunk then return default end
setfenv(chunk, {})
local ok, res = pcall(chunk)
if ok then return res end
return default
end
function mc.log(...)
local parts = {}
for i = 1, select("#", ...) do parts[i] = tostring((select(i, ...))) end
mc._log(table.concat(parts, " "))
end
-- ------------------------------------------------------------------ blocks
local BLOCKS = {
[0] = "air", [1] = "stone", [2] = "grass", [3] = "dirt", [4] = "cobblestone", [5] = "planks",
[6] = "sapling", [7] = "bedrock", [8] = "flowing_water", [9] = "water", [10] = "flowing_lava",
[11] = "lava", [12] = "sand", [13] = "gravel", [14] = "gold_ore", [15] = "iron_ore",
[16] = "coal_ore", [17] = "log", [18] = "leaves", [20] = "glass", [21] = "lapis_ore",
[22] = "lapis_block", [24] = "sandstone", [26] = "bed", [30] = "cobweb", [31] = "tallgrass",
[35] = "wool", [37] = "dandelion", [38] = "rose", [39] = "brown_mushroom", [40] = "red_mushroom",
[41] = "gold_block", [42] = "iron_block", [43] = "double_slab", [44] = "slab", [45] = "bricks",
[46] = "tnt", [47] = "bookshelf", [48] = "mossy_cobblestone", [49] = "obsidian", [50] = "torch",
[51] = "fire", [53] = "oak_stairs", [54] = "chest", [56] = "diamond_ore", [57] = "diamond_block",
[58] = "crafting_table", [59] = "wheat", [60] = "farmland", [61] = "furnace", [62] = "lit_furnace",
[63] = "sign", [64] = "wooden_door", [65] = "ladder", [67] = "stone_stairs", [68] = "wall_sign",
[71] = "iron_door", [73] = "redstone_ore", [74] = "lit_redstone_ore", [78] = "snow_layer",
[79] = "ice", [80] = "snow", [81] = "cactus", [82] = "clay", [83] = "reeds", [85] = "fence",
[86] = "pumpkin", [87] = "netherrack", [89] = "glowstone", [91] = "jack_o_lantern",
[96] = "trapdoor", [98] = "stonebrick", [102] = "glass_pane", [103] = "melon", [105] = "melon_stem",
[107] = "fence_gate", [108] = "brick_stairs", [109] = "stonebrick_stairs", [112] = "nether_brick",
[114] = "nether_brick_stairs", [128] = "sandstone_stairs", [129] = "emerald_ore",
[133] = "emerald_block", [155] = "quartz_block", [156] = "quartz_stairs", [245] = "stonecutter",
[246] = "glowing_obsidian", [247] = "nether_reactor",
}
local ALIASES = {
rock = 1, smooth_stone = 1, grass_block = 2, cobble = 4, wood = 5, wood_planks = 5, oak_planks = 5,
planks = 5, sapling = 6, adminium = 7, bed_rock = 7, water = 9, still_water = 9, stationary_water = 9,
lava = 11, still_lava = 11, stationary_lava = 11, flowing_water = 8, flowing_lava = 10,
gold = 14, iron = 15, coal = 16, trunk = 17, tree = 17, wood_log = 17, oak_log = 17, leaf = 18,
leaves = 18, lapis = 21, sandstone = 24, web = 30, grass_plant = 31, cloth = 35, flower = 37,
yellow_flower = 37, red_flower = 38, goldblock = 41, ironblock = 42, brick = 45, bricks = 45,
mossy = 48, mossy_cobble = 48, moss = 48, obsidian = 49, torch = 50, fire = 51, chest = 54,
diamond = 56, workbench = 58, crafting = 58, table = 58, furnace = 61, ladder = 65, ice = 79,
snowblock = 80, snow_block = 80, cactus = 81, clay = 82, sugarcane = 83, fence = 85, glowstone = 89,
lightstone = 89, netherrack = 87, hell = 87, stonebricks = 98, stone_brick = 98, stone_bricks = 98,
melon = 103, quartz = 155, door = 64, iron_door = 71, tnt = 46, bookshelf = 47, books = 47,
glass = 20, sand = 12, gravel = 13, dirt = 3, stone = 1, grass = 2, bedrock = 7,
pane = 102, trap_door = 96, pumpkin = 86, lantern = 91, stair = 53, stairs = 53, double_step = 43,
step = 44, half_slab = 44, slab = 44, double_slab = 43, farmland = 60, soil = 60,
}
local WOOL = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray",
"light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" }
local WOOL_DATA = {}
for i, name in ipairs(WOOL) do
WOOL_DATA[name] = i - 1
ALIASES[name .. "_wool"] = { 35, i - 1 }
end
local NAME_TO_ID = {}
for id, name in pairs(BLOCKS) do NAME_TO_ID[name] = id end
mc.block = { ids = NAME_TO_ID, names = BLOCKS }
--- Name of a block id ("stone"), or the number as a string.
function mc.block.name(id)
return BLOCKS[id] or tostring(id)
end
--- Parses "stone", "35:14", "red_wool", "log:1" -> id, data (data is nil when not given)
function mc.block.parse(text)
text = string.lower(text)
local nameOrId, data = string.match(text, "^([%w_]+):(%d+)$")
if nameOrId then data = tonumber(data) else nameOrId = text end
local id = tonumber(nameOrId)
if not id then
local alias = ALIASES[nameOrId]
if type(alias) == "table" then
id, data = alias[1], data or alias[2]
else
id = alias or NAME_TO_ID[nameOrId]
end
end
if not id or id < 0 or id > 255 then return nil end
return id, data
end
-- Blocks that are not solid ground (used by e.g. //green, //naturalize, //ascend)
mc.block.AIR = 0
-- ------------------------------------------------------------------- items
mc.item = {
stick = 280, compass = 345, wooden_axe = 271, wooden_pickaxe = 270, wooden_shovel = 269,
wooden_sword = 268, stone_axe = 275, iron_axe = 258, diamond_axe = 279, flint_and_steel = 259,
apple = 260, bow = 261, arrow = 262, coal = 263, diamond = 264, iron_ingot = 265, gold_ingot = 266,
bucket = 325, water_bucket = 326, lava_bucket = 327, clock = 347, paper = 339, book = 340,
}
mc.mob = { chicken = 10, cow = 11, pig = 12, sheep = 13, zombie = 32, creeper = 33,
skeleton = 34, spider = 35, pig_zombie = 36 }
-- ------------------------------------------------------------------ players
local Player = {}
Player.__index = Player
local playerCache = {}
local function getPlayer(id)
if not id then return nil end
local p = playerCache[id]
if not p then
local name = mc._pname(id)
if not name then return nil end
p = setmetatable({ id = id, name = name, data = {} }, Player)
playerCache[id] = p
end
return p
end
mc._player = getPlayer
function Player:__tostring() return "Player(" .. self.name .. ")" end
--- Feet position: x, y, z
function Player:pos() local x, y, z = mc._ppos(self.id); return x, y, z end
--- Block the feet are in
function Player:block_pos()
local x, y, z = mc._ppos(self.id)
return floor(x), floor(y), floor(z)
end
--- yaw, pitch in degrees
function Player:look() local _, _, _, yaw, pitch = mc._ppos(self.id); return yaw, pitch end
--- Horizontal facing as 0..3 (south, west, north, east) and its unit vector
function Player:facing()
local yaw = self:look()
local dir = floor(((yaw % 360) + 45) / 90) % 4
local vec = { [0] = { 0, 1 }, [1] = { -1, 0 }, [2] = { 0, -1 }, [3] = { 1, 0 } }
return dir, vec[dir][1], vec[dir][2]
end
function Player:teleport(x, y, z, yaw, pitch) mc._pteleport(self.id, x, y, z, yaw, pitch) end
function Player:say(...)
local parts = {}
for i = 1, select("#", ...) do parts[i] = tostring((select(i, ...))) end
local text = table.concat(parts, " ")
for line in string.gmatch(text .. "\n", "(.-)\n") do
if line ~= "" then mc._pmsg(self.id, line) end
end
end
function Player:is_op() return mc._pop(self.id) end
--- id, data, count of the held item (0,0,0 when empty)
function Player:held() return mc._pheld(self.id) end
function Player:give(id, count, data) mc._pgive(self.id, id, count or 1, data or 0) end
--- 0 = survival, 1 = creative
function Player:gamemode() return mc._pgamemode() end
--- x, y, z, face of the block the player is looking at, or nil
function Player:target(distance) return mc._ptrace(self.id, distance or 128) end
function Player:is_online() return mc._pname(self.id) ~= nil end
mc.Player = Player
function mc.players()
local list = {}
for i, id in ipairs(mc._players()) do list[i] = getPlayer(id) end
return list
end
function mc.player(name)
name = string.lower(name)
for _, id in ipairs(mc._players()) do
local p = getPlayer(id)
if p and string.lower(p.name) == name then return p end
end
return nil
end
function mc.broadcast(text) mc._broadcast(text) end
-- -------------------------------------------------------------------- world
mc.world = {}
local W = mc.world
W.get_block = mc._get_block
W.set_block = mc._set_block
--- Re-sends/relights everything written with silent set_block calls
W.flush = mc._flush
W.is_loaded = mc._loaded
W.ensure_loaded = mc._ensure
W.seed = mc._seed
W.explode = mc._explode
W.spawn_mob = mc._spawn_mob
W.drop_item = mc._drop_item
W.butcher = mc._butcher
W.height = mc._solid_height
W.get_time = mc._get_time
W.set_time = mc._set_time
-- ---------------------------------------------------------------- scheduler
local tasks, nextTask, tickCount = {}, 1, 0
mc.tick_count = 0
function mc.after(ticks, fn)
local id = nextTask; nextTask = nextTask + 1
tasks[id] = { at = tickCount + max(1, ticks), fn = fn }
return id
end
function mc.every(ticks, fn)
local id = nextTask; nextTask = nextTask + 1
tasks[id] = { at = tickCount + max(1, ticks), fn = fn, period = max(1, ticks) }
return id
end
function mc.cancel(id) tasks[id] = nil end
-- ------------------------------------------------------------------- events
local handlers = {}
--- mc.on("block_break", function(player, x, y, z, tile) return false end)
--- Events: start, stop, tick, join, leave, chat, block_break, use_item
--- Returning false from a cancellable event (chat, block_break, use_item) cancels it.
function mc.on(event, fn)
handlers[event] = handlers[event] or {}
table.insert(handlers[event], fn)
end
local function report(modName, err)
mc._log("error in handler: " .. tostring(err))
end
function mc._fire(event, pid, ...)
local list = handlers[event]
if not list then return true end
local first = pid
if pid ~= nil then first = getPlayer(pid) end
local result = true
for i = 1, #list do
local ok, res = xpcall(list[i], debug.traceback, first, ...)
if not ok then
report(nil, res)
elseif res == false then
result = false
end
end
if event == "leave" and pid then playerCache[pid] = nil end
return result
end
function mc._tick()
tickCount = tickCount + 1
mc.tick_count = tickCount
for id, task in pairs(tasks) do
if task.at <= tickCount then
if task.period then task.at = tickCount + task.period else tasks[id] = nil end
local ok, err = xpcall(task.fn, debug.traceback)
if not ok then report(nil, err) end
end
end
if handlers.tick then mc._fire("tick") end
end
-- ----------------------------------------------------------------- commands
local commands = {}
--- mc.command("home", { description = "...", usage = "/home", op = false }, function(ctx) ... end)
--- Names are what the player types after the first slash, so WorldEdit's "//set" is "/set".
function mc.command(name, opts, fn)
if type(opts) == "function" then fn, opts = opts, {} end
commands[string.lower(name)] = { fn = fn, opts = opts or {}, name = name }
end
function mc._command_names()
local names = {}
for name in pairs(commands) do names[#names + 1] = name end
table.sort(names)
return names
end
function mc._run_command(pid, name, args)
local cmd = commands[string.lower(name)]
if not cmd then return false end
local player = getPlayer(pid)
if cmd.opts.op and not player:is_op() then
return true, "You are not allowed to use this command."
end
local replies = {}
local ctx = {
player = player, args = args, name = name,
reply = function(_, ...) player:say(...) end,
}
setmetatable(ctx, { __index = function(_, k) return nil end })
local ok, res = xpcall(cmd.fn, debug.traceback, ctx)
if not ok then
mc._log("command /" .. name .. " failed: " .. tostring(res))
return true, "Command failed: " .. tostring(res):match("^[^\n]*")
end
if type(res) == "string" then return true, res end
return true
end
-- ------------------------------------------------------------------- mods
mc.mods = {}
local function listDir(dir)
return mc._listdir and mc._listdir(dir) or {}
end
local function loadMod(name, dir, file)
local env = setmetatable({}, { __index = _G })
env.MOD = { name = name, dir = dir }
env.require = function(m)
local path = dir .. "/" .. m:gsub("%.", "/") .. ".lua"
local chunk = loadfile(path)
if chunk then
setfenv(chunk, env)
return chunk()
end
return require(m)
end
local chunk, err = loadfile(file)
if not chunk then
mc._log("cannot load mod '" .. name .. "': " .. tostring(err))
return
end
setfenv(chunk, env)
local ok, res = xpcall(chunk, debug.traceback)
if not ok then
mc._log("mod '" .. name .. "' failed: " .. tostring(res))
return
end
mc.mods[name] = env.MOD
mc._log("loaded mod '" .. name .. "'")
end
function mc._load_mods()
local entries = listDir("mods")
table.sort(entries, function(a, b) return a.name < b.name end)
for _, e in ipairs(entries) do
if e.dir then
local main = "mods/" .. e.name .. "/main.lua"
local f = io.open(main, "r")
if f then f:close(); loadMod(e.name, "mods/" .. e.name, main) end
elseif e.name:match("%.lua$") then
loadMod((e.name:gsub("%.lua$", "")), "mods", "mods/" .. e.name)
end
end
mc._fire("start")
for _, id in ipairs(mc._players()) do mc._fire("join", id) end
end

120
mods/README.md Normal file
View file

@ -0,0 +1,120 @@
# Lua mods (LuaJIT)
The game embeds **LuaJIT 2.1**. Mods run on the machine that hosts the world:
the dedicated server (`MinecraftPE-server.exe`), a single player world, or a
client that hosts a LAN game. A client that only joins a server runs no mods.
```
mods/
my_mod/
main.lua <- loaded at startup (alphabetical order)
other.lua <- require("other")
tiny.lua <- a single file mod works too
```
Every mod runs in its own environment (`MOD.name`, `MOD.dir` describe it), so
globals do not leak between mods. `require("x")` loads `mods/<mod>/x.lua` first.
The full Lua 5.1 standard library, `io`, `os`, `bit` and `ffi` are available –
mods are trusted code, only install mods you trust.
## Events
```lua
mc.on("start", function() end) -- all mods loaded, world is up
mc.on("stop", function() end)
mc.on("tick", function() end) -- 20 times per second
mc.on("join", function(player) end)
mc.on("leave", function(player) end)
mc.on("chat", function(player, message) end) -- return false to cancel
mc.on("block_break", function(player, x, y, z, tile) end)-- return false to cancel
mc.on("use_item", function(player, x, y, z, face, itemId, itemData) end) -- right click on a block, false cancels
```
## Commands
```lua
mc.command("home", { description = "Go home", op = false }, function(ctx)
ctx.player:teleport(0, 70, 0)
return "Welcome home!" -- a returned string is sent to the player
end)
```
`ctx` has `player`, `args` (array of strings) and `name`. Names are what is typed
after the first slash: `mc.command("/set", ...)` is `//set` in game. `op = true`
restricts the command to operators (`ops.txt`).
## Players
`mc.players()`, `mc.player("name")`, `mc.broadcast(text)`
| method | |
|---|---|
| `p.name`, `p.id`, `p.data` | `data` is a free table for your mod |
| `p:pos()` → x, y, z | feet position |
| `p:block_pos()` → x, y, z | integer block of the feet |
| `p:look()` → yaw, pitch | |
| `p:facing()` → 0..3, dx, dz | south, west, north, east |
| `p:teleport(x, y, z [, yaw, pitch])` | |
| `p:say(text)` | private message |
| `p:is_op()` | |
| `p:held()` → id, data, count | |
| `p:give(id [, count [, data]])` | |
| `p:target([distance])` → x, y, z, face | block in the crosshair |
| `p:gamemode()` | 0 survival, 1 creative |
## World
```lua
mc.world.get_block(x, y, z) -- id, data
mc.world.set_block(x, y, z, id, data) -- normal change (updates neighbours, notifies clients)
mc.world.set_block(x, y, z, id, data, true) -- "silent": no updates; call mc.world.flush() afterwards
mc.world.flush() -- relight + resend every chunk touched by silent writes
mc.world.height(x, z) -- highest solid block, -1 if none
mc.world.is_loaded(x, z) -- block coordinates
mc.world.ensure_loaded(x, z, radiusInChunks)
mc.world.spawn_mob(mc.mob.pig, x, y, z) -- returns entity id
mc.world.drop_item(id, count, data, x, y, z)
mc.world.explode(x, y, z, radius)
mc.world.butcher(x, y, z, radius, includeFriendly) -- radius 0 = everywhere, returns count
mc.world.get_time() / set_time(t) / seed()
```
The world is infinite: chunks around players are generated, saved and unloaded
on demand. Use `ensure_loaded` before touching far-away coordinates.
## Names and ids
`mc.block.parse("stone")`, `mc.block.parse("35:14")`, `mc.block.parse("red_wool")` → id, data
`mc.block.name(id)`, `mc.item.wooden_axe`, `mc.mob.zombie`, …
## Scheduler and utilities
```lua
local id = mc.after(40, function() ... end) -- ticks
mc.every(20, function() ... end)
mc.cancel(id)
mc.log("text")
mc.save_table("mods/data/x.lua", tbl) / mc.load_table(path, default)
```
# Bundled mods
* **worldedit** – a port of EngineHub's WorldEdit command set (see below).
* **hello** – the smallest possible example.
## WorldEdit
Give yourself the wand with `//wand` (a wooden axe): left click = position 1,
right click = position 2. Operators only. Implemented commands:
`//wand //pos1 //pos2 //hpos1 //hpos2 //chunk //sel //expand //contract //shift //outset //inset //trim //size //count //distr`
`//set //replace //overlay //center //naturalize //walls //faces //hollow //smooth //move //stack //line`
`//sphere //hsphere //cyl //hcyl //cone //pyramid //hpyramid`
`//copy //cut //paste //rotate //flip /clearclipboard /schematic save|load|list|delete`
`/undo /redo /clearhistory //fill //fillr //drain /fixwater /fixlava /removeabove /removebelow /removenear /replacenear`
`/snow /thaw /green /extinguish /butcher //limit /toggleplace /we`
`/unstuck /ascend /descend /ceil /thru /jumpto /up`
`/tool (repl, info, farwand, navwand, selwand, deltree, floodfill, none) /brush (sphere, cylinder, set, smooth, raise, lower, gravity, extinguish, butcher) /mask /material /range /size // /sp`
Patterns: `stone`, `35:14`, `red_wool`, `50%stone,50%dirt`. Masks: `stone,dirt`, `!air`,
`#existing`, `#solid`. Flags work like in the original (`//sphere -h stone 5`).

22
mods/hello.lua Normal file
View file

@ -0,0 +1,22 @@
-- The smallest mod: greets players and adds /hello and /where.
mc.on("join", function(player)
player:say("Welcome, " .. player.name .. "! Lua mods are running on this world.")
end)
mc.command("hello", { description = "Say hello" }, function(ctx)
return "Hello, " .. ctx.player.name .. "!"
end)
mc.command("where", { description = "Show your coordinates" }, function(ctx)
local x, y, z = ctx.player:block_pos()
return string.format("You are at %d, %d, %d", x, y, z)
end)
mc.command("tp", { description = "Teleport: /tp <x> <y> <z>", usage = "/tp <x> <y> <z>", op = true }, function(ctx)
local x, y, z = tonumber(ctx.args[1]), tonumber(ctx.args[2]), tonumber(ctx.args[3])
if not (x and y and z) then return "Usage: /tp <x> <y> <z> (y = 0 puts you on the ground)" end
if y <= 0 then mc.world.ensure_loaded(x, z, 1); y = mc.world.height(math.floor(x), math.floor(z)) + 1 end
ctx.player:teleport(x + 0.5, y, z + 0.5)
return string.format("Teleported to %d, %d, %d", x, y, z)
end)

450
mods/worldedit/lib.lua Normal file
View file

@ -0,0 +1,450 @@
-- WorldEdit for MinecraftPE: core library
-- (edit sessions, patterns, masks, region helpers, shapes, history)
local L = {}
local floor, ceil, abs, min, max, sqrt = math.floor, math.ceil, math.abs, math.min, math.max, math.sqrt
local get_block, set_block = mc.world.get_block, mc.world.set_block
L.DEFAULT_LIMIT = 5000000
-- =========================================================== player sessions
local sessions = {}
function L.session(player)
local s = sessions[player.name]
if not s then
s = {
pos1 = nil, pos2 = nil,
clipboard = nil,
undo = {}, redo = {},
limit = L.DEFAULT_LIMIT,
tools = {}, -- item id -> { type = "repl"/"info"/"brush"/..., ... }
superpick = nil, -- nil | "single" | "area" | "recursive"
superpick_range = 3,
brush_size = 5, brush_mask = nil, brush_material = nil, brush_range = 200,
selector = "cuboid",
}
sessions[player.name] = s
end
return s
end
-- ================================================================== helpers
function L.region(s)
if not s.pos1 or not s.pos2 then return nil end
local a, b = s.pos1, s.pos2
return {
x0 = min(a[1], b[1]), y0 = min(a[2], b[2]), z0 = min(a[3], b[3]),
x1 = max(a[1], b[1]), y1 = max(a[2], b[2]), z1 = max(a[3], b[3]),
}
end
function L.volume(r)
return (r.x1 - r.x0 + 1) * (r.y1 - r.y0 + 1) * (r.z1 - r.z0 + 1)
end
local function clampY(y) return max(0, min(127, y)) end
L.clampY = clampY
--- Loads every chunk the region touches.
function L.load_region(r)
for cx = floor(r.x0 / 16), floor(r.x1 / 16) do
for cz = floor(r.z0 / 16), floor(r.z1 / 16) do
mc.world.ensure_loaded(cx * 16 + 8, cz * 16 + 8, 0)
end
end
end
local DIRS = {
up = { 0, 1, 0 }, u = { 0, 1, 0 }, down = { 0, -1, 0 }, d = { 0, -1, 0 },
north = { 0, 0, -1 }, n = { 0, 0, -1 }, south = { 0, 0, 1 }, s = { 0, 0, 1 },
east = { 1, 0, 0 }, e = { 1, 0, 0 }, west = { -1, 0, 0 }, w = { -1, 0, 0 },
}
--- Direction word -> unit vector. "me"/nil = where the player looks (incl. up/down)
function L.direction(player, word)
word = word and string.lower(word)
if word and DIRS[word] then return DIRS[word] end
local yaw, pitch = player:look()
if pitch < -50 then return DIRS.up end
if pitch > 50 then return DIRS.down end
local _, dx, dz = player:facing()
return { dx, 0, dz }
end
--- Splits "-abc foo 5 -p 2" into flags and positional arguments.
--- `valued` is a set of flags that take a value: { p = true }
function L.parse(args, valued)
local flags, pos = {}, {}
local i = 1
while i <= #args do
local a = args[i]
if a:match("^%-%a+$") and not tonumber(a) then
for ch in a:sub(2):gmatch(".") do
if valued and valued[ch] then
i = i + 1
flags[ch] = args[i]
else
flags[ch] = true
end
end
else
pos[#pos + 1] = a
end
i = i + 1
end
return flags, pos
end
-- ================================================================== patterns
-- "stone" "5%stone,5%dirt:1,air" "35:14"
function L.pattern(text)
if not text or text == "" then return nil, "No pattern given." end
local entries, total = {}, 0
for part in text:gmatch("[^,]+") do
local weight, spec = part:match("^([%d%.]+)%%(.+)$")
weight = tonumber(weight) or 1
spec = spec or part
local id, data = mc.block.parse(spec)
if not id then return nil, "Unknown block: " .. spec end
entries[#entries + 1] = { id = id, data = data, w = weight }
total = total + weight
end
if #entries == 1 then
local e = entries[1]
return function() return e.id, e.data end, entries[1]
end
return function()
local r = math.random() * total
for _, e in ipairs(entries) do
r = r - e.w
if r <= 0 then return e.id, e.data end
end
local e = entries[#entries]
return e.id, e.data
end
end
-- masks: "stone" "stone,dirt" "!air" "#existing" "#solid"
function L.mask(text)
if not text or text == "" then return nil end
local negate = false
if text:sub(1, 1) == "!" then negate = true; text = text:sub(2) end
local test
if text == "#existing" then
test = function(id) return id ~= 0 end
elseif text == "#solid" then
test = function(id) return id ~= 0 and id ~= 8 and id ~= 9 and id ~= 10 and id ~= 11 end
elseif text == "#air" then
test = function(id) return id == 0 end
else
local set = {}
for part in text:gmatch("[^,]+") do
local id, data = mc.block.parse(part)
if not id then return nil, "Unknown block: " .. part end
set[#set + 1] = { id, data }
end
test = function(id, data)
for _, e in ipairs(set) do
if e[1] == id and (e[2] == nil or e[2] == data) then return true end
end
return false
end
end
if negate then return function(id, data) return not test(id, data) end end
return test
end
-- ============================================================== edit sessions
local Edit = {}
Edit.__index = Edit
function L.new_edit(session)
return setmetatable({ s = session, entries = {}, index = {}, count = 0, limit = session.limit }, Edit)
end
local OFFSET = 1000000
--- Sets a block (recording the old one for undo). Returns true when something changed.
function Edit:set(x, y, z, id, data)
if y < 0 or y > 127 then return false end
data = data or 0
local oid, od = get_block(x, y, z)
if oid == id and od == data then return false end
if self.limit >= 0 and self.count >= self.limit then
self.overflow = true
return false
end
if not self.bx then self.bx, self.bz = x, z end
local key = ((x - self.bx + OFFSET) * 4000000 + (z - self.bz + OFFSET)) * 128 + y
local e = self.index[key]
if not e then
e = { x, y, z, oid, od, id, data }
self.index[key] = e
self.entries[#self.entries + 1] = e
else
e[6], e[7] = id, data
end
self.count = self.count + 1
set_block(x, y, z, id, data, true)
return true
end
function Edit:get(x, y, z)
return get_block(x, y, z)
end
--- Writes the pattern into the block
function Edit:place(x, y, z, pattern)
local id, data = pattern()
return self:set(x, y, z, id, data)
end
--- Finishes the edit: relights/resends the touched chunks and stores it in the history
function Edit:commit()
mc.world.flush()
if #self.entries > 0 then
local undo = self.s.undo
undo[#undo + 1] = self.entries
if #undo > 40 then table.remove(undo, 1) end
self.s.redo = {}
end
return #self.entries
end
local function apply_history(entries, reverse)
local changed = 0
if reverse then
for i = #entries, 1, -1 do
local e = entries[i]
set_block(e[1], e[2], e[3], e[4], e[5], true)
changed = changed + 1
end
else
for i = 1, #entries do
local e = entries[i]
set_block(e[1], e[2], e[3], e[6], e[7], true)
changed = changed + 1
end
end
mc.world.flush()
return changed
end
function L.undo(s)
local e = table.remove(s.undo)
if not e then return nil end
s.redo[#s.redo + 1] = e
return apply_history(e, true)
end
function L.redo(s)
local e = table.remove(s.redo)
if not e then return nil end
s.undo[#s.undo + 1] = e
return apply_history(e, false)
end
-- ============================================================ region iteration
function L.each(r, fn)
for x = r.x0, r.x1 do
for z = r.z0, r.z1 do
for y = r.y0, r.y1 do
fn(x, y, z)
end
end
end
end
function L.walls_and_faces(r, edit, pattern, floorAndCeil)
L.each(r, function(x, y, z)
local wall = x == r.x0 or x == r.x1 or z == r.z0 or z == r.z1
local cap = y == r.y0 or y == r.y1
if wall or (floorAndCeil and cap) then edit:place(x, y, z, pattern) end
end)
end
-- ================================================================== shapes
local function lsq(x, y, z) return x * x + y * y + z * z end
--- WorldEdit's ellipsoid. (cx,cy,cz) is the centre block.
function L.sphere(edit, cx, cy, cz, pattern, rx, ry, rz, filled)
rx, ry, rz = rx + 0.5, ry + 0.5, rz + 0.5
local irx, iry, irz = 1 / rx, 1 / ry, 1 / rz
local crx, cry, crz = ceil(rx), ceil(ry), ceil(rz)
local nextXn = 0
for x = 0, crx do
local xn = nextXn
nextXn = (x + 1) * irx
local nextYn = 0
for y = 0, cry do
local yn = nextYn
nextYn = (y + 1) * iry
local nextZn = 0
for z = 0, crz do
local zn = nextZn
nextZn = (z + 1) * irz
if lsq(xn, yn, zn) > 1 then break end
local skip = false
if not filled then
if lsq(nextXn, yn, zn) <= 1 and lsq(xn, nextYn, zn) <= 1 and lsq(xn, yn, nextZn) <= 1 then
skip = true
end
end
if not skip then
for sx = -1, 1, 2 do
for sy = -1, 1, 2 do
for sz = -1, 1, 2 do
if (x ~= 0 or sx == 1) and (y ~= 0 or sy == 1) and (z ~= 0 or sz == 1) then
edit:place(cx + sx * x, cy + sy * y, cz + sz * z, pattern)
end
end
end
end
end
end
end
end
end
function L.cylinder(edit, cx, cy, cz, pattern, rx, rz, height, filled)
rx, rz = rx + 0.5, rz + 0.5
if height == 0 then return end
local irx, irz = 1 / rx, 1 / rz
local crx, crz = ceil(rx), ceil(rz)
local ys, ye = cy, cy + height - 1
if height < 0 then ys, ye = cy + height + 1, cy end
local nextXn = 0
for x = 0, crx do
local xn = nextXn
nextXn = (x + 1) * irx
local nextZn = 0
for z = 0, crz do
local zn = nextZn
nextZn = (z + 1) * irz
if lsq(xn, 0, zn) > 1 then break end
local skip = false
if not filled then
if lsq(nextXn, 0, zn) <= 1 and lsq(xn, 0, nextZn) <= 1 then skip = true end
end
if not skip then
for sx = -1, 1, 2 do
for sz = -1, 1, 2 do
if (x ~= 0 or sx == 1) and (z ~= 0 or sz == 1) then
for y = ys, ye do
edit:place(cx + sx * x, y, cz + sz * z, pattern)
end
end
end
end
end
end
end
end
function L.cone(edit, cx, cy, cz, pattern, rx, rz, height, filled)
for h = 0, height - 1 do
local f = 1 - h / height
L.cylinder(edit, cx, cy + h, cz, pattern, max(0, rx * f), max(0, rz * f), 1, filled)
end
end
function L.pyramid(edit, cx, cy, cz, pattern, size, filled)
local height = size
for y = 0, height do
size = size - 1
for x = 0, size do
for z = 0, size do
if (filled and z <= size and x <= size) or z == size or x == size then
edit:place(cx + x, cy + y, cz + z, pattern)
edit:place(cx - x, cy + y, cz + z, pattern)
edit:place(cx + x, cy + y, cz - z, pattern)
edit:place(cx - x, cy + y, cz - z, pattern)
end
end
end
end
end
--- Line through block space; thickness > 0 puts a sphere of that radius on every point.
function L.line(edit, a, b, pattern, radius, filled)
local dx, dy, dz = b[1] - a[1], b[2] - a[2], b[3] - a[3]
local steps = max(abs(dx), abs(dy), abs(dz))
local seen = {}
for i = 0, steps do
local t = steps == 0 and 0 or i / steps
local x = floor(a[1] + dx * t + 0.5)
local y = floor(a[2] + dy * t + 0.5)
local z = floor(a[3] + dz * t + 0.5)
if radius and radius > 0 then
L.sphere(edit, x, y, z, pattern, radius, radius, radius, filled ~= false)
else
edit:place(x, y, z, pattern)
end
end
end
-- ============================================================== block helpers
local function is_air(id) return id == 0 end
local LIQUID = { [8] = true, [9] = true, [10] = true, [11] = true }
function L.is_liquid(id) return LIQUID[id] == true end
function L.is_air(id) return is_air(id) end
--- Top block (y) that is not air within [y0, y1] for the column, or nil
function L.top_existing(x, z, y0, y1)
for y = y1, y0, -1 do
if get_block(x, y, z) ~= 0 then return y end
end
return nil
end
--- Top solid (non liquid/plant) block y in the column
local PLANTS = { [6] = true, [31] = true, [37] = true, [38] = true, [39] = true, [40] = true, [50] = true,
[51] = true, [59] = true, [83] = true, [78] = true, [81] = false, [18] = false }
function L.top_ground(x, z, y0, y1)
for y = y1, y0, -1 do
local id = get_block(x, y, z)
if id ~= 0 and not LIQUID[id] and not PLANTS[id] and id ~= 17 and id ~= 18 then return y end
end
return nil
end
-- ======================================================== rotation of block data
-- data values that point in a direction, rotated 90 degrees clockwise (y axis)
local ROT = {
stairs = { [0] = 2, [1] = 3, [2] = 1, [3] = 0 }, -- east,west,south,north
torch = { [1] = 3, [2] = 4, [3] = 2, [4] = 1 },
ladder = { [2] = 5, [3] = 4, [4] = 2, [5] = 3 }, -- chest, furnace, ladder, signs
door = { [0] = 1, [1] = 2, [2] = 3, [3] = 0 },
trapdoor = { [0] = 3, [1] = 2, [2] = 0, [3] = 1 },
}
local KIND = {
[53] = "stairs", [67] = "stairs", [108] = "stairs", [109] = "stairs", [114] = "stairs", [128] = "stairs",
[156] = "stairs",
[50] = "torch", [75] = "torch", [76] = "torch",
[65] = "ladder", [54] = "ladder", [61] = "ladder", [62] = "ladder", [68] = "ladder", [86] = "ladder",
[91] = "ladder",
[64] = "door", [71] = "door", [107] = "door",
[96] = "trapdoor",
}
function L.rotate_data(id, data, turns)
local kind = KIND[id]
if not kind then return data end
local map = ROT[kind]
turns = turns % 4
for _ = 1, turns do
local flags, d = 0, data
if kind == "stairs" then
flags = bit.band(d, 4); d = bit.band(d, 3)
elseif kind == "door" or kind == "trapdoor" then
flags = bit.band(d, bit.bnot(3)); d = bit.band(d, 3)
end
d = map[d] or d
data = bit.bor(d, flags)
end
return data
end
return L

1574
mods/worldedit/main.lua Normal file

File diff suppressed because it is too large Load diff

76
package-windows.ps1 Normal file
View file

@ -0,0 +1,76 @@
<#
Builds the Windows client and dedicated server (Release, x64) and assembles
ready to run folders:
dist\MinecraftPE-win64\ client (MinecraftPE.exe, data\, lua\, mods\)
dist\MinecraftPE-server-win64\ server (MinecraftPE-server.exe, lua\, mods\)
Requirements: Visual Studio 2022 (C++ workload) and CMake. The first run downloads
the dependencies (zlib, libpng, glfw, OpenAL Soft, LuaJIT, stb) with git.
.\package-windows.ps1 full build + package
.\package-windows.ps1 -NoBuild only (re)assemble dist from an existing build
.\package-windows.ps1 -Jobs 2 fewer parallel compiler jobs (low memory machines)
#>
param(
[switch]$NoBuild,
[int]$Jobs = 4
)
$ErrorActionPreference = 'Stop'
$root = $PSScriptRoot
$build = Join-Path $root 'build'
$dist = Join-Path $root 'dist'
# The dependencies are cloned with git; drives that do not record file ownership make git refuse
# that ("dubious ownership"). Tell git to trust directories for this process only.
$env:GIT_CONFIG_COUNT = '1'
$env:GIT_CONFIG_KEY_0 = 'safe.directory'
$env:GIT_CONFIG_VALUE_0 = '*'
if (-not $NoBuild) {
cmake -S $root -B $build -G 'Visual Studio 17 2022' -A x64
if ($LASTEXITCODE -ne 0) { throw 'CMake configure failed' }
# OpenAL Soft needs a lot of memory per compiler process, so the compiler parallelism is limited
cmake --build $build --config Release --parallel $Jobs -- /p:CL_MPCount=2
if ($LASTEXITCODE -ne 0) { throw 'Build failed' }
}
$rel = Join-Path $build 'Release'
foreach ($f in 'MinecraftPE.exe', 'MinecraftPE-server.exe') {
if (-not (Test-Path (Join-Path $rel $f))) { throw "$f not found in $rel" }
}
if (Test-Path $dist) { Remove-Item $dist -Recurse -Force }
# ---- client
$client = Join-Path $dist 'MinecraftPE-win64'
New-Item -ItemType Directory -Force $client | Out-Null
Copy-Item (Join-Path $rel 'MinecraftPE.exe') $client
Get-ChildItem $rel -Filter *.dll | Copy-Item -Destination $client
Copy-Item (Join-Path $root 'data') $client -Recurse
Copy-Item (Join-Path $root 'lua') $client -Recurse
Copy-Item (Join-Path $root 'mods') $client -Recurse
# ---- server
$server = Join-Path $dist 'MinecraftPE-server-win64'
New-Item -ItemType Directory -Force $server | Out-Null
Copy-Item (Join-Path $rel 'MinecraftPE-server.exe') $server
Copy-Item (Join-Path $root 'lua') $server -Recurse
Copy-Item (Join-Path $root 'mods') $server -Recurse
@"
port=19132
level-dir=level
level-cachepath=.
level-externalpath=.
gamemode=creative
level-name=level
view-distance=10
"@ | Set-Content (Join-Path $server 'server.properties') -Encoding ascii
Set-Content (Join-Path $server 'start-server.bat') "@echo off`r`nMinecraftPE-server.exe`r`npause" -Encoding ascii
Write-Host ''
Write-Host 'Done:'
Write-Host " $client"
Write-Host " $server"

View file

@ -965,5 +965,5 @@ desc.netherbrickitem=Used to form blocks of Nether bricks.
desc.netherquartz=Quartz from the Nether, used to create Blocks of Quartz.
desc.quartzblock=Decorative block, used to create other kinds of Quartz blocks.
desc.stonecutter=For crafting stoneblocks.
desc.seedsmelon=Allows for more melons.
desc.seeds_melon=Allows for more melons.
desc.tile.melon=Can be cut up and eaten.

View file

@ -47,6 +47,8 @@
9D293CE816071C08000305C8 /* CreateNewWorld_iphone.xib in Resources */ = {isa = PBXBuildFile; fileRef = 9D293CE616071C08000305C8 /* CreateNewWorld_iphone.xib */; };
9D293CEB160720D6000305C8 /* worldname_iphone5_3.png in Resources */ = {isa = PBXBuildFile; fileRef = 9D293CEA160720D6000305C8 /* worldname_iphone5_3.png */; };
9D293CEC160720D6000305C8 /* worldname_iphone5_3.png in Resources */ = {isa = PBXBuildFile; fileRef = 9D293CEA160720D6000305C8 /* worldname_iphone5_3.png */; };
BEEF202614CFF670005F0002 /* Lighting.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEEF202614CFF670005F0001 /* Lighting.cpp */; };
BEEF202614CFF670005F0003 /* Lighting.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEEF202614CFF670005F0001 /* Lighting.cpp */; };
D506D3E2161288BD0099FA65 /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 9D959AFF16036BEE00E23A6F /* Default-568h@2x.png */; };
D51DC73614581D4E00E3D761 /* itemframe.png in Resources */ = {isa = PBXBuildFile; fileRef = D51DC73514581D4E00E3D761 /* itemframe.png */; };
D51DC74314592B8B00E3D761 /* PVRTexture.m in Sources */ = {isa = PBXBuildFile; fileRef = D51DC74214592B8A00E3D761 /* PVRTexture.m */; };
@ -1179,8 +1181,19 @@
F99F0FAD2F8436CE00F2B29A /* FoliageColor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F99F0FAB2F8436CE00F2B29A /* FoliageColor.cpp */; };
F99F0FAF2F8436EB00F2B29A /* Color.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F99F0FAE2F8436EB00F2B29A /* Color.cpp */; };
F99F0FB02F8436EB00F2B29A /* Color.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F99F0FAE2F8436EB00F2B29A /* Color.cpp */; };
BEEF202614CFF670005F0002 /* Lighting.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEEF202614CFF670005F0001 /* Lighting.cpp */; };
BEEF202614CFF670005F0003 /* Lighting.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEEF202614CFF670005F0001 /* Lighting.cpp */; };
F9E5A772300E7A8700164066 /* LevelConstants.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A771300E7A8700164066 /* LevelConstants.cpp */; };
F9E5A775300E7AB700164066 /* CommandManager.hpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A773300E7AB700164066 /* CommandManager.hpp */; };
F9E5A776300E7AB700164066 /* CommandManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A774300E7AB700164066 /* CommandManager.cpp */; };
F9E5A779300E7AD500164066 /* CommandBan.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A777300E7AD500164066 /* CommandBan.cpp */; };
F9E5A77A300E7AD500164066 /* CommandBan.hpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A778300E7AD500164066 /* CommandBan.hpp */; };
F9E5A77D300E7AF400164066 /* CommandHelp.hpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A77B300E7AF400164066 /* CommandHelp.hpp */; };
F9E5A77E300E7AF400164066 /* CommandHelp.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A77C300E7AF400164066 /* CommandHelp.cpp */; };
F9E5A783300E7B0B00164066 /* CommandKick.hpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A77F300E7B0A00164066 /* CommandKick.hpp */; };
F9E5A784300E7B0B00164066 /* CommandOp.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A780300E7B0A00164066 /* CommandOp.cpp */; };
F9E5A785300E7B0B00164066 /* CommandKick.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A781300E7B0B00164066 /* CommandKick.cpp */; };
F9E5A786300E7B0B00164066 /* CommandOp.hpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A782300E7B0B00164066 /* CommandOp.hpp */; };
F9E5A789300E7B3400164066 /* Command.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A787300E7B3400164066 /* Command.cpp */; };
F9E5A78A300E7B3400164066 /* Command.hpp in Sources */ = {isa = PBXBuildFile; fileRef = F9E5A788300E7B3400164066 /* Command.hpp */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@ -1248,6 +1261,7 @@
9D293CE616071C08000305C8 /* CreateNewWorld_iphone.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = CreateNewWorld_iphone.xib; path = minecraftpe/dialogs/CreateNewWorld_iphone.xib; sourceTree = "<group>"; };
9D293CEA160720D6000305C8 /* worldname_iphone5_3.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = worldname_iphone5_3.png; sourceTree = "<group>"; };
9D959AFF16036BEE00E23A6F /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = "<group>"; };
BEEF202614CFF670005F0001 /* Lighting.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Lighting.cpp; sourceTree = "<group>"; };
D51A8B01146A200000E5D720 /* minecraftpedemo-info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "minecraftpedemo-info.plist"; sourceTree = "<group>"; };
D51DC73514581D4E00E3D761 /* itemframe.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = itemframe.png; sourceTree = "<group>"; };
D51DC74114592B8A00E3D761 /* PVRTexture.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PVRTexture.h; sourceTree = "<group>"; };
@ -2468,7 +2482,19 @@
F99F0FA82F84369F00F2B29A /* GrassColor.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = GrassColor.cpp; sourceTree = "<group>"; };
F99F0FAB2F8436CE00F2B29A /* FoliageColor.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = FoliageColor.cpp; sourceTree = "<group>"; };
F99F0FAE2F8436EB00F2B29A /* Color.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = Color.cpp; sourceTree = "<group>"; };
BEEF202614CFF670005F0001 /* Lighting.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Lighting.cpp; path = Lighting.cpp; sourceTree = "<group>"; };
F9E5A771300E7A8700164066 /* LevelConstants.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = LevelConstants.cpp; path = ../../src/world/level/LevelConstants.cpp; sourceTree = "<group>"; };
F9E5A773300E7AB700164066 /* CommandManager.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = CommandManager.hpp; path = ../../src/commands/CommandManager.hpp; sourceTree = "<group>"; };
F9E5A774300E7AB700164066 /* CommandManager.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = CommandManager.cpp; path = ../../src/commands/CommandManager.cpp; sourceTree = "<group>"; };
F9E5A777300E7AD500164066 /* CommandBan.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = CommandBan.cpp; path = ../../src/commands/CommandBan.cpp; sourceTree = "<group>"; };
F9E5A778300E7AD500164066 /* CommandBan.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = CommandBan.hpp; path = ../../src/commands/CommandBan.hpp; sourceTree = "<group>"; };
F9E5A77B300E7AF400164066 /* CommandHelp.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = CommandHelp.hpp; path = ../../src/commands/CommandHelp.hpp; sourceTree = "<group>"; };
F9E5A77C300E7AF400164066 /* CommandHelp.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = CommandHelp.cpp; path = ../../src/commands/CommandHelp.cpp; sourceTree = "<group>"; };
F9E5A77F300E7B0A00164066 /* CommandKick.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = CommandKick.hpp; path = ../../src/commands/CommandKick.hpp; sourceTree = "<group>"; };
F9E5A780300E7B0A00164066 /* CommandOp.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = CommandOp.cpp; path = ../../src/commands/CommandOp.cpp; sourceTree = "<group>"; };
F9E5A781300E7B0B00164066 /* CommandKick.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = CommandKick.cpp; path = ../../src/commands/CommandKick.cpp; sourceTree = "<group>"; };
F9E5A782300E7B0B00164066 /* CommandOp.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = CommandOp.hpp; path = ../../src/commands/CommandOp.hpp; sourceTree = "<group>"; };
F9E5A787300E7B3400164066 /* Command.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = Command.cpp; path = ../../src/commands/Command.cpp; sourceTree = "<group>"; };
F9E5A788300E7B3400164066 /* Command.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; name = Command.hpp; path = ../../src/commands/Command.hpp; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@ -4319,6 +4345,19 @@
D5CF9C37144C225000E4244F = {
isa = PBXGroup;
children = (
F9E5A788300E7B3400164066 /* Command.hpp */,
F9E5A787300E7B3400164066 /* Command.cpp */,
F9E5A77F300E7B0A00164066 /* CommandKick.hpp */,
F9E5A781300E7B0B00164066 /* CommandKick.cpp */,
F9E5A782300E7B0B00164066 /* CommandOp.hpp */,
F9E5A780300E7B0A00164066 /* CommandOp.cpp */,
F9E5A77B300E7AF400164066 /* CommandHelp.hpp */,
F9E5A77C300E7AF400164066 /* CommandHelp.cpp */,
F9E5A778300E7AD500164066 /* CommandBan.hpp */,
F9E5A777300E7AD500164066 /* CommandBan.cpp */,
F9E5A773300E7AB700164066 /* CommandManager.hpp */,
F9E5A774300E7AB700164066 /* CommandManager.cpp */,
F9E5A771300E7A8700164066 /* LevelConstants.cpp */,
F99D344D2F7372A100DC153E /* Launch Screen.storyboard */,
D5E1BA9A1451C8A0007DCC4F /* Default@2x.png */,
9D959AFF16036BEE00E23A6F /* Default-568h@2x.png */,
@ -5451,6 +5490,19 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
F9E5A789300E7B3400164066 /* Command.cpp in Sources */,
F9E5A78A300E7B3400164066 /* Command.hpp in Sources */,
F9E5A783300E7B0B00164066 /* CommandKick.hpp in Sources */,
F9E5A784300E7B0B00164066 /* CommandOp.cpp in Sources */,
F9E5A785300E7B0B00164066 /* CommandKick.cpp in Sources */,
F9E5A786300E7B0B00164066 /* CommandOp.hpp in Sources */,
F9E5A77D300E7AF400164066 /* CommandHelp.hpp in Sources */,
F9E5A77E300E7AF400164066 /* CommandHelp.cpp in Sources */,
F9E5A779300E7AD500164066 /* CommandBan.cpp in Sources */,
F9E5A77A300E7AD500164066 /* CommandBan.hpp in Sources */,
F9E5A775300E7AB700164066 /* CommandManager.hpp in Sources */,
F9E5A776300E7AB700164066 /* CommandManager.cpp in Sources */,
F9E5A772300E7A8700164066 /* LevelConstants.cpp in Sources */,
F912B8CF2F6C3D5200BC60DF /* TextBox.h in Sources */,
D5CF9C57144C225000E4244F /* main.mm in Sources */,
D5CF9C5B144C225000E4244F /* minecraftpeAppDelegate.mm in Sources */,

View file

@ -142,8 +142,8 @@ void seedMT( unsigned int seed, unsigned int *state, unsigned int *&next, int &l
// so-- that's why the only change I made is to restrict to odd seeds.
//
unsigned int x = ( seed | 1U ) & 0xFFFFFFFFU, *s = state;
int j;
register unsigned int x = ( seed | 1U ) & 0xFFFFFFFFU, *s = state;
register int j;
for ( left = 0, *s++ = x, j = N; --j;
*s++ = ( x *= 69069U ) & 0xFFFFFFFFU )
@ -154,8 +154,8 @@ void seedMT( unsigned int seed, unsigned int *state, unsigned int *&next, int &l
unsigned int reloadMT( unsigned int *state, unsigned int *&next, int &left )
{
unsigned int * p0 = state, *p2 = state + 2, *pM = state + M, s0, s1;
int j;
register unsigned int * p0 = state, *p2 = state + 2, *pM = state + M, s0, s1;
register int j;
if ( left < -1 )
seedMT( 4357U );

View file

@ -4,12 +4,11 @@ namespace Common {
std::string getGameVersionString(const std::string& versionSuffix /* = "" */)
{
std::string result = std::string("v0.6.1") + versionSuffix;
std::string result = std::string("v0.1.0 (forked from v0.6.1 alpha)") + versionSuffix;
// append 64-bit port marker only on Android 64‑bit targets
#if defined(ANDROID) && (defined(__aarch64__) || defined(__x86_64__))
result += " (64-bit port)";
result += " (64-bit)";
#endif
result += " alpha";
return result;
}

View file

@ -16,8 +16,8 @@ namespace SharedConstants
{
// 0.5.0 uses NPv8
// 0.6.0 uses NPv9
const int NetworkProtocolVersion = 9;
const int NetworkProtocolLowestSupportedVersion = 9;
const int NetworkProtocolVersion = 10;
const int NetworkProtocolLowestSupportedVersion = 10;
const int GameProtocolVersion = 1;
const int GameProtocolLowestSupportedVersion = 1;

View file

@ -3,6 +3,7 @@
#include "client/Options.h"
#include "client/player/input/IBuildInput.h"
#include "commands/CommandManager.hpp"
#include "lua/LuaEngine.h"
#include "platform/input/Keyboard.h"
#include "world/item/Item.h"
#include "world/item/ItemInstance.h"
@ -223,6 +224,7 @@ Minecraft::~Minecraft()
screen = NULL;
}
#endif
LuaEngine::get().stop();
if (level != NULL) {
level->saveGame();
if (level->getChunkSource())
@ -287,9 +289,13 @@ void Minecraft::setLevel(Level* level, const std::string& message /* ="" */, Loc
}
}
this->level = level;
// So uhhh
std::string op = options.getStringValue(OPTIONS_USERNAME);
std::transform(op.begin(), op.end(), op.begin(), ::tolower);
level->ops.emplace(op);
_hasSignaledGeneratingLevelFinished = false;
#ifdef STANDALONE_SERVER
#if defined(STANDALONE_SERVER) || defined(PLATFORM_WEB)
const bool threadedLevelCreation = false;
#else
const bool threadedLevelCreation = true;
@ -326,6 +332,8 @@ void Minecraft::leaveGame(bool renameLevel /*=false*/)
level->getChunkSource()->saveAll(true);
}
LuaEngine::get().stop();
LOGI("Clearing levels\n");
cameraTargetPlayer = NULL;
@ -371,14 +379,22 @@ void Minecraft::prepareLevel(const std::string& title) {
if (!level->isNew())
level->setUpdateLights(false);
int Max = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH;
// The world is infinite: only the area around the spawn point is generated
// up front, everything else is streamed in around the players while playing.
if (level->isNew() && !level->isClientSide) {
level->setInitialSpawn(); // @note: should obviously be called from Level itself
}
const Pos spawn = level->getSharedSpawnPos();
const int spawnCx = spawn.x >> 4;
const int spawnCz = spawn.z >> 4;
const int PrepareRadius = level->isClientSide ? -1 : 4; // a client gets its chunks from the server
const int Max = (2 * PrepareRadius + 1) * (2 * PrepareRadius + 1);
int pp = 0;
for (int x = 8; x < (LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH); x += LevelConstants::CHUNK_WIDTH) {
for (int z = 8; z < (LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH); z += LevelConstants::CHUNK_WIDTH) {
progressStagePercentage = 100 * pp++ / Max;
//printf("level generation progress %d\n", progressStagePercentage);
for (int cx = spawnCx - PrepareRadius; cx <= spawnCx + PrepareRadius; cx++) {
for (int cz = spawnCz - PrepareRadius; cz <= spawnCz + PrepareRadius; cz++) {
progressStagePercentage = 100 * pp++ / Max;
B.start();
level->getTile(x, 64, z);
level->getChunk(cx, cz);
B.stop();
L.start();
if (level->isNew())
@ -391,11 +407,12 @@ void Minecraft::prepareLevel(const std::string& title) {
level->setUpdateLights(true);
C.start();
for (int x = 0; x < LevelConstants::CHUNK_CACHE_WIDTH; x++)
{
for (int z = 0; z < LevelConstants::CHUNK_CACHE_WIDTH; z++)
std::vector<LevelChunk*> loadedChunks;
level->getChunkSource()->getLoadedChunks(loadedChunks);
for (unsigned int i = 0; i < loadedChunks.size(); i++)
{
LevelChunk* chunk = level->getChunk(x, z);
LevelChunk* chunk = loadedChunks[i];
if (chunk && !chunk->createdFromSave)
{
chunk->unsaved = false;
@ -408,7 +425,6 @@ void Minecraft::prepareLevel(const std::string& title) {
LOGI("status: 3\n");
progressStageStatusId = 3;
if (level->isNew()) {
level->setInitialSpawn(); // @note: should obviously be called from Level itself
level->saveLevelData();
level->getChunkSource()->saveAll(false);
level->saveGame();
@ -512,7 +528,7 @@ void Minecraft::tick(int nTick, int maxTick) {
if (missTime > 0) missTime--;
#ifndef STANDALONE_SERVER
if (!screen && player) {
if (player->health <= 0) {
if (player->hasDied()) {
setScreen(new DeathScreen());
}
}
@ -566,6 +582,10 @@ void Minecraft::tick(int nTick, int maxTick) {
TIMER_POP_PUSH("level");
level->tickEntities();
level->tick();
if (!level->isClientSide) LuaEngine::get().tick();
if (level->isClientSide && netCallback && !raknetInstance->isServer()) {
((ClientSideNetworkHandler*)netCallback)->updateChunks();
}
#ifndef STANDALONE_SERVER
TIMER_POP_PUSH("animateTick");
if (player) {
@ -1210,8 +1230,6 @@ void Minecraft::init()
checkGlError("Init complete");
#endif
PluginsManager::get().init(*this);
options.load();
setIsCreativeMode(false); // false means it's Survival Mode
@ -1471,6 +1489,8 @@ void Minecraft::_levelGenerated()
level->loadPlayer(player, true);
// if we are client side, we trust the server to have given us a correct position
if (player && !level->isClientSide) {
// the saved position can be anywhere in the (infinite) world
level->ensureChunksAround((int)player->x, (int)player->z, 3);
player->resetPos(false);
}
@ -1491,6 +1511,11 @@ void Minecraft::_levelGenerated()
netCallback->levelGenerated(level);
}
// Lua mods run where the world is hosted
if (!level->isClientSide) {
LuaEngine::get().start(this);
}
#if defined(WIN32) || defined(RPI)
if (_commandServer) {
delete _commandServer;

View file

@ -3,8 +3,6 @@
#include "Options.h"
#include "commands/CommandManager.hpp"
#include <plugins/PluginsManager.hpp>
#ifndef STANDALONE_SERVER
#include "MouseHandler.h"
#include "gui/Gui.h"

View file

@ -65,17 +65,13 @@ OptionBool useVignette("useVignette", true);
OptionBool useTouchscreen("useTouchscreen", true);
OptionBool serverVisible("servervisible", true);
OptionBool foliageTint("foliagetint", true);
OptionBool foliageTint("foliagetint", false);
OptionInt fogType("fogType", 0, 0, 2);
OptionBool javaHud("javaHud", false);
OptionBool betaSky("betaSky", false);
OptionBool tintedSide("tintedSide", false);
OptionBool blockOutline("blockOutline", false);
OptionBool restoredAnims("restoredAnims", true);
@ -200,16 +196,13 @@ void Options::initTable() {
m_options[OPTIONS_ALLOW_SPRINT] = &allowSprint;
m_options[OPTIONS_RPI_CURSOR] = &rpiCursor;
m_options[OPTIONS_FOLIAGE_TINT] = &foliageTint;
// more options yay
m_options[OPTIONS_FOG_TYPE] = &fogType;
m_options[OPTIONS_DEBUG_STYLE] = &debugStyle;
m_options[OPTIONS_BETA_SKY] = &betaSky;
m_options[OPTIONS_TINTED_SIDE] = &tintedSide;
m_options[OPTIONS_JAVA_HUD] = &javaHud;
m_options[OPTIONS_AUTOJUMP] = &autoJump;

View file

@ -89,7 +89,7 @@ enum OptionId {
OPTIONS_RPI_CURSOR,
OPTIONS_FOLIAGE_TINT,
OPTIONS_FOG_TYPE,
OPTIONS_FOG_TYPE,
OPTIONS_JAVA_HUD,
OPTIONS_RESTORED_ANIMS,
OPTIONS_TINTED_SIDE,

View file

@ -16,6 +16,7 @@
#include "../renderer/LevelRenderer.h"
#endif
#include "../../world/level/material/Material.h"
#include "../../lua/LuaEngine.h"
GameMode::GameMode( Minecraft* minecraft)
: minecraft(minecraft),
@ -59,6 +60,9 @@ bool GameMode::destroyBlock(int x, int y, int z, int face) {
if (!oldTile)
return false;
if (!level->isClientSide && minecraft->player && LuaEngine::get().onBlockBreak(minecraft->player, x, y, z))
return false; // cancelled by a Lua mod
if (level->adventureSettings.immutableWorld) {
if (oldTile != (Tile*)Tile::leaves
&& oldTile->material != Material::plant) {
@ -89,6 +93,8 @@ bool GameMode::useItemOn(Player* player, Level* level, ItemInstance* item, int x
float clickX = hit.x - x;
float clickY = hit.y - y;
float clickZ = hit.z - z;
if (!level->isClientSide && player == minecraft->player && LuaEngine::get().onUseItem(player, x, y, z, face, item))
return true; // cancelled by a Lua mod
if (level->isClientSide) {
LOGI("%f %f %f \n", player->x, player->y, player->z);

View file

@ -61,6 +61,12 @@ bool Screen::handleBackEvent( bool isDown )
return false;
}
void Screen::tick() {
for (auto& textbox : textBoxes) {
textbox->tick(minecraft);
}
}
void Screen::updateEvents()
{
if (passEvents)
@ -110,10 +116,12 @@ void Screen::keyboardEvent()
keyPressed(Keyboard::getEventKey());
}
}
void Screen::keyboardTextEvent()
{
charPressed(Keyboard::getChar());
}
void Screen::renderBackground()
{
renderBackground(0);

View file

@ -31,7 +31,7 @@ public:
virtual void keyboardTextEvent();
virtual bool handleBackEvent(bool isDown);
virtual void tick() {}
virtual void tick();
virtual void removed() {}

View file

@ -35,6 +35,17 @@ void GuiElementContainer::removeChild( GuiElement* element ) {
children.erase(it);
}
bool GuiElementContainer::containsPointInChildren(int x, int y) const {
for (auto it = children.begin(); it != children.end(); ++it) {
GuiElement* child = *it;
if (child == NULL || !child->visible) continue;
if (child->pointInside(x, y)) return true;
const GuiElementContainer* container = dynamic_cast<const GuiElementContainer*>(child);
if (container != NULL && container->containsPointInChildren(x, y)) return true;
}
return false;
}
void GuiElementContainer::tick( Minecraft* minecraft ) {
for(std::vector<GuiElement*>::iterator it = children.begin(); it != children.end(); ++it) {
(*it)->tick(minecraft);

View file

@ -13,6 +13,7 @@ public:
virtual void setupPositions();
virtual void addChild(GuiElement* element);
virtual void removeChild(GuiElement* element);
bool containsPointInChildren(int x, int y) const;
virtual void tick( Minecraft* minecraft );

View file

@ -6,15 +6,26 @@
#include "../../../locale/I18n.h"
#include "TextOption.h"
#include "KeyOption.h"
#include <algorithm>
#include "../Gui.h"
#include "../Screen.h"
#include "../../../platform/input/Mouse.h"
#include "../../../util/Mth.h"
OptionsGroup::OptionsGroup( std::string labelID ) {
OptionsGroup::OptionsGroup( std::string labelID ) {
label = I18n::get(labelID);
}
void OptionsGroup::setupPositions() {
const int labelHeight = 18;
const int bottomPadding = 36;
const float requestedScroll = scrollOffsetY;
const int scrollOffset = (int)requestedScroll;
int curY = y + labelHeight - scrollOffset;
const int contentStartY = y + labelHeight;
// First we write the header and then we add the items
int curY = y + 18;
for(std::vector<GuiElement*>::iterator it = children.begin(); it != children.end(); ++it) {
for(auto it = children.begin(); it != children.end(); ++it) {
(*it)->width = width - 5;
(*it)->y = curY;
@ -22,16 +33,109 @@ void OptionsGroup::setupPositions() {
(*it)->setupPositions();
curY += (*it)->height + 3;
}
height = curY;
curY += bottomPadding;
contentHeight = std::max(0, curY - contentStartY + scrollOffset);
maxScrollOffsetY = std::max(0, contentHeight - (height - labelHeight));
const float clampedScroll = Mth::clamp(requestedScroll, 0.0f, maxScrollOffsetY);
if (clampedScroll != requestedScroll) {
scrollOffsetY = clampedScroll;
setupPositions();
}
}
void OptionsGroup::render( Minecraft* minecraft, int xm, int ym ) {
float padX = 10.0f;
float padY = 5.0f;
const int labelHeight = 18;
minecraft->font->draw(label, (float)x + padX, (float)y + padY, 0xffffffff, false);
glEnable2(GL_SCISSOR_TEST);
glScissor(
Gui::GuiScale * x,
minecraft->height - Gui::GuiScale * (y + height),
Gui::GuiScale * width,
Gui::GuiScale * (height - labelHeight)
);
super::render(minecraft, xm, ym);
glDisable2(GL_SCISSOR_TEST);
}
void OptionsGroup::tick(Minecraft* minecraft) {
int xm = Mouse::getX();
int ym = Mouse::getY();
if (minecraft->screen != NULL) {
minecraft->screen->toGUICoordinate(xm, ym);
}
bool leftDown = Mouse::isButtonDown(MouseAction::ACTION_LEFT);
if (trackingScrollGesture && leftDown) {
int dy = ym - lastDragY;
int dx = xm - dragStartX;
if (!scrollingGesture) {
int totalDx = xm - dragStartX;
int totalDy = ym - dragStartY;
if (std::abs(totalDx) >= ScrollStartThreshold || std::abs(totalDy) >= ScrollStartThreshold) {
if (std::abs(totalDy) >= std::abs(totalDx)) {
scrollingGesture = true;
} else if (!touchDispatched) {
super::mouseClicked(minecraft, touchStartX, touchStartY, MouseAction::ACTION_LEFT);
touchDispatched = true;
}
}
}
if (scrollingGesture && dy != 0) {
scrollByPixels((float)dy);
}
lastDragY = ym;
}
super::tick(minecraft);
}
void OptionsGroup::mouseClicked(Minecraft* minecraft, int x, int y, int buttonNum) {
trackingScrollGesture = false;
scrollingGesture = false;
touchDispatched = false;
if (buttonNum == MouseAction::ACTION_LEFT && pointInside(x, y)) {
trackingScrollGesture = true;
dragStartX = x;
dragStartY = y;
lastDragY = y;
touchStartX = x;
touchStartY = y;
return;
}
super::mouseClicked(minecraft, x, y, buttonNum);
}
void OptionsGroup::mouseReleased(Minecraft* minecraft, int x, int y, int buttonNum) {
bool wasScrolling = scrollingGesture;
bool wasTracking = trackingScrollGesture;
trackingScrollGesture = false;
scrollingGesture = false;
if (buttonNum == MouseAction::ACTION_LEFT && wasTracking && !touchDispatched && pointInside(touchStartX, touchStartY)) {
super::mouseClicked(minecraft, touchStartX, touchStartY, buttonNum);
touchDispatched = true;
}
if (!wasScrolling) {
super::mouseReleased(minecraft, x, y, buttonNum);
}
}
void OptionsGroup::scrollByPixels(float deltaY) {
if (deltaY == 0.0f || maxScrollOffsetY <= 0.0f) return;
scrollOffsetY = Mth::clamp(scrollOffsetY - deltaY, 0.0f, maxScrollOffsetY);
setupPositions();
}
bool OptionsGroup::isScrollingGestureActive() const {
return trackingScrollGesture || scrollingGesture;
}
OptionsGroup& OptionsGroup::addOptionItem(OptionId optId, Minecraft* minecraft ) {

View file

@ -17,7 +17,12 @@ public:
OptionsGroup(std::string labelID);
virtual void setupPositions();
virtual void render(Minecraft* minecraft, int xm, int ym);
virtual void tick(Minecraft* minecraft);
virtual void mouseClicked(Minecraft* minecraft, int x, int y, int buttonNum);
virtual void mouseReleased(Minecraft* minecraft, int x, int y, int buttonNum);
OptionsGroup& addOptionItem(OptionId optId, Minecraft* minecraft);
void scrollByPixels(float deltaY);
bool isScrollingGestureActive() const;
protected:
void createToggle(OptionId optId, Minecraft* minecraft);
@ -27,6 +32,18 @@ protected:
void createKey(OptionId optId, Minecraft* minecraft);
std::string label;
int contentHeight = 0;
float scrollOffsetY = 0.f;
float maxScrollOffsetY = 0.f;
bool trackingScrollGesture = false;
bool scrollingGesture = false;
bool touchDispatched = false;
int dragStartX = 0;
int dragStartY = 0;
int lastDragY = 0;
int touchStartX = 0;
int touchStartY = 0;
static const int ScrollStartThreshold = 5;
};
#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__OptionsGroup_H__*/

View file

@ -204,22 +204,23 @@ void ScrollingPane::render( int xm, int ym, float alpha ) {
const float bxx = bbox.x - (fpx /*+ dx*alpha*/) + (nw.xf - nw.x);
const float byy = bbox.y - (fpy /*+ dy*alpha*/) + (nw.yf - nw.y);
for (int y = nw.y; y <= se.y; ++y)
for (int x = nw.x; x <= se.x; ++x) {
int id = y * columns + x;
if (y <0 || id < 0 || id >= numItems) continue; // @todo: break rather
if (isNotSet(SF_WrapX) && (x < 0 || x >= columns)) continue; // @todo: break rather
GridItem item; //@todo: v- Does not support SF_Wrapping
item.id = id;
item.xf = bxx + x * itemBbox.w;
item.yf = byy + y * itemBbox.h;
item.x = (int)item.xf;
item.y = (int)item.yf;
//LOGI("i: %d (%.1f, %.1f)\t", id, item.xf, item.yf);
if (isSet(SF_MultiSelect)) item.selected = selected[id];
else item.selected = (id == selectedId);
for (int y = nw.y; y <= se.y; ++y) {
for (int x = nw.x; x <= se.x; ++x) {
int id = y * columns + x;
if (y <0 || id < 0 || id >= numItems) continue; // @todo: break rather
if (isNotSet(SF_WrapX) && (x < 0 || x >= columns)) continue; // @todo: break rather
GridItem item; //@todo: v- Does not support SF_Wrapping
item.id = id;
item.xf = bxx + x * itemBbox.w;
item.yf = byy + y * itemBbox.h;
item.x = (int)item.xf;
item.y = (int)item.yf;
//LOGI("i: %d (%.1f, %.1f)\t", id, item.xf, item.yf);
if (isSet(SF_MultiSelect)) item.selected = selected[id];
else item.selected = (id == selectedId);
itemsToRender.push_back(item);
itemsToRender.push_back(item);
}
}
renderBatch(itemsToRender, alpha);

View file

@ -329,7 +329,10 @@ bool ChestScreen::handleAddItem(FillingContainer* from, FillingContainer* to, in
added = (takenItem.count != wantedCount);
if (added) {
item->count -= (wantedCount - takenItem.count);
if (!minecraft->isCreativeMode()) {
item->count -= (wantedCount - takenItem.count);
}
std::vector<int> changed;
std::vector<const ItemInstance*> items = getItems(toPane);
differ.getDiff(items, changed);

View file

@ -6,9 +6,20 @@
#include "../../../world/level/Level.h"
#include "../../../network/RakNetInstance.h"
#include "../../../network/ServerSideNetworkHandler.h"
#include "../../../network/packet/ChatPacket.h"
#include "../../../network/packet/MessagePacket.h"
#include "../../../platform/log.h"
#include "util/StringUtils.h"
#include "../../../network/packet/SetSkinPacket.h"
#include <vector>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif
#include <sstream>
#include <cstdlib>
@ -63,29 +74,93 @@ void ConsoleScreen::execute()
return minecraft->setScreen(NULL);
}
// if (_input[0] == '/') {
// // Command
// _input = Util::stringTrim(_input.substr(1));
if (_input == "/skin" || _input.compare(0, 6, "/skin ") == 0) {
executeSkinCommand(_input.size() > 6 ? Util::stringTrim(_input.substr(6)) : "");
return minecraft->setScreen(NULL);
}
// std::istringstream iss(minecraft->commandManager().execute(*minecraft, *minecraft->player, _input));
// for (std::string line; std::getline(iss, line); ) {
// minecraft->gui.addMessage(line);
// }
// } else {
// @ai @rewrite
if (minecraft->netCallback && minecraft->raknetInstance->isServer()) {
static_cast<ServerSideNetworkHandler*>(minecraft->netCallback)->displayGameMessage(_input);
} else if (minecraft->netCallback) {
ChatPacket chatPkt(_input);
minecraft->raknetInstance->send(chatPkt);
} else {
minecraft->gui.addMessage("<" + minecraft->player->name + "> " + _input);
if (minecraft->netCallback && !minecraft->raknetInstance->isServer()) {
MessagePacket packet(_input.c_str());
minecraft->raknetInstance->send(packet);
} else if (_input[0] == '/') {
_input = Util::stringTrim(_input.substr(1));
std::istringstream iss(
minecraft->commandManager().execute(*minecraft, *minecraft->player, _input)
);
for (std::string line; std::getline(iss, line);) {
minecraft->gui.addMessage(line);
}
// }
}
else {
if (minecraft->raknetInstance->isServer()) {
MessagePacket packet(_input.c_str());
minecraft->raknetInstance->send(packet);
}
minecraft->gui.addMessage("<" + minecraft->player->name + "> " + _input);
}
minecraft->setScreen(NULL);
}
// /skin [list|auto|<name>]: purely client side, the choice is announced to the server
void ConsoleScreen::executeSkinCommand(const std::string& arg)
{
const std::string dir = "data/images/skins/";
std::vector<std::string> names;
#ifdef _WIN32
WIN32_FIND_DATAA fd;
HANDLE h = FindFirstFileA((dir + "*.png").c_str(), &fd);
if (h != INVALID_HANDLE_VALUE) {
do {
std::string n = fd.cFileName;
names.push_back(n.substr(0, n.size() - 4));
} while (FindNextFileA(h, &fd));
FindClose(h);
}
#endif
if (arg.empty() || arg == "list") {
std::string line = "Skins:";
for (size_t i = 0; i < names.size(); ++i) line += " " + names[i];
minecraft->gui.addMessage(line);
minecraft->gui.addMessage("Use /skin <name>, or /skin auto for the one of your account.");
return;
}
LocalPlayer* player = minecraft->player;
if (!player) return;
if (arg == "auto") {
minecraft->options.set(OPTIONS_SKIN, std::string("Default"));
minecraft->options.save();
player->skinName.clear();
player->setTextureName("skins/" + player->name + ".png");
minecraft->gui.addMessage("Skin reset, it is picked from your username after a restart.");
return;
}
bool found = false;
for (size_t i = 0; i < names.size(); ++i) if (names[i] == arg) found = true;
if (!found) {
minecraft->gui.addMessage("No skin named '" + arg + "'. Try /skin list");
return;
}
minecraft->options.set(OPTIONS_SKIN, arg);
minecraft->options.save();
player->skinName = arg;
player->setTextureName("skins/" + arg + ".png");
minecraft->gui.addMessage("You now wear the '" + arg + "' skin.");
if (minecraft->level && (minecraft->level->isClientSide || minecraft->raknetInstance->isServer())) {
SetSkinPacket packet(player->entityId, arg);
minecraft->raknetInstance->send(packet);
}
}
// ---------------------------------------------------------------------------
// render
// ---------------------------------------------------------------------------

View file

@ -25,6 +25,7 @@ public:
private:
void execute();
void executeSkinCommand(const std::string& arg);
std::string _input;
int _cursorBlink; // tick counter for cursor blink

View file

@ -72,7 +72,7 @@ void DeathScreen::render( int xm, int ym, float a )
if (minecraft->options.getIntValue(OPTIONS_MENU_STYLE) == 2){
glPushMatrix2();
glScalef2(2, 2, 2);
drawCenteredString(font, "Game over!", width / 2 / 2, height / 8, 0xffffff);
drawCenteredString(font, I18n::get("deathScreen.title.hardcore"), width / 4, height / 8, 0xffffff);
glPopMatrix2();
std::stringstream ss;
ss << "Score: &e" << minecraft->player->getScore();
@ -80,7 +80,7 @@ if (minecraft->options.getIntValue(OPTIONS_MENU_STYLE) == 2){
} else {
glPushMatrix2();
glScalef2(2, 2, 2);
drawCenteredString(font, "You died!", width / 2 / 2, height / 8, 0xffffff);
drawCenteredString(font, I18n::get("deathScreen.title"), width / 4, height / 8, 0xffffff);
glPopMatrix2();
}

View file

@ -500,6 +500,8 @@ ItemInstance FurnaceScreen::moveOver(const ItemInstance* item, int maxCount) {
setIfNotSet(doRecreatePane, newSize != oldSize);
return removed;
}
return ItemInstance();
}

View file

@ -121,6 +121,7 @@ void OptionsScreen::setupPositions() {
(*it)->x = categoryButtons[0]->width;
(*it)->y = bHeader->height;
(*it)->width = width - categoryButtons[0]->width;
(*it)->height = height - bHeader->height;
(*it)->setupPositions();
}
@ -237,8 +238,10 @@ void OptionsScreen::generateOptionScreens() {
.addOptionItem(OPTIONS_BAR_ON_TOP, minecraft)
.addOptionItem(OPTIONS_MENU_STYLE, minecraft)
.addOptionItem(OPTIONS_RPI_CURSOR, minecraft)
#ifndef __APPLE__
.addOptionItem(OPTIONS_FOLIAGE_TINT, minecraft)
.addOptionItem(OPTIONS_TINTED_SIDE, minecraft)
#endif
.addOptionItem(OPTIONS_JAVA_HUD, minecraft)
.addOptionItem(OPTIONS_FOG_TYPE, minecraft)
.addOptionItem(OPTIONS_BETA_SKY, minecraft)
@ -261,6 +264,12 @@ void OptionsScreen::mouseReleased(int x, int y, int buttonNum) {
super::mouseReleased(x, y, buttonNum);
}
void OptionsScreen::mouseWheel(int dx, int dy, int xm, int ym) {
if (currentOptionsGroup != NULL && currentOptionsGroup->pointInside(xm, ym) && dy != 0) {
currentOptionsGroup->scrollByPixels((float)dy * 18.0f);
}
}
void OptionsScreen::keyPressed(int eventKey) {
if (currentOptionsGroup != NULL)
currentOptionsGroup->keyPressed(minecraft, eventKey);

View file

@ -27,6 +27,7 @@ public:
virtual void mouseClicked(int x, int y, int buttonNum);
virtual void mouseReleased(int x, int y, int buttonNum);
virtual void mouseWheel(int dx, int dy, int xm, int ym);
virtual void keyPressed(int eventKey);
virtual void charPressed(char inputChar);

View file

@ -8,13 +8,14 @@
#include "../../../platform/time.h"
#include "../../../platform/input/Keyboard.h"
#include "../../../platform/log.h"
#include <locale/I18n.h>
SimpleChooseLevelScreen::SimpleChooseLevelScreen(const std::string& levelName)
: bHeader(0),
bGamemode(0),
bCheats(0),
bBack(0),
bCreate(0),
: bHeader(nullptr),
bGamemode(nullptr),
bCheats(nullptr),
bBack(nullptr),
bCreate(nullptr),
levelName(levelName),
hasChosen(false),
gamemode(GameType::Survival),
@ -42,10 +43,10 @@ void SimpleChooseLevelScreen::init()
// first") when the name already existed.
ChooseLevelScreen::init();
tLevelName.text = "New world";
tLevelName.text = I18n::get("selectWorld.newWorld");
// header + close button
bHeader = new Touch::THeader(0, "Create World");
bHeader = new Touch::THeader(0, I18n::get("selectWorld.create"));
// create the back/X button as ImageButton like CreditsScreen
bBack = new ImageButton(2, "");
{
@ -56,14 +57,14 @@ void SimpleChooseLevelScreen::init()
def.setSrc(IntRectangle(150, 0, (int)def.width, (int)def.height));
bBack->setImageDef(def, true);
}
if (/* minecraft->useTouchscreen() */ true) {
bGamemode = new Touch::TButton(1, "Survival mode");
if (minecraft->options.getIntValue(OPTIONS_MENU_STYLE) != 2) {
bGamemode = new Touch::TButton(1, I18n::get("selectWorld.gameMode.survival"));
bCheats = new Touch::TButton(4, "Cheats: Off");
bCreate = new Touch::TButton(3, "Create");
bCreate = new Touch::TButton(3, I18n::get("selectWorld.create"));
} else {
bGamemode = new Button(1, "Survival mode");
bGamemode = new Button(1, I18n::get("selectWorld.gameMode.survival"));
bCheats = new Button(4, "Cheats: Off");
bCreate = new Button(3, "Create");
bCreate = new Button(3, I18n::get("Create"));
}
buttons.push_back(bHeader);

View file

@ -21,6 +21,9 @@ HumanoidModel::HumanoidModel( float g /*= 0*/, float yOffset /*= 0*/, int texW /
texWidth = texW;
texHeight = texH;
// texWidth = 64;
// texHeight = 32;
head.setModel(this);
hair.setModel(this);
body.setModel(this);

View file

@ -370,9 +370,18 @@ LocalPlayer::LocalPlayer(Minecraft* minecraft, Level* level, const std::string&
this->name = minecraft->options.getStringValue(OPTIONS_USERNAME);
printf("test \n");
// A skin picked with /skin wins over the one from the Mojang servers
const std::string chosenSkin = minecraft->options.getStringValue(OPTIONS_SKIN);
const bool hasChosenSkin = !chosenSkin.empty() && chosenSkin != "Default"
&& fileExists("data/images/skins/" + chosenSkin + ".png");
if (hasChosenSkin) {
textureName = "skins/" + chosenSkin + ".png";
skinName = chosenSkin;
}
// Fetch user skin and cape from Mojang servers in the background (avoids blocking the main thread)
// TODO: Fix this memory leak
new CThread(fetchSkinForPlayer, this);
if (!hasChosenSkin) new CThread(fetchSkinForPlayer, this);
new CThread(fetchCapeForPlayer, this);
}
#endif
@ -774,22 +783,19 @@ void LocalPlayer::startCrafting(int x, int y, int z, int tableSize) {
void LocalPlayer::startStonecutting(int x, int y, int z) {
#ifndef STANDALONE_SERVER
if (!minecraft->isCreativeMode())
minecraft->setScreen( new StonecutterScreen() );
minecraft->setScreen( new StonecutterScreen() );
#endif
}
void LocalPlayer::openFurnace( FurnaceTileEntity* e ) {
#ifndef STANDALONE_SERVER
if (!minecraft->isCreativeMode())
minecraft->setScreen( new FurnaceScreen(this, e) );
minecraft->setScreen( new FurnaceScreen(this, e) );
#endif
}
void LocalPlayer::openContainer( ChestTileEntity* container ) {
#ifndef STANDALONE_SERVER
if (!minecraft->isCreativeMode())
minecraft->setScreen( new ChestScreen(this, container) );
minecraft->setScreen( new ChestScreen(this, container) );
#endif
}

View file

@ -99,6 +99,14 @@ void Chunk::rebuild()
LevelChunk::touchedSky = false;
// The world is streamed in: wait until this part and its surroundings exist.
// (the chunk cache marks the area dirty again once more chunks arrive)
if (!level->hasChunksAt(x0 - 1, 0, z0 - 1, x1 + 1, 1, z1 + 1)) {
skyLit = false;
compiled = true;
return;
}
int r = 1;
Region region(level, x0 - r, y0 - r, z0 - r, x1 + r, y1 + r, z1 + r);
TileRenderer tileRenderer(&region);

View file

@ -440,7 +440,7 @@ float GameRenderer::getFov(float a, bool applyEffects) {
fov *= this->oFov + (this->fov - this->oFov) * a;
if (player->isUnderLiquid(Material::water)) fov = 60;
if (player->health <= 0) {
if (player->hasDied()) {
float duration = player->deathTime + a;
fov /= ((1 - 500 / (duration + 500)) * 2.0f + 1);
@ -537,7 +537,7 @@ void GameRenderer::bobHurt(float a) {
float hurt = player->hurtTime - a;
if (player->health <= 0) {
if (player->hasDied()) {
float duration = player->deathTime + a;
glRotatef2(40 - (40 * 200) / (duration + 200), 0, 0, 1);
}

View file

@ -291,8 +291,7 @@ void ItemInHandRenderer::render( float a )
Lighting::turnOn(mc);
glPopMatrix2();
if (localPlayer) // shredder added, basically does the hand swaying animation from b1.8
{
if (localPlayer) { // shredder added, basically does the hand swaying animation from b1.8
float xrr = localPlayer->xBobO + (localPlayer->xBob - localPlayer->xBobO) * a;
float yrr = localPlayer->yBobO + (localPlayer->yBob - localPlayer->yBobO) * a;
// 4J - was using player->xRot and yRot directly here rather than interpolating between old & current with a
@ -425,6 +424,8 @@ void ItemInHandRenderer::render( float a )
EntityRenderer* er = EntityRenderDispatcher::getInstance()->getRenderer(mc->player);
HumanoidMobRenderer* playerRenderer = (HumanoidMobRenderer*) er;
EntityRenderDispatcher::getInstance()->setModernSkin((Entity*)(player));
float ss = 1;
glScalef2(ss, ss, ss);
playerRenderer->renderHand();

View file

@ -69,7 +69,8 @@ LevelRenderer::LevelRenderer( Minecraft* mc)
destroyProgress(0)
{
#ifdef OPENGL_ES
int maxChunksWidth = 2 * LevelConstants::LEVEL_WIDTH / CHUNK_SIZE + 1;
// enough render chunks for the largest possible view distance (400 blocks, see allChanged)
int maxChunksWidth = 400 / CHUNK_SIZE + 1;
numListsOrBuffers = maxChunksWidth * maxChunksWidth * (128/CHUNK_SIZE) * 3;
chunkBuffers = new GLuint[numListsOrBuffers];
glGenBuffers2(numListsOrBuffers, chunkBuffers);
@ -185,11 +186,14 @@ void LevelRenderer::allChanged()
lastFogType = mc->options.getIntValue(OPTIONS_FOG_TYPE);
#ifndef __APPLE__
bool tint = mc->options.getBooleanValue(OPTIONS_FOLIAGE_TINT);
bool sideTint = mc->options.getBooleanValue(OPTIONS_TINTED_SIDE);
#else
bool tint = false, sideTint = false;
#endif
FoliageColor::setUseTint(tint);
GrassColor::setUseTint(tint);
bool sideTint = mc->options.getBooleanValue(OPTIONS_TINTED_SIDE);
TileRenderer::setUseTint(sideTint);
@ -206,6 +210,14 @@ void LevelRenderer::allChanged()
/*
* if (Minecraft.FLYBY_MODE) { dist = 512 - CHUNK_SIZE * 2; }
*/
// The world is infinite: keep as many chunks around the player as can be seen
{
int chunkRadius = dist / 16 + 2;
if (chunkRadius < 4) chunkRadius = 4;
if (chunkRadius > 16) chunkRadius = 16;
LevelConstants::VIEW_DISTANCE_CHUNKS = chunkRadius;
}
xChunks = (dist / LevelRenderer::CHUNK_SIZE) + 1;
yChunks = (128 / LevelRenderer::CHUNK_SIZE);
zChunks = (dist / LevelRenderer::CHUNK_SIZE) + 1;

View file

@ -137,6 +137,11 @@ void EntityRenderDispatcher::render( Entity* entity, float x, float y, float z,
}
}
void EntityRenderDispatcher::setModernSkin(Entity* player) {
PlayerRenderer* rend = (PlayerRenderer*)(getRenderer(player));
rend->setModernSkin((Mob*)player);
}
EntityRenderer* EntityRenderDispatcher::getRenderer( Entity* entity )
{
EntityRendererId rendererId = entity->entityRendererId;

View file

@ -45,6 +45,8 @@ public:
Font* getFont();
void onGraphicsReset();
void setModernSkin(Entity* player);
private:
void assign(EntityRendererId id, EntityRenderer* renderer);
public:

View file

@ -257,7 +257,7 @@ void EntityRenderer::renderShadow(Entity* e, float x, float y, float z, float po
//Textures* textures = entityRenderDispatcher->textures;
//textures->bind(textures->loadTexture("%clamp%/environment/shadow.png"));
Textures* textures = entityRenderDispatcher->textures;
textures->loadAndBindTexture("/misc/shadow.png");
textures->loadAndBindTexture("misc/shadow.png");
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
@ -298,6 +298,7 @@ void EntityRenderer::renderShadow(Entity* e, float x, float y, float z, float po
tt.draw();
glColor4f2(1, 1, 1, 1);
// tt.color(1.f, 1.f, 1.f, 1.f);
glDisable2(GL_BLEND);
glDepthMask(true);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
@ -315,7 +316,7 @@ void EntityRenderer::renderTileShadow(Tile* tt, float x, float y, float z, int x
float a = ((pow - (y - (yt + yo)) / 2) * 0.5f) * getLevel()->getBrightness(xt, yt, zt);
if (a < 0) return;
if (a > 1) a = 1;
// t.color(1, 1, 1, (float) a);
// t.color(1.f, 1.f, 1.f, (float) a);
glColor4f2(1, 1, 1, (float) a);
float x0 = xt + tt->xx0 + xo;

View file

@ -189,9 +189,9 @@ void ItemRenderer::renderGuiItem(Font* font, Textures* textures, const ItemInsta
// it we're batching for saving the
// buffer, this will fail miserably
t.endOverrideAndDraw();
glDisable2(GL_TEXTURE_2D);
fillRect(t, x, y, w, h, 0xff0000);
glEnable2(GL_TEXTURE_2D);
// glDisable2(GL_TEXTURE_2D);
// fillRect(t, x, y, w, h, 0xff0000);
// glEnable2(GL_TEXTURE_2D);
renderGuiItemCorrect(font, textures, item, int(x), int(y));
t.beginOverride();
}

View file

@ -70,13 +70,18 @@ void PlayerRenderer::renderName( Mob* mob, float x, float y, float z ){
}
}
void PlayerRenderer::render(Entity* mob_, float x, float y, float z, float rot, float a) {
Mob* mob = (Mob*) mob_;
// @note fix player skin system
void PlayerRenderer::setModernSkin(Mob* mob) {
HumanoidModel* desired = isModernPlayerSkin(mob) ? playerModel64 : playerModel32;
if (model != desired || humanoidModel != desired) {
model = desired;
humanoidModel = desired;
}
}
void PlayerRenderer::render(Entity* mob_, float x, float y, float z, float rot, float a) {
Mob* mob = (Mob*) mob_;
setModernSkin(mob);
/* LOGI("[PlayerRenderer] %s: skin=%s, modelTex=%dx%d, desired=%s\n",
((Player*)mob)->name.c_str(), mob->getTexture().c_str(),
humanoidModel->texWidth, humanoidModel->texHeight,

View file

@ -19,6 +19,8 @@ public:
virtual void renderName(Mob* mob, float x, float y, float z);
virtual void onGraphicsReset();
void setModernSkin(Mob* mob);
private:
HumanoidModel* playerModel32;
HumanoidModel* playerModel64;

View file

@ -0,0 +1,228 @@
#include "MusicPlayer.h"
#if defined(PLATFORM_DESKTOP) && !defined(NO_SOUND)
#include <AL/al.h>
#include <AL/alc.h>
#define STB_VORBIS_HEADER_ONLY
#include "stb_vorbis.c"
#include <cstdlib>
#include <ctime>
#include <chrono>
#include "../../platform/log.h"
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <dirent.h>
#endif
namespace {
const char* MUSIC_DIR = "data/music";
const int BUFFER_COUNT = 4;
const int FRAMES_PER_BUFFER = 32768;
double now() {
using namespace std::chrono;
return duration_cast<duration<double> >(steady_clock::now().time_since_epoch()).count();
}
bool endsWith(const std::string& s, const char* suffix) {
std::string suf(suffix);
if (s.size() < suf.size()) return false;
for (size_t i = 0; i < suf.size(); ++i)
if (tolower((unsigned char)s[s.size() - suf.size() + i]) != suf[i]) return false;
return true;
}
} // namespace
MusicPlayer::MusicPlayer()
: scanned(false),
alReady(false),
state(Waiting),
nextStart(0),
lastTrack(-1),
source(0),
decoder(NULL),
channels(2),
sampleRate(44100),
decoderDone(false)
{
for (int i = 0; i < BUFFER_COUNT; ++i) buffers[i] = 0;
srand((unsigned int)time(NULL));
}
MusicPlayer::~MusicPlayer()
{
stop();
}
void MusicPlayer::scan()
{
scanned = true;
tracks.clear();
#ifdef _WIN32
WIN32_FIND_DATAA fd;
HANDLE h = FindFirstFileA((std::string(MUSIC_DIR) + "/*").c_str(), &fd);
if (h != INVALID_HANDLE_VALUE) {
do {
std::string name = fd.cFileName;
if (endsWith(name, ".ogg")) tracks.push_back(std::string(MUSIC_DIR) + "/" + name);
} while (FindNextFileA(h, &fd));
FindClose(h);
}
#else
if (DIR* d = opendir(MUSIC_DIR)) {
while (dirent* e = readdir(d)) {
std::string name = e->d_name;
if (endsWith(name, ".ogg")) tracks.push_back(std::string(MUSIC_DIR) + "/" + name);
}
closedir(d);
}
#endif
LOGI("MusicPlayer: %d tracks found in %s\n", (int)tracks.size(), MUSIC_DIR);
nextStart = now() + 8.0; // let the world appear before the first track
}
void MusicPlayer::closeTrack()
{
if (source) {
alSourceStop(source);
ALint queued = 0;
alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
while (queued-- > 0) {
ALuint b;
alSourceUnqueueBuffers(source, 1, &b);
}
}
if (decoder) {
stb_vorbis_close(decoder);
decoder = NULL;
}
state = Waiting;
trackName.clear();
}
void MusicPlayer::stop()
{
if (!alReady) return;
closeTrack();
if (source) alDeleteSources(1, &source);
alDeleteBuffers(BUFFER_COUNT, buffers);
source = 0;
alReady = false;
}
bool MusicPlayer::fillBuffer(unsigned int buffer)
{
if (decoderDone || !decoder) return false;
pcm.resize((size_t)FRAMES_PER_BUFFER * channels);
int frames = stb_vorbis_get_samples_short_interleaved(decoder, channels, &pcm[0], FRAMES_PER_BUFFER * channels);
if (frames <= 0) {
decoderDone = true;
return false;
}
alBufferData(buffer, channels == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16, &pcm[0],
frames * channels * (int)sizeof(short), sampleRate);
return true;
}
bool MusicPlayer::startTrack(const std::string& path)
{
int error = 0;
decoder = stb_vorbis_open_filename(path.c_str(), &error, NULL);
if (!decoder) {
LOGE("MusicPlayer: cannot open %s (%d)\n", path.c_str(), error);
return false;
}
stb_vorbis_info info = stb_vorbis_get_info(decoder);
channels = info.channels > 1 ? 2 : 1;
sampleRate = (int)info.sample_rate;
decoderDone = false;
int queued = 0;
for (int i = 0; i < BUFFER_COUNT; ++i) {
if (!fillBuffer(buffers[i])) break;
alSourceQueueBuffers(source, 1, &buffers[i]);
++queued;
}
if (queued == 0) {
stb_vorbis_close(decoder);
decoder = NULL;
return false;
}
alSourcePlay(source);
state = Playing;
size_t slash = path.find_last_of('/');
trackName = path.substr(slash == std::string::npos ? 0 : slash + 1);
LOGI("MusicPlayer: now playing %s\n", trackName.c_str());
return true;
}
void MusicPlayer::update(float volume)
{
if (!scanned) scan();
if (tracks.empty()) return;
// the OpenAL context is created by the sound system
if (!alReady) {
if (!alcGetCurrentContext()) return;
alGenSources(1, &source);
alGenBuffers(BUFFER_COUNT, buffers);
alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE);
alSource3f(source, AL_POSITION, 0, 0, 0);
alSourcef(source, AL_ROLLOFF_FACTOR, 0);
alReady = true;
}
if (volume <= 0.0f) {
if (state == Playing) closeTrack();
return;
}
if (state == Waiting) {
if (now() < nextStart) return;
int pick = rand() % (int)tracks.size();
if (tracks.size() > 1 && pick == lastTrack) pick = (pick + 1) % (int)tracks.size();
lastTrack = pick;
if (!startTrack(tracks[pick])) nextStart = now() + 20.0;
else alSourcef(source, AL_GAIN, volume * 0.6f);
return;
}
// Playing: keep the queue filled
alSourcef(source, AL_GAIN, volume * 0.6f);
ALint processed = 0;
alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
while (processed-- > 0) {
ALuint b;
alSourceUnqueueBuffers(source, 1, &b);
if (fillBuffer(b)) alSourceQueueBuffers(source, 1, &b);
}
ALint queued = 0, srcState = 0;
alGetSourcei(source, AL_BUFFERS_QUEUED, &queued);
alGetSourcei(source, AL_SOURCE_STATE, &srcState);
if (queued == 0) {
// finished: pause for a while before the next track
closeTrack();
nextStart = now() + 45.0 + (rand() % 120);
} else if (srcState != AL_PLAYING) {
alSourcePlay(source); // underrun
}
}
#endif // PLATFORM_DESKTOP

View file

@ -0,0 +1,48 @@
#pragma once
#include <string>
#include <vector>
struct stb_vorbis;
/**
* Plays the OGG tracks found in "data/music" in random order with pauses in
* between, streamed through OpenAL. Volume comes from the music volume option.
* Needs the OpenAL context created by SoundSystemAL.
*/
class MusicPlayer {
public:
MusicPlayer();
~MusicPlayer();
// Call once per frame. `volume` is 0..1.
void update(float volume);
void stop();
const std::string& currentTrack() const { return trackName; }
private:
void scan();
bool startTrack(const std::string& path);
bool fillBuffer(unsigned int buffer);
void closeTrack();
enum State { Waiting, Playing };
bool scanned;
bool alReady;
State state;
double nextStart;
int lastTrack;
std::vector<std::string> tracks;
std::string trackName;
unsigned int source;
unsigned int buffers[4];
stb_vorbis* decoder;
int channels;
int sampleRate;
std::vector<short> pcm;
bool decoderDone;
};

View file

@ -169,6 +169,9 @@ void SoundEngine::destroy()
void SoundEngine::update( Mob* player, float a )
{
#if defined(PLATFORM_DESKTOP) && !defined(NO_SOUND)
music.update(options ? options->getProgressValue(OPTIONS_MUSIC_VOLUME) : 0.0f);
#endif
if (/*!loaded || */options->getProgressValue(OPTIONS_SOUND_VOLUME) == 0) return;
if (player == NULL) return;

View file

@ -17,6 +17,10 @@ class Minecraft;
class Mob;
class Options;
#if defined(PLATFORM_DESKTOP) && !defined(NO_SOUND)
#include "MusicPlayer.h"
#endif
class SoundEngine
{
static const int SOUND_DISTANCE = 16;
@ -29,6 +33,10 @@ class SoundEngine
SoundSystem soundSystem;
#endif
#if defined(PLATFORM_DESKTOP) && !defined(NO_SOUND)
MusicPlayer music;
#endif
Options* options;
int idCounter;
//static bool loaded;

View file

@ -2,18 +2,12 @@
#include <string>
#include <vector>
enum CommandFlags {
COMMAND_FLAG_SINGLEPLAYER_ONLY = (1 << 1),
COMMAND_FLAG_NO_ARGS = (1 << 2),
};
class Minecraft;
class Player;
class Command {
public:
const std::string& getName() { return m_name; }
const CommandFlags getFlags() { return m_flags; }
bool isPlayerOp(Minecraft& mc, Player& player);
@ -21,8 +15,7 @@ public:
virtual std::string help(Minecraft& mc) = 0;
protected:
Command(const std::string& name, CommandFlags flags = (CommandFlags)0) : m_name(name), m_flags(flags) {}
Command(const std::string& name) : m_name(name) {}
const std::string m_name;
const CommandFlags m_flags;
};

View file

@ -5,7 +5,6 @@
#include "world/level/Level.h"
#include <algorithm>
#include <client/Minecraft.h>
#include <network/packet/LoginStatusPacket.h>
CommandBan::CommandBan() : Command("ban") {}
@ -21,26 +20,30 @@ std::string CommandBan::execute(Minecraft& mc, Player& player, const std::vector
std::string nicknameLower = args[0];
std::transform(nicknameLower.begin(), nicknameLower.end(), nicknameLower.begin(), ::tolower);
auto it = std::find_if(mc.level->players.begin(), mc.level->players.end(), [nicknameLower] (auto& it) -> bool {
auto it = std::find_if(mc.level->players.begin(), mc.level->players.end(), [args, nicknameLower] (auto& it) -> bool {
std::string lower = it->name;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
return lower == nicknameLower;
});
if (*it == (Player*)mc.player) {
return "ban: you can't ban urself lol";
}
if (it != mc.level->players.end()) {
if (*it == (Player*)mc.player) {
return "banip: you can't ban urself lol";
}
mc.level->removePlayer(*it);
(*it)->remove();
mc.raknetInstance->getPeer()->CloseConnection((*it)->owner, true);
} else {
for (auto& banned : mc.level->bannedPpl) {
for (auto& banned : mc.level->bannedPlayers) {
if (nicknameLower == banned) {
return args[0] + " already banned!";
return args[0] + "already banned!";
}
}
}
mc.level->bannedPpl.insert(nicknameLower);
mc.level->bannedPlayers.insert(nicknameLower);
return "ban: successfully banned player " + args[0];
}

View file

@ -1,65 +0,0 @@
#include "CommandBanIp.hpp"
#include "commands/Command.hpp"
#include "network/RakNetInstance.h"
#include "raknet/RakPeerInterface.h"
#include "world/level/Level.h"
#include <algorithm>
#include <client/Minecraft.h>
CommandBanIp::CommandBanIp() : Command("banip") {}
std::string CommandBanIp::execute(Minecraft& mc, Player& player, const std::vector<std::string>& args) {
if (!isPlayerOp(mc, player)) {
return "You aren't enough priveleged to run this command";
}
if (args.empty()) {
return help(mc);
}
std::string nicknameLower = args[0];
std::transform(nicknameLower.begin(), nicknameLower.end(), nicknameLower.begin(), ::tolower);
auto it = std::find_if(mc.level->players.begin(), mc.level->players.end(), [nicknameLower] (auto& it) -> bool {
std::string lower = it->name;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
return lower == nicknameLower;
});
std::string clientIp;
if (it != mc.level->players.end()) {
if (*it == (Player*)mc.player) {
return "banip: you can't ban urself lol";
}
RakNet::SystemAddress sysAddress = mc.raknetInstance->getPeer()->GetSystemAddressFromGuid((*it)->owner);
char ip[32];
sysAddress.ToString(false, ip);
clientIp = ip;
auto sourceId = (*it)->owner;
(*it)->reallyRemoveIfPlayer = true;
mc.level->removeEntity((*it));
mc.raknetInstance->getPeer()->CloseConnection(sourceId, true);
} else {
for (auto& banned : mc.level->bannedIps) {
if (clientIp == banned) {
return args[0] + " already banned!";
}
}
clientIp = args[0];
}
mc.level->bannedIps.insert(clientIp);
return "banip: successfully banned player by ip " + args[0];
}
std::string CommandBanIp::help(Minecraft& mc) {
return "Usage: /banip <player>";
}

View file

@ -0,0 +1,33 @@
#include "CommandGimmieItems.hpp"
#include <client/Minecraft.h>
#include <world/level/Level.h>
#include <world/item/DyePowderItem.h>
CommandGimmieItems::CommandGimmieItems() : Command("gimmieitems") {}
std::string CommandGimmieItems::execute(Minecraft& mc, Player& player, const std::vector<std::string>& args) {
if (mc.level != nullptr) {
if (mc.level->getLevelData()->getAllowCheats()) {
player.inventory->add(new ItemInstance(Item::ironIngot, 64));
player.inventory->add(new ItemInstance(Item::ironIngot, 34));
player.inventory->add(new ItemInstance(Tile::stonecutterBench));
player.inventory->add(new ItemInstance(Tile::workBench));
player.inventory->add(new ItemInstance(Tile::furnace));
player.inventory->add(new ItemInstance(Tile::wood, 54));
player.inventory->add(new ItemInstance(Item::stick, 14));
player.inventory->add(new ItemInstance(Item::coal, 31));
player.inventory->add(new ItemInstance(Tile::sand, 6));
player.inventory->add(new ItemInstance(Item::dye_powder, 23, DyePowderItem::PURPLE));
return "Grant debug items. Have fun!";
} else {
return "Cheats are not allowed!";
}
}
return "World not loaded";
}
std::string CommandGimmieItems::help(Minecraft& mc) {
return "Usage: /gimmieitems";
}

View file

@ -1,8 +1,8 @@
#include "Command.hpp"
class CommandBanIp : public Command {
class CommandGimmieItems : public Command {
public:
CommandBanIp();
CommandGimmieItems();
std::string execute(Minecraft& mc, Player& player, const std::vector<std::string>& args);
std::string help(Minecraft& mc);

View file

@ -35,11 +35,9 @@ std::string CommandKick::execute(Minecraft& mc, Player& player, const std::vecto
return "kick: you can't kick urself lol";
}
auto sourceId = (*it)->owner;
(*it)->reallyRemoveIfPlayer = true;
mc.level->removeEntity((*it));
mc.raknetInstance->getPeer()->CloseConnection(sourceId, true);
mc.level->removePlayer(*it);
(*it)->remove();
mc.raknetInstance->getPeer()->CloseConnection((*it)->owner, true);
return "kick: successfully kicked player " + args[0];
}

View file

@ -8,11 +8,11 @@
#include "commands/CommandKick.hpp"
#include "commands/CommandOp.hpp"
#include "commands/CommandBan.hpp"
#include "commands/CommandBanIp.hpp"
#include "commands/CommandPardon.hpp"
#include "commands/CommandGimmieItems.hpp"
#include "network/packet/ChatPacket.h"
#include "network/RakNetInstance.h"
#include "world/level/Level.h"
#include "lua/LuaEngine.h"
CommandManager::CommandManager() {
registerAllCommands();
@ -23,8 +23,7 @@ void CommandManager::registerAllCommands() {
m_commands.push_back(new CommandKick());
m_commands.push_back(new CommandOp());
m_commands.push_back(new CommandBan());
m_commands.push_back(new CommandBanIp());
m_commands.push_back(new CommandPardon());
// m_commands.push_back(new CommandGimmieItems());
}
std::vector<std::string> CommandManager::getListAllCommands() {
@ -33,6 +32,9 @@ std::vector<std::string> CommandManager::getListAllCommands() {
for (auto& cmd : m_commands) {
ret.push_back(cmd->getName());
}
for (auto& name : LuaEngine::get().commandNames()) {
ret.push_back(name);
}
return ret;
}
@ -47,23 +49,21 @@ std::string CommandManager::execute(Minecraft& mc, Player& player, const std::st
return it->getName() == cmd;
});
if (it == m_commands.end()) {
return "Command /" + cmd + " not found";
}
std::vector<std::string> args;
std::string tok;
while (ss >> tok) args.push_back(tok);
if (!mc.level->isClientSide || (*it)->getFlags() & CommandFlags::COMMAND_FLAG_SINGLEPLAYER_ONLY) {
return (*it)->execute(mc, player, args);
} else {
ChatPacket packet("/" + input);
mc.raknetInstance->send(packet);
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 "";
return (*it)->execute(mc, player, args);
}
Command* CommandManager::getCommand(const std::string& name) {

View file

@ -1,40 +0,0 @@
#include "CommandPardon.hpp"
#include "commands/Command.hpp"
#include "network/RakNetInstance.h"
#include "raknet/RakPeerInterface.h"
#include "world/level/Level.h"
#include <algorithm>
#include <client/Minecraft.h>
CommandPardon::CommandPardon() : Command("pardon") {}
std::string CommandPardon::execute(Minecraft& mc, Player& player, const std::vector<std::string>& args) {
if (!isPlayerOp(mc, player)) {
return "You aren't enough priveleged to run this command";
}
if (args.empty()) {
return help(mc);
}
std::string nicknameLower = args[0];
std::transform(nicknameLower.begin(), nicknameLower.end(), nicknameLower.begin(), ::tolower);
if (mc.level->bannedPpl.find(nicknameLower) != mc.level->bannedPpl.end()) {
mc.level->bannedPpl.erase(nicknameLower);
return "pardon: successfully unbanned player " + args[0];
}
if (mc.level->bannedIps.find(nicknameLower) != mc.level->bannedIps.end()) {
mc.level->bannedIps.erase(nicknameLower);
return "pardon: successfully unbanned ip " + args[0];
}
return "Player/Ip doesnt banned";
}
std::string CommandPardon::help(Minecraft& mc) {
return "Usage: /pardon <player>";
}

View file

@ -1,9 +0,0 @@
#include "Command.hpp"
class CommandPardon : public Command {
public:
CommandPardon();
std::string execute(Minecraft& mc, Player& player, const std::vector<std::string>& args);
std::string help(Minecraft& mc);
};

628
src/lua/LuaEngine.cpp Normal file
View file

@ -0,0 +1,628 @@
#include "LuaEngine.h"
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#include <cstdio>
#include <cstring>
#include <fstream>
#include <map>
#include <set>
#include <sstream>
#include <algorithm>
#include "client/Minecraft.h"
#include "network/RakNetInstance.h"
#include "network/ServerSideNetworkHandler.h"
#include "network/packet/ChatPacket.h"
#include "network/packet/ChunkDataPacket.h"
#include "network/packet/MovePlayerPacket.h"
#include "network/packet/SendInventoryPacket.h"
#include "network/packet/UpdateBlockPacket.h"
#include "platform/log.h"
#include "raknet/RakPeerInterface.h"
#include "raknet/PacketPriority.h"
#include "world/entity/EntityTypes.h"
#include "world/entity/MobFactory.h"
#include "world/entity/item/ItemEntity.h"
#include "world/entity/player/Inventory.h"
#include "world/entity/player/Player.h"
#include "world/item/Item.h"
#include "world/item/ItemInstance.h"
#include "world/level/Level.h"
#include "world/level/LightLayer.h"
#include "world/level/LevelConstants.h"
#include "world/level/chunk/LevelChunk.h"
#include "world/level/material/Material.h"
#include "world/level/tile/Tile.h"
#include "world/phys/HitResult.h"
#include "util/Mth.h"
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <direct.h>
#define MKDIR(p) _mkdir(p)
#else
#include <dirent.h>
#include <sys/stat.h>
#define MKDIR(p) mkdir(p, 0755)
#endif
namespace {
Minecraft* MC() { return LuaEngine::get().minecraft(); }
Level* LV() { Minecraft* m = MC(); return m ? m->level : NULL; }
Player* findPlayer(int id) {
Level* level = LV();
if (!level) return NULL;
for (unsigned int i = 0; i < level->players.size(); ++i)
if (level->players[i]->entityId == id) return level->players[i];
return NULL;
}
ServerSideNetworkHandler* server() {
Minecraft* m = MC();
if (m && m->raknetInstance && m->raknetInstance->isServer() && m->netCallback)
return (ServerSideNetworkHandler*)m->netCallback;
return NULL;
}
bool isLocalPlayer(Player* p) {
return (Entity*)p == (Entity*)MC()->player;
}
void sendChat(Player* p, const std::string& text) {
if (!p) return;
if (isLocalPlayer(p)) {
#ifndef STANDALONE_SERVER
MC()->gui.addMessage(text);
#else
LOGI("%s\n", text.c_str());
#endif
return;
}
if (ServerSideNetworkHandler* s = server()) {
ChatPacket packet(text);
RakNet::BitStream bs;
packet.write(&bs);
MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, p->owner, false);
}
}
void broadcastChat(const std::string& text) {
#ifndef STANDALONE_SERVER
if (MC()->player) MC()->gui.addMessage(text);
#else
LOGI("%s\n", text.c_str());
#endif
if (server()) {
ChatPacket packet(text);
RakNet::BitStream bs;
packet.write(&bs);
MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
}
}
// ---- bulk edits: blocks are written silently and the touched chunks are re-sent once at the end
struct DirtyBox { int x0, y0, z0, x1, y1, z1; };
std::map<long long, DirtyBox> g_dirty;
void markDirty(int x, int y, int z) {
const long long key = LevelConstants::chunkKey(x >> 4, z >> 4);
std::map<long long, DirtyBox>::iterator it = g_dirty.find(key);
if (it == g_dirty.end()) {
DirtyBox b = { x, y, z, x, y, z };
g_dirty[key] = b;
} else {
DirtyBox& b = it->second;
if (x < b.x0) b.x0 = x; if (x > b.x1) b.x1 = x;
if (y < b.y0) b.y0 = y; if (y > b.y1) b.y1 = y;
if (z < b.z0) b.z0 = z; if (z > b.z1) b.z1 = z;
}
}
// ---- lua helpers
int argInt(lua_State* L, int i) { return (int)lua_tointeger(L, i); }
float argNum(lua_State* L, int i) { return (float)lua_tonumber(L, i); }
// ================================================================== world
int l_get_block(lua_State* L) {
Level* level = LV();
int x = argInt(L, 1), y = argInt(L, 2), z = argInt(L, 3);
lua_pushinteger(L, level->getTile(x, y, z));
lua_pushinteger(L, level->getData(x, y, z));
return 2;
}
int l_set_block(lua_State* L) {
Level* level = LV();
int x = argInt(L, 1), y = argInt(L, 2), z = argInt(L, 3);
int id = argInt(L, 4), data = argInt(L, 5);
bool silent = lua_toboolean(L, 6) != 0;
if (y < 0 || y >= LevelConstants::LEVEL_HEIGHT || id < 0 || id > 255 || (id > 0 && !Tile::tiles[id])) {
lua_pushboolean(L, 0);
return 1;
}
bool changed;
if (silent) {
changed = level->setTileAndDataNoUpdate(x, y, z, id, data & 15);
if (changed) markDirty(x, y, z);
} else {
changed = level->setTileAndData(x, y, z, id, data & 15);
}
lua_pushboolean(L, changed);
return 1;
}
int l_flush(lua_State* L) {
Level* level = LV();
ServerSideNetworkHandler* srv = server();
int count = 0;
for (std::map<long long, DirtyBox>::iterator it = g_dirty.begin(); it != g_dirty.end(); ++it) {
DirtyBox& b = it->second;
const int cx = b.x0 >> 4, cz = b.z0 >> 4;
// lighting of the touched volume
const int y0 = (b.y0 - 1 < 0) ? 0 : b.y0 - 1;
const int y1 = (b.y1 + 1 > LevelConstants::LEVEL_HEIGHT - 1) ? LevelConstants::LEVEL_HEIGHT - 1 : b.y1 + 1;
level->updateLight(LightLayer::Sky, b.x0 - 1, y0, b.z0 - 1, b.x1 + 1, y1, b.z1 + 1);
level->updateLight(LightLayer::Block, b.x0 - 1, y0, b.z0 - 1, b.x1 + 1, y1, b.z1 + 1);
level->setTilesDirty(b.x0 - 1, y0, b.z0 - 1, b.x1 + 1, y1, b.z1 + 1);
if (srv) {
LevelChunk* chunk = level->getChunk(cx, cz);
ChunkDataPacket packet(cx, cz, chunk);
RakNet::BitStream bs;
packet.write(&bs);
MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
}
++count;
}
g_dirty.clear();
lua_pushinteger(L, count);
return 1;
}
int l_solid_height(lua_State* L) {
Level* level = LV();
int x = argInt(L, 1), z = argInt(L, 2);
for (int y = LevelConstants::LEVEL_HEIGHT - 1; y >= 0; --y) {
int id = level->getTile(x, y, z);
if (id > 0 && Tile::tiles[id] && Tile::tiles[id]->material->blocksMotion()) {
lua_pushinteger(L, y);
return 1;
}
}
lua_pushinteger(L, -1);
return 1;
}
int l_loaded(lua_State* L) {
lua_pushboolean(L, LV()->hasChunkAt(argInt(L, 1), 64, argInt(L, 2)));
return 1;
}
int l_ensure(lua_State* L) {
LV()->ensureChunksAround(argInt(L, 1), argInt(L, 2), argInt(L, 3));
return 0;
}
int l_get_time(lua_State* L) { lua_pushinteger(L, LV()->getTime()); return 1; }
int l_set_time(lua_State* L) { LV()->setTime(argInt(L, 1)); return 0; }
int l_seed(lua_State* L) { lua_pushnumber(L, (double)LV()->getSeed()); return 1; }
int l_explode(lua_State* L) {
LV()->explode(NULL, argNum(L, 1), argNum(L, 2), argNum(L, 3), argNum(L, 4));
return 0;
}
int l_spawn_mob(lua_State* L) {
Level* level = LV();
Mob* mob = MobFactory::CreateMob(argInt(L, 1), level);
if (!mob) { lua_pushnil(L); return 1; }
mob->moveTo(argNum(L, 2), argNum(L, 3), argNum(L, 4), 0, 0);
level->addEntity(mob);
lua_pushinteger(L, mob->entityId);
return 1;
}
int l_drop_item(lua_State* L) {
Level* level = LV();
ItemInstance item(argInt(L, 1), argInt(L, 2), argInt(L, 3));
level->addEntity(new ItemEntity(level, argNum(L, 4), argNum(L, 5), argNum(L, 6), item));
return 0;
}
// butcher(x, y, z, radius, includeFriendly) -> count
int l_butcher(lua_State* L) {
Level* level = LV();
float x = argNum(L, 1), y = argNum(L, 2), z = argNum(L, 3), r = argNum(L, 4);
bool friendly = lua_toboolean(L, 5) != 0;
int n = 0;
for (unsigned int i = 0; i < level->entities.size(); ++i) {
Entity* e = level->entities[i];
if (e->removed || !e->isMob() || e->isPlayer()) continue;
if (!friendly && e->getCreatureBaseType() != MobTypes::BaseEnemy) continue;
float dx = e->x - x, dy = e->y - y, dz = e->z - z;
if (r > 0 && dx * dx + dy * dy + dz * dz > r * r) continue;
e->remove();
++n;
}
lua_pushinteger(L, n);
return 1;
}
// ================================================================== players
int l_players(lua_State* L) {
Level* level = LV();
lua_newtable(L);
int n = 0;
for (unsigned int i = 0; i < level->players.size(); ++i) {
lua_pushinteger(L, level->players[i]->entityId);
lua_rawseti(L, -2, ++n);
}
return 1;
}
int l_pname(lua_State* L) {
Player* p = findPlayer(argInt(L, 1));
if (!p) { lua_pushnil(L); return 1; }
lua_pushstring(L, p->name.c_str());
return 1;
}
int l_ppos(lua_State* L) {
Player* p = findPlayer(argInt(L, 1));
if (!p) return 0;
lua_pushnumber(L, p->x);
lua_pushnumber(L, p->y - p->heightOffset); // feet
lua_pushnumber(L, p->z);
lua_pushnumber(L, p->yRot);
lua_pushnumber(L, p->xRot);
return 5;
}
int l_pteleport(lua_State* L) {
Player* p = findPlayer(argInt(L, 1));
if (!p) return 0;
float x = argNum(L, 2), y = argNum(L, 3), z = argNum(L, 4);
float yaw = lua_isnumber(L, 5) ? argNum(L, 5) : p->yRot;
float pitch = lua_isnumber(L, 6) ? argNum(L, 6) : p->xRot;
LV()->ensureChunksAround((int)floorf(x), (int)floorf(z), 2);
p->moveTo(x, y, z, yaw, pitch);
if (!isLocalPlayer(p) && server()) {
MovePlayerPacket packet(p->entityId, p->x, p->y - p->heightOffset, p->z, p->xRot, p->yRot);
RakNet::BitStream bs;
packet.write(&bs);
MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
}
return 0;
}
int l_pmsg(lua_State* L) {
sendChat(findPlayer(argInt(L, 1)), lua_tostring(L, 2));
return 0;
}
int l_broadcast(lua_State* L) {
broadcastChat(lua_tostring(L, 1));
return 0;
}
int l_pop(lua_State* L) {
Player* p = findPlayer(argInt(L, 1));
if (!p) { lua_pushboolean(L, 0); return 1; }
std::string lower = p->name;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
lua_pushboolean(L, LV()->ops.find(lower) != LV()->ops.end());
return 1;
}
int l_pheld(lua_State* L) {
Player* p = findPlayer(argInt(L, 1));
ItemInstance* item = p ? p->inventory->getSelected() : NULL;
if (!item || item->isNull()) { lua_pushinteger(L, 0); lua_pushinteger(L, 0); lua_pushinteger(L, 0); return 3; }
lua_pushinteger(L, item->id);
lua_pushinteger(L, item->getAuxValue());
lua_pushinteger(L, item->count);
return 3;
}
int l_pgive(lua_State* L) {
Player* p = findPlayer(argInt(L, 1));
if (!p) return 0;
p->inventory->add(new ItemInstance(argInt(L, 2), argInt(L, 3), argInt(L, 4)));
if (!isLocalPlayer(p) && server()) {
SendInventoryPacket packet(p, false);
RakNet::BitStream bs;
packet.write(&bs);
MC()->raknetInstance->getPeer()->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, p->owner, false);
}
return 0;
}
int l_pgamemode(lua_State* L) {
lua_pushinteger(L, LV()->getLevelData()->getGameType());
return 1;
}
// trace(id, maxDist) -> x, y, z, face (the block the player looks at)
int l_ptrace(lua_State* L) {
Player* p = findPlayer(argInt(L, 1));
float dist = lua_isnumber(L, 2) ? argNum(L, 2) : 128.0f;
if (!p) return 0;
float yaw = p->yRot * Mth::DEGRAD, pitch = p->xRot * Mth::DEGRAD;
Vec3 dir(-sinf(yaw) * cosf(pitch), -sinf(pitch), cosf(yaw) * cosf(pitch));
Vec3 a(p->x, p->y, p->z);
Vec3 b(a.x + dir.x * dist, a.y + dir.y * dist, a.z + dir.z * dist);
HitResult hit = LV()->clip(a, b, false, false);
if (!hit.isHit() || hit.type != TILE) return 0;
lua_pushinteger(L, hit.x);
lua_pushinteger(L, hit.y);
lua_pushinteger(L, hit.z);
lua_pushinteger(L, hit.f);
return 4;
}
int l_log(lua_State* L) {
LOGI("[lua] %s\n", lua_tostring(L, 1));
return 0;
}
int l_mkdir(lua_State* L) {
MKDIR(lua_tostring(L, 1));
return 0;
}
// listdir(path) -> { {name=, dir=bool}, ... }
int l_listdir(lua_State* L) {
std::string path = lua_tostring(L, 1);
lua_newtable(L);
int n = 0;
#ifdef _WIN32
WIN32_FIND_DATAA fd;
HANDLE h = FindFirstFileA((path + "/*").c_str(), &fd);
if (h != INVALID_HANDLE_VALUE) {
do {
if (!strcmp(fd.cFileName, ".") || !strcmp(fd.cFileName, "..")) continue;
lua_newtable(L);
lua_pushstring(L, fd.cFileName);
lua_setfield(L, -2, "name");
lua_pushboolean(L, (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
lua_setfield(L, -2, "dir");
lua_rawseti(L, -2, ++n);
} while (FindNextFileA(h, &fd));
FindClose(h);
}
#else
if (DIR* d = opendir(path.c_str())) {
while (dirent* e = readdir(d)) {
if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
struct stat st;
bool isDir = stat((path + "/" + e->d_name).c_str(), &st) == 0 && S_ISDIR(st.st_mode);
lua_newtable(L);
lua_pushstring(L, e->d_name);
lua_setfield(L, -2, "name");
lua_pushboolean(L, isDir);
lua_setfield(L, -2, "dir");
lua_rawseti(L, -2, ++n);
}
closedir(d);
}
#endif
return 1;
}
const luaL_Reg api[] = {
{ "_get_block", l_get_block }, { "_set_block", l_set_block }, { "_flush", l_flush },
{ "_solid_height", l_solid_height }, { "_loaded", l_loaded }, { "_ensure", l_ensure },
{ "_get_time", l_get_time }, { "_set_time", l_set_time }, { "_seed", l_seed },
{ "_explode", l_explode }, { "_spawn_mob", l_spawn_mob }, { "_drop_item", l_drop_item },
{ "_butcher", l_butcher },
{ "_players", l_players }, { "_pname", l_pname }, { "_ppos", l_ppos }, { "_pteleport", l_pteleport },
{ "_pmsg", l_pmsg }, { "_broadcast", l_broadcast }, { "_pop", l_pop }, { "_pheld", l_pheld },
{ "_pgive", l_pgive }, { "_pgamemode", l_pgamemode }, { "_ptrace", l_ptrace },
{ "_log", l_log }, { "_mkdir", l_mkdir }, { "_listdir", l_listdir },
{ NULL, NULL }
};
int traceback(lua_State* L) {
const char* msg = lua_tostring(L, 1);
luaL_traceback(L, L, msg ? msg : "(error)", 1);
return 1;
}
// calls the function sitting below `nargs` arguments; returns false on error
bool protectedCall(lua_State* L, int nargs, int nresults) {
int base = lua_gettop(L) - nargs;
lua_pushcfunction(L, traceback);
lua_insert(L, base);
int rc = lua_pcall(L, nargs, nresults, base);
lua_remove(L, base);
if (rc != 0) {
LOGE("[lua] %s\n", lua_tostring(L, -1));
lua_pop(L, 1);
return false;
}
return true;
}
bool fileExists(const std::string& p) {
std::ifstream f(p.c_str());
return f.good();
}
} // namespace
// =================================================================== engine
LuaEngine& LuaEngine::get() {
static LuaEngine engine;
return engine;
}
void LuaEngine::start(Minecraft* minecraft) {
if (L) stop();
mc = minecraft;
g_dirty.clear();
L = luaL_newstate();
luaL_openlibs(L);
lua_newtable(L);
luaL_register(L, NULL, api);
lua_setglobal(L, "mc");
// prelude: the friendly API on top of the primitives above
const char* candidates[] = { "lua/prelude.lua", "data/lua/prelude.lua", "../lua/prelude.lua" };
std::string prelude;
for (unsigned int i = 0; i < sizeof(candidates) / sizeof(candidates[0]); ++i)
if (fileExists(candidates[i])) { prelude = candidates[i]; break; }
if (prelude.empty()) {
LOGE("[lua] lua/prelude.lua not found, Lua mods are disabled\n");
lua_close(L);
L = 0;
return;
}
if (luaL_loadfile(L, prelude.c_str()) != 0 || !protectedCall(L, 0, 0)) {
if (lua_gettop(L) > 0) { LOGE("[lua] %s\n", lua_tostring(L, -1)); }
lua_close(L);
L = 0;
return;
}
MKDIR("mods");
loadMods();
LOGI("[lua] LuaJIT mod host started\n");
}
void LuaEngine::stop() {
if (!L) return;
lua_getglobal(L, "mc");
lua_getfield(L, -1, "_fire");
lua_remove(L, -2);
lua_pushstring(L, "stop");
lua_pushnil(L);
protectedCall(L, 2, 1);
lua_pop(L, 1);
lua_close(L);
L = 0;
mc = 0;
}
void LuaEngine::loadMods() {
lua_getglobal(L, "mc");
lua_getfield(L, -1, "_load_mods");
lua_remove(L, -2);
protectedCall(L, 0, 0);
}
void LuaEngine::tick() {
if (!L) return;
lua_getglobal(L, "mc");
lua_getfield(L, -1, "_tick");
lua_remove(L, -2);
protectedCall(L, 0, 0);
}
// Calls mc._fire(event, ...) with `nargs` arguments already pushed after the event name.
bool LuaEngine::fire(const char* event, int nargs, bool cancellable) {
// stack now: args...; put the function and the event below them
lua_getglobal(L, "mc");
lua_getfield(L, -1, "_fire");
lua_remove(L, -2);
lua_insert(L, -(nargs + 1));
lua_pushstring(L, event);
lua_insert(L, -(nargs + 1));
bool cancelled = false;
if (protectedCall(L, nargs + 1, 1)) {
if (cancellable && lua_isboolean(L, -1) && !lua_toboolean(L, -1)) cancelled = true;
lua_pop(L, 1);
}
return cancelled;
}
void LuaEngine::onPlayerJoin(Player* player) {
if (!L) return;
lua_pushinteger(L, player->entityId);
fire("join", 1, false);
}
void LuaEngine::onPlayerLeave(Player* player) {
if (!L) return;
lua_pushinteger(L, player->entityId);
fire("leave", 1, false);
}
bool LuaEngine::onChat(Player* player, const std::string& message) {
if (!L) return false;
lua_pushinteger(L, player->entityId);
lua_pushstring(L, message.c_str());
return fire("chat", 2, true);
}
bool LuaEngine::onBlockBreak(Player* player, int x, int y, int z) {
if (!L) return false;
lua_pushinteger(L, player->entityId);
lua_pushinteger(L, x); lua_pushinteger(L, y); lua_pushinteger(L, z);
lua_pushinteger(L, MC()->level->getTile(x, y, z));
return fire("block_break", 5, true);
}
bool LuaEngine::onUseItem(Player* player, int x, int y, int z, int face, ItemInstance* item) {
if (!L) return false;
lua_pushinteger(L, player->entityId);
lua_pushinteger(L, x); lua_pushinteger(L, y); lua_pushinteger(L, z);
lua_pushinteger(L, face);
lua_pushinteger(L, item && !item->isNull() ? item->id : 0);
lua_pushinteger(L, item && !item->isNull() ? item->getAuxValue() : 0);
return fire("use_item", 7, true);
}
bool LuaEngine::runCommand(Player* player, const std::string& name, const std::vector<std::string>& args, std::string& reply) {
if (!L) return false;
lua_getglobal(L, "mc");
lua_getfield(L, -1, "_run_command");
lua_remove(L, -2);
lua_pushinteger(L, player->entityId);
lua_pushstring(L, name.c_str());
lua_newtable(L);
for (unsigned int i = 0; i < args.size(); ++i) {
lua_pushstring(L, args[i].c_str());
lua_rawseti(L, -2, i + 1);
}
bool handled = false;
if (protectedCall(L, 3, 2)) {
handled = lua_toboolean(L, -2) != 0;
if (lua_isstring(L, -1)) reply = lua_tostring(L, -1);
lua_pop(L, 2);
}
return handled;
}
std::vector<std::string> LuaEngine::commandNames() {
std::vector<std::string> names;
if (!L) return names;
lua_getglobal(L, "mc");
lua_getfield(L, -1, "_command_names");
lua_remove(L, -2);
if (protectedCall(L, 0, 1)) {
int n = (int)lua_objlen(L, -1);
for (int i = 1; i <= n; ++i) {
lua_rawgeti(L, -1, i);
if (lua_isstring(L, -1)) names.push_back(lua_tostring(L, -1));
lua_pop(L, 1);
}
lua_pop(L, 1);
}
return names;
}

50
src/lua/LuaEngine.h Normal file
View file

@ -0,0 +1,50 @@
#pragma once
#include <string>
#include <vector>
class Minecraft;
class Player;
class ItemInstance;
struct lua_State;
/**
* LuaJIT mod host. Mods live in "mods/<name>/main.lua" (or "mods/<name>.lua")
* next to the executable and run on the machine that hosts the world (dedicated
* server, single player, or a listening client). See mods/README.md for the API.
*/
class LuaEngine {
public:
static LuaEngine& get();
// Called once the level of a hosting game is ready
void start(Minecraft* mc);
void stop();
bool active() const { return L != 0; }
void tick();
// Events. The "cancellable" ones return true when a mod cancelled the action.
void onPlayerJoin(Player* player);
void onPlayerLeave(Player* player);
bool onChat(Player* player, const std::string& message);
bool onBlockBreak(Player* player, int x, int y, int z);
bool onUseItem(Player* player, int x, int y, int z, int face, ItemInstance* item);
bool onAttackBlock(Player* player, int x, int y, int z) { return onBlockBreak(player, x, y, z); }
// Chat commands registered by mods. Returns false when nobody knows `name`.
bool runCommand(Player* player, const std::string& name, const std::vector<std::string>& args, std::string& reply);
std::vector<std::string> commandNames();
// Used by the bindings
Minecraft* minecraft() const { return mc; }
lua_State* state() const { return L; }
private:
LuaEngine() : L(0), mc(0) {}
void loadMods();
bool fire(const char* event, int nargs, bool cancellable);
lua_State* L;
Minecraft* mc;
};

View file

@ -220,16 +220,23 @@ static int androidKeyToInternal(int androidKey) {
JNIEXPORT void JNICALL
Java_com_mojang_minecraftpe_MainActivity_nativeOnKeyDown(JNIEnv* env, jclass cls, jint keyCode) {
LOGI("@nativeOnKeyDown: %d\n", keyCode);
int mapped = androidKeyToInternal(keyCode);
Keyboard::feed(mapped, true);
// @rewrite
if (keyCode != AKEYCODE_1) {
int mapped = androidKeyToInternal(keyCode);
Keyboard::feed(mapped, true);
}
}
JNIEXPORT void JNICALL
Java_com_mojang_minecraftpe_MainActivity_nativeTextChar(JNIEnv* env, jclass cls, jint unicodeChar) {
LOGI("@nativeTextChar: %d '%c'", unicodeChar, (char)unicodeChar);
// soft-keyboards may send a backspace as a character code
if (unicodeChar == 8) {
// Kolyah35: i dont believe :v
/*if (unicodeChar == 8) {
Keyboard::feed(Keyboard::KEY_BACKSPACE, true);
Keyboard::feed(Keyboard::KEY_BACKSPACE, false);
} else if (unicodeChar > 0 && unicodeChar < 128) {
} else*/ if (unicodeChar > 0 && unicodeChar < 128) {
Keyboard::feedText((char)unicodeChar);
}
}

View file

@ -15,16 +15,15 @@
#include "platform/time.h"
#include "SharedConstants.h"
#include "world/level/LevelConstants.h"
#include <plugins/PluginsManager.hpp>
#define MAIN_CLASS NinecraftApp
static App* g_app = 0;
static int g_exitCode = 0;
void signal_callback_handler(int signum) {
std::cout << "Signum caught: " << signum << std::endl;
if(signum == 2 || signum == 3){ // SIGINT || SIGQUIT
if (signum == 2 || signum == 3) { // SIGINT || SIGQUIT
if (g_app != 0) {
if(g_app != 0) {
g_app->quit();
} else {
exit(g_exitCode);
@ -65,6 +64,7 @@ std::string findStringInConfig(std::string line, std::string config) {
return valueStr;
}
int main(int numArguments, char* pszArgs[]) {
std::ifstream serverProperties("server.properties");
@ -91,15 +91,21 @@ int main(int numArguments, char* pszArgs[]) {
}
port = std::stoi(findStringInConfig("port", propString));
worldSize = std::stoi(findStringInConfig("world-size", propString));
if (worldSize < 16 || worldSize > 32) {
throw std::runtime_error("Incorrect world size.");
// The world is infinite. "view-distance" (in chunks) is how far around every
// player the server keeps chunks loaded. The old "world-size" is ignored.
try {
worldSize = std::stoi(findStringInConfig("view-distance", propString));
if (worldSize < 3 || worldSize > 32) {
throw std::runtime_error("view-distance must be between 3 and 32.");
}
} catch (const std::out_of_range&) {
throw std::runtime_error("Incorrect view-distance.");
} catch (const std::runtime_error& e) {
if (std::string(e.what()) == "Cannot find value") worldSize = 10;
else throw;
}
LevelConstants::CHUNK_CACHE_WIDTH = worldSize;
LevelConstants::LEVEL_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH;
LevelConstants::LEVEL_DEPTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_DEPTH;
LevelConstants::VIEW_DISTANCE_CHUNKS = worldSize;
cachePath = findStringInConfig("level-cachepath", propString);
externalPath = findStringInConfig("level-externalpath", propString);
@ -116,7 +122,7 @@ int main(int numArguments, char* pszArgs[]) {
gamemode = GameType::Survival;
}
printf("%d %s %s %d %d\n", port, cachePath.c_str(), externalPath.c_str(), gamemode, LevelConstants::CHUNK_CACHE_WIDTH);
printf("%d %s %s %d %d\n", port, cachePath.c_str(), externalPath.c_str(), gamemode, LevelConstants::VIEW_DISTANCE_CHUNKS);
} else {
std::ofstream defaultProperties("server.properties");
@ -132,7 +138,7 @@ int main(int numArguments, char* pszArgs[]) {
buffer << "level-externalpath=" << defaultSettings.getExternalPath() << std::endl;
buffer << "gamemode=survival" << std::endl;
buffer << "level-name=" << defaultSettings.getLevelName() << std::endl;
buffer << "world-size=16" << std::endl;
buffer << "view-distance=10" << std::endl;
defaultProperties << buffer.str();
@ -162,7 +168,6 @@ int main(int numArguments, char* pszArgs[]) {
float startTime = getTimeS();
((MAIN_CLASS*)g_app)->selectLevel(levelDir, levelName, settings);
((MAIN_CLASS*)g_app)->hostMultiplayer(port);
PluginsManager::get().loadPlugins();
// Reading ops
std::ifstream ops("ops.txt");
@ -191,31 +196,13 @@ int main(int numArguments, char* pszArgs[]) {
while (std::getline(banned, line)) {
if (!line.empty()) {
((MAIN_CLASS*)g_app)->level->bannedPpl.insert(line);
((MAIN_CLASS*)g_app)->level->bannedPlayers.insert(line);
}
}
} else {
std::ofstream bannedPpl("banned-players.txt");
std::ofstream bannedPlayers("banned-players.txt");
if (!bannedPpl.is_open()) {
throw std::runtime_error("Cannot create banned players list.");
}
}
std::ifstream bannedIps("banned-ips.txt");
if (bannedIps.is_open()) {
std::string line;
while (std::getline(bannedIps, line)) {
if (!line.empty()) {
((MAIN_CLASS*)g_app)->level->bannedIps.insert(line);
}
}
} else {
std::ofstream bannedIp("banned-ips.txt");
if (!bannedIp.is_open()) {
if (!bannedPlayers.is_open()) {
throw std::runtime_error("Cannot create banned players list.");
}
}
@ -223,7 +210,6 @@ int main(int numArguments, char* pszArgs[]) {
std::cout << "Level has been generated in " << getTimeS() - startTime << std::endl;
((MAIN_CLASS*)g_app)->level->saveLevelData();
std::cout << "Level has been saved!" << std::endl;
PluginsManager::get().emit("ServerLoaded");
while(!app->wantToQuit()) {
app->update();
@ -245,7 +231,7 @@ int main(int numArguments, char* pszArgs[]) {
std::ofstream bannedWrite("banned-players.txt");
if (bannedWrite.is_open()) {
for (auto& banned : ((MAIN_CLASS*)g_app)->level->bannedPpl) {
for (auto& banned : ((MAIN_CLASS*)g_app)->level->bannedPlayers) {
bannedWrite << banned << std::endl;
}
bannedWrite.close();
@ -253,19 +239,6 @@ int main(int numArguments, char* pszArgs[]) {
throw std::runtime_error("Cannot open banned players list.");
}
std::ofstream bannedIpsWrite("banned-ips.txt");
if (bannedIpsWrite.is_open()) {
for (auto& banned : ((MAIN_CLASS*)g_app)->level->bannedIps) {
bannedIpsWrite << banned << std::endl;
}
bannedIpsWrite.close();
} else {
throw std::runtime_error("Cannot open banned players list.");
}
PluginsManager::get().emit("ServerShutdown");
((MAIN_CLASS*)g_app)->level->saveLevelData();
delete app;

View file

@ -43,12 +43,10 @@ ClientSideNetworkHandler::ClientSideNetworkHandler(Minecraft* minecraft, IRakNet
: minecraft(minecraft),
raknetInstance(raknetInstance),
level(NULL),
requestNextChunkPosition(0),
requestNextChunkIndex(0)
initialLoadDone(false),
initialPending(0),
spiralRadius(-1)
{
NumRequestChunks = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH;
requestNextChunkIndexList.resize(NumRequestChunks);
chunksLoaded.resize(NumRequestChunks);
rakPeer = raknetInstance->getPeer();
}
@ -56,35 +54,93 @@ ClientSideNetworkHandler::~ClientSideNetworkHandler()
{
}
void ClientSideNetworkHandler::requestNextChunk()
void ClientSideNetworkHandler::requestChunk(int x, int z)
{
if (requestNextChunkIndex < NumRequestChunks)
{
IntPair& chunk = requestNextChunkIndexList[requestNextChunkIndex];
RequestChunkPacket packet(chunk.x, chunk.y);
raknetInstance->send(packet);
const long long key = LevelConstants::chunkKey(x, z);
if (requestedChunks.count(key) || loadedChunks.count(key)) return;
//LOGI("requesting chunks @ (%d, %d)\n", chunk.x, chunk.y);
//raknetInstance->send(new RequestChunkPacket(requestNextChunkPosition % LevelConstants::CHUNK_CACHE_WIDTH, requestNextChunkPosition / LevelConstants::CHUNK_CACHE_WIDTH));
requestNextChunkIndex++;
requestNextChunkPosition++;
}
}
bool ClientSideNetworkHandler::areAllChunksLoaded()
{
return (requestNextChunkPosition >= (LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH));
RequestChunkPacket packet(x, z);
raknetInstance->send(packet);
requestedChunks.insert(key);
}
bool ClientSideNetworkHandler::isChunkLoaded(int x, int z)
{
if (x < 0 || x >= LevelConstants::CHUNK_CACHE_WIDTH || z < 0 || z >= LevelConstants::CHUNK_CACHE_WIDTH) {
LOGE("Error: Tried to request chunk (%d, %d)\n", x, z);
return true;
return loadedChunks.count(LevelConstants::chunkKey(x, z)) != 0;
}
// Keeps the chunks around the local player in sync with the server: asks for
// the ones that came into range (nearest first) and drops the ones left behind.
void ClientSideNetworkHandler::updateChunks()
{
if (!level || !minecraft->player || !initialLoadDone) return;
Player* p = minecraft->player;
const int pcx = Mth::floor(p->x / 16.0f);
const int pcz = Mth::floor(p->z / 16.0f);
const int radius = LevelConstants::VIEW_DISTANCE_CHUNKS + 1;
if (radius != spiralRadius) {
spiralRadius = radius;
spiral.clear();
for (int dx = -radius; dx <= radius; ++dx)
for (int dz = -radius; dz <= radius; ++dz)
if (dx * dx + dz * dz <= radius * radius + radius)
spiral.push_back(std::make_pair(dx, dz));
struct ByDistance {
bool operator()(const std::pair<int, int>& a, const std::pair<int, int>& b) const {
return a.first * a.first + a.second * a.second < b.first * b.first + b.second * b.second;
}
};
std::stable_sort(spiral.begin(), spiral.end(), ByDistance());
}
return chunksLoaded[x * LevelConstants::CHUNK_CACHE_WIDTH + z];
//return areAllChunksLoaded();
// Request what is missing, a few at a time
int budget = 4;
if (requestedChunks.size() < 16) {
for (unsigned int i = 0; i < spiral.size() && budget > 0; ++i) {
const int cx = pcx + spiral[i].first;
const int cz = pcz + spiral[i].second;
const long long key = LevelConstants::chunkKey(cx, cz);
if (requestedChunks.count(key) || loadedChunks.count(key)) continue;
requestChunk(cx, cz);
--budget;
}
}
// Forget chunks that are far away now
const int unloadRadius = radius + 2;
std::vector<long long> victims;
for (std::set<long long>::iterator it = loadedChunks.begin(); it != loadedChunks.end() && victims.size() < 8; ++it) {
const int cx = (int)(*it >> 32);
const int cz = (int)(*it & 0xffffffffLL);
if (std::abs(cx - pcx) > unloadRadius || std::abs(cz - pcz) > unloadRadius)
victims.push_back(*it);
}
for (std::set<long long>::iterator it = requestedChunks.begin(); it != requestedChunks.end() && victims.size() < 8; ++it) {
const int cx = (int)(*it >> 32);
const int cz = (int)(*it & 0xffffffffLL);
if (std::abs(cx - pcx) > unloadRadius || std::abs(cz - pcz) > unloadRadius)
victims.push_back(*it);
}
for (unsigned int i = 0; i < victims.size(); ++i) {
const int cx = (int)(victims[i] >> 32);
const int cz = (int)(victims[i] & 0xffffffffLL);
loadedChunks.erase(victims[i]);
requestedChunks.erase(victims[i]);
level->getChunkSource()->unloadChunk(cx, cz);
}
}
// The chunks right around the player arrived: the server may now send everything else.
void ClientSideNetworkHandler::finishInitialLoad()
{
if (initialLoadDone) return;
initialLoadDone = true;
ReadyPacket packet(ReadyPacket::READY_REQUESTEDCHUNKS);
raknetInstance->send(packet);
bufferedBlockUpdates.clear();
}
void ClientSideNetworkHandler::onConnect(const RakNet::RakNetGUID& hostGuid)
@ -104,9 +160,7 @@ void ClientSideNetworkHandler::onUnableToConnect()
void ClientSideNetworkHandler::onDisconnect(const RakNet::RakNetGUID& guid)
{
LevelConstants::CHUNK_CACHE_WIDTH = 16;
LevelConstants::LEVEL_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH;
LevelConstants::LEVEL_DEPTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_DEPTH;
clearChunksLoaded();
// TODO: Good disconnecting
LOGI("onDisconnect\n");
@ -174,18 +228,8 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, StartGam
}
#endif
// @todo @note i think its trash
// we can put it directly to selectLevel?
if (packet->chunkCacheWidth != 0) {
printf("lol \n");
LevelConstants::CHUNK_CACHE_WIDTH = packet->chunkCacheWidth;
LevelConstants::LEVEL_WIDTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_WIDTH;
LevelConstants::LEVEL_DEPTH = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_DEPTH;
LevelChunk::ChunkBlockCount = LevelConstants::CHUNK_BLOCK_COUNT;
}
NumRequestChunks = LevelConstants::CHUNK_CACHE_WIDTH * LevelConstants::CHUNK_CACHE_WIDTH;
requestNextChunkIndexList.resize(NumRequestChunks);
chunksLoaded.resize(NumRequestChunks);
// The world is infinite, the chunk cache width sent by the server is a legacy field.
clearChunksLoaded();
const std::string& levelId = LevelStorageSource::TempLevelId;
LevelStorageSource* storageSource = minecraft->getLevelSource();
@ -499,6 +543,7 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, UpdateBl
int x = packet->x, z = packet->z;
// Updates for chunks we do not hold are already part of the chunk data we will get
if (isChunkLoaded(x >> 4, z >> 4))
{
//LOGI("chunk is loaded - UPDATE @ %d, %d, %d -- %d, %d\n", x, packet->y, z, packet->blockId, packet->blockData);
@ -506,15 +551,6 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, UpdateBl
int y = packet->y;
int tileId = Tile::transformToValidBlockId(packet->blockId, x, y, z);
level->setTileAndData(x, y, z, tileId, packet->blockData);
} else {
SBufferedBlockUpdate update;
update.blockId = packet->blockId;
update.blockData = packet->blockData;
update.setData = true;
update.x = packet->x;
update.y = packet->y;
update.z = packet->z;
bufferedBlockUpdates.push_back(update);
}
}
@ -555,6 +591,14 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ChunkDat
}
//LOGI("ChunkDataPacket\n");
const long long chunkKey = LevelConstants::chunkKey(packet->x, packet->z);
const bool requested = requestedChunks.erase(chunkKey) > 0;
if (!requested && loadedChunks.count(chunkKey) == 0) {
// we do not want this chunk (any more)
return;
}
// (a chunk we already hold can be pushed again, e.g. after a bulk edit by a mod)
LevelChunk* chunk = level->getChunkSource()->create(packet->x, packet->z);
if (!chunk || chunk->isEmpty())
{
@ -672,66 +716,11 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ChunkDat
//chunk->terrainPopulated = true;
chunk->unsaved = false;
chunksLoaded[packet->x * LevelConstants::CHUNK_CACHE_WIDTH + packet->z] = true;
loadedChunks.insert(chunkKey);
if (areAllChunksLoaded())
{
ReadyPacket packet(ReadyPacket::READY_REQUESTEDCHUNKS);
raknetInstance->send(packet);
for (unsigned int i = 0; i < bufferedBlockUpdates.size(); i++)
{
const SBufferedBlockUpdate& update = bufferedBlockUpdates[i];
int tileId = Tile::transformToValidBlockId( update.blockId, update.x, update.y, update.z );
if (update.setData)
level->setTileAndData(update.x, update.y, update.z, tileId, update.blockData);
else
level->setTile(update.x, update.y, update.z, tileId);
}
bufferedBlockUpdates.clear();
if (requested && !initialLoadDone && initialPending > 0 && --initialPending == 0) {
finishInitialLoad();
}
else
{
requestNextChunk();
}
}
class _ChunkSorter
{
public:
_ChunkSorter(int x, int z)
: x(x),
y(z)
{
}
bool operator() (const IntPair& a, const IntPair& b) {
const int ax = a.x - x, ay = a.y - y;
const int bx = b.x - x, by = b.y - y;
return (ax*ax + ay*ay) < (bx*bx + by*by);
}
private:
int x;
int y;
};
void ClientSideNetworkHandler::arrangeRequestChunkOrder() {
clearChunksLoaded();
// Default sort is around center of the world
int cx = LevelConstants::CHUNK_CACHE_WIDTH / 2;
int cz = LevelConstants::CHUNK_CACHE_WIDTH / 2;
// If player exists, let's sort around him
Player* p = minecraft? minecraft->player : NULL;
if (p) {
cx = Mth::floor(p->x / (float)LevelConstants::CHUNK_WIDTH);
cz = Mth::floor(p->z / (float)LevelConstants::CHUNK_DEPTH);
}
_ChunkSorter sorter(cx, cz);
std::sort(requestNextChunkIndexList.begin(), requestNextChunkIndexList.end(), sorter);
}
void ClientSideNetworkHandler::levelGenerated(Level* level)
@ -740,8 +729,26 @@ void ClientSideNetworkHandler::levelGenerated(Level* level)
ReadyPacket packet(ReadyPacket::READY_CLIENTGENERATION);
raknetInstance->send(packet);
arrangeRequestChunkOrder();
requestNextChunk();
#ifndef STANDALONE_SERVER
if (minecraft && minecraft->player) {
const std::string skin = minecraft->options.getStringValue(OPTIONS_SKIN);
if (!skin.empty() && skin != "Default") {
SetSkinPacket skinPacket(minecraft->player->entityId, skin);
raknetInstance->send(skinPacket);
}
}
#endif
// First ask for the chunks right around the player
clearChunksLoaded();
Player* p = minecraft ? minecraft->player : NULL;
const int pcx = p ? Mth::floor(p->x / 16.0f) : 0;
const int pcz = p ? Mth::floor(p->z / 16.0f) : 0;
const int r = 2;
for (int dx = -r; dx <= r; ++dx)
for (int dz = -r; dz <= r; ++dz)
requestChunk(pcx + dx, pcz + dz);
initialPending = (int)requestedChunks.size();
}
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, PlayerEquipmentPacket* packet)
@ -1017,12 +1024,28 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, Adventur
packet->fillIn(level->adventureSettings);
}
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet)
{
if (!level) return;
Entity* e = level->getEntity(packet->entityId);
if (!e || !e->isPlayer() || e == minecraft->player) return;
Player* p = (Player*)e;
p->skinName = packet->skin.C_String();
#ifndef STANDALONE_SERVER
// every client ships the same skin files; anything we do not have keeps the default look
const std::string file = "data/images/skins/" + p->skinName + ".png";
if (FILE* fp = fopen(file.c_str(), "rb")) {
fclose(fp);
p->setTextureName("skins/" + p->skinName + ".png");
}
#endif
}
void ClientSideNetworkHandler::clearChunksLoaded()
{
// Init the chunk positions
for (int i = 0; i < NumRequestChunks; ++i) {
requestNextChunkIndexList[i].x = i / LevelConstants::CHUNK_WIDTH;
requestNextChunkIndexList[i].y = i % LevelConstants::CHUNK_WIDTH;
chunksLoaded[i] = false;
}
requestedChunks.clear();
loadedChunks.clear();
initialLoadDone = false;
initialPending = 0;
}

View file

@ -7,6 +7,7 @@
#include "../world/level/LevelConstants.h"
#include <vector>
#include <set>
class Minecraft;
class Level;
@ -81,15 +82,17 @@ public:
virtual void handle(const RakNet::RakNetGUID& source, TakeItemPacket* packet);
virtual void handle(const RakNet::RakNetGUID& source, WantCreatePacket* packet);
virtual void handle(const RakNet::RakNetGUID& source, SendInventoryPacket* packet);
virtual void handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet);
// Streams chunks in/out around the local player. Called once per game tick.
void updateChunks();
private:
void requestNextChunk();
void arrangeRequestChunkOrder();
bool isChunkLoaded(int x, int z);
bool areAllChunksLoaded();
void clearChunksLoaded();
void requestChunk(int x, int z);
void finishInitialLoad();
private:
Minecraft* minecraft;
@ -100,13 +103,14 @@ private:
RakNet::RakNetGUID serverGuid;
BlockUpdateList bufferedBlockUpdates;
int requestNextChunkPosition;
int NumRequestChunks;
int requestNextChunkIndex;
std::vector<IntPair> requestNextChunkIndexList;
std::vector<bool> chunksLoaded;
// The world is infinite: only the chunks around the player are kept.
std::set<long long> requestedChunks; // asked from the server, data not here yet
std::set<long long> loadedChunks; // data received and applied
bool initialLoadDone;
int initialPending;
std::vector<std::pair<int, int> > spiral;
int spiralRadius;
};
#endif

View file

@ -52,6 +52,7 @@ class ContainerSetDataPacket;
class ContainerSetContentPacket;
class WantCreatePacket;
class ChatPacket;
class SetSkinPacket;
class SignUpdatePacket;
class Minecraft;
class Level;
@ -119,6 +120,7 @@ public:
virtual void handle(const RakNet::RakNetGUID& source, ContainerSetSlotPacket* packet) {}
virtual void handle(const RakNet::RakNetGUID& source, ContainerSetContentPacket* packet) {}
virtual void handle(const RakNet::RakNetGUID& source, ChatPacket* packet) {}
virtual void handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet) {}
virtual void handle(const RakNet::RakNetGUID& source, SignUpdatePacket* packet) {}
virtual void handle(const RakNet::RakNetGUID& source, AdventureSettingsPacket* packet) {}
virtual void handle(const RakNet::RakNetGUID& source, AnimatePacket* packet) {}

View file

@ -177,6 +177,9 @@ Packet* MinecraftPackets::createPacket(int id)
case PACKET_ADVENTURESETTINGS:
packet = new AdventureSettingsPacket();
break;
case PACKET_SETSKIN:
packet = new SetSkinPacket();
break;
}
return packet;

View file

@ -88,6 +88,8 @@ enum MinecraftPacketIds
PACKET_SIGNUPDATE,
PACKET_ADVENTURESETTINGS,
PACKET_SETSKIN,
/*
PACKET_PRELOGIN,
PACKET_CHAT,

View file

@ -173,7 +173,6 @@ bool RakNetInstance::isMyLocalGuid(const RakNet::RakNetGUID& guid)
void RakNetInstance::runEvents(NetEventCallback* callback)
{
RakNet::Packet* currentEvent;
bool disconnect = false;
while ((currentEvent = rakPeer->Receive()) != NULL)
{
@ -201,8 +200,7 @@ void RakNetInstance::runEvents(NetEventCallback* callback)
case ID_DISCONNECTION_NOTIFICATION:
case ID_CONNECTION_LOST:
callback->onDisconnect(currentEvent->guid);
disconnect = true;
break;
return;
case ID_UNCONNECTED_PONG:
{
RakNet::TimeMS time;
@ -235,9 +233,8 @@ void RakNetInstance::runEvents(NetEventCallback* callback)
}
}
}
if (!disconnect) {
rakPeer->DeallocatePacket(currentEvent);
}
rakPeer->DeallocatePacket(currentEvent);
//delete activeBitStream;
}

View file

@ -38,9 +38,8 @@
#include "../client/sound/SoundEngine.h"
#endif
#include "../server/ServerPlayer.h"
#include "../lua/LuaEngine.h"
#include "../world/entity/item/FallingTile.h"
#include <plugins/LuaPlayer.hpp>
#include <plugins/MessageEvent.hpp>
#define TIMES(x) for(int itc ## __LINE__ = 0; itc ## __LINE__ < x; ++ itc ## __LINE__)
@ -162,29 +161,17 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, MessageP
auto player = getPlayer(source);
if (player == nullptr) return; // @todo maybe kick?
std::string msg = packet->message.C_String();
auto msg = std::string(packet->message.C_String());
if (msg[0] == '/') {
// This is a command
MessageEvent event;
event.m_decline = false;
PluginsManager::get().emit("Message", LuaPlayer(source), msg, event);
if (!event.m_decline) {
if (packet->message[0] == '/') {
// This is a command
auto cmd = Util::stringTrim(msg.substr(1));
if (PluginsManager::get().emitCommands(cmd, source)) {
ChatPacket resp(minecraft->commandManager().execute(*minecraft, *player, cmd));
return sendPrivate(resp, source);
} else {
return;
}
}
displayGameMessage("<" + player->name + "> " + msg);
ChatPacket resp(minecraft->commandManager().execute(*minecraft, *player, Util::stringTrim(msg.substr(1))));
return sendPrivate(resp, source);
}
if (LuaEngine::get().onChat(player, msg)) return;
displayGameMessage("<" + player->name + "> " + msg);
}
void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ChatPacket* packet)
@ -193,26 +180,15 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ChatPack
if (player == nullptr) return; // @todo maybe kick?
MessageEvent event;
event.m_decline = false;
if (packet->message[0] == '/') {
// This is a command
PluginsManager::get().emit("Message", LuaPlayer(source), packet->message, event);
if (!event.m_decline) {
if (packet->message[0] == '/') {
// This is a command
auto cmd = Util::stringTrim(packet->message.substr(1));
if (PluginsManager::get().emitCommands(cmd, source)) {
ChatPacket resp(minecraft->commandManager().execute(*minecraft, *player, cmd));
return sendPrivate(resp, source);
} else {
return;
}
}
displayGameMessage("<" + player->name + "> " + packet->message);
ChatPacket resp(minecraft->commandManager().execute(*minecraft, *player, Util::stringTrim(packet->message.substr(1))));
return sendPrivate(resp, source);
}
if (LuaEngine::get().onChat(player, packet->message)) return;
displayGameMessage("<" + player->name + "> " + packet->message);
}
void ServerSideNetworkHandler::onNewClient(const RakNet::RakNetGUID& clientGuid)
@ -232,8 +208,8 @@ void ServerSideNetworkHandler::onDisconnect(const RakNet::RakNetGUID& guid)
if (player->owner == guid)
{
PluginsManager::get().emit("PlayerDisconnect", LuaPlayer(guid));
minecraft->level->getLevelStorage()->savePlayer(*player);
LuaEngine::get().onPlayerLeave(player);
std::string message = player->name;
message += " disconnected from the game";
@ -271,10 +247,7 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, LoginPac
std::string nicknameLower = packet->clientName.C_String();
std::transform(nicknameLower.begin(), nicknameLower.end(), nicknameLower.begin(), ::tolower);
RakNet::SystemAddress sysAddress = rakPeer->GetSystemAddressFromGuid(source);
char clientIp[32];
sysAddress.ToString(false, clientIp);
printf("%s lower \n", nicknameLower.c_str());
for (int i = 0; i < level->players.size(); i++) {
ServerPlayer* player = (ServerPlayer*) level->players.at(i);
@ -288,20 +261,13 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, LoginPac
}
}
for (auto& banned : level->bannedPpl) {
for (auto& banned : level->bannedPlayers) {
if (nicknameLower == banned) {
loginStatus = packet->newProto ? LoginStatus::Failed_Banned : LoginStatus::Failed_ClientOld;
break;
}
}
for (auto& banned : level->bannedIps) {
if (clientIp == banned) {
loginStatus = packet->newProto ? LoginStatus::Failed_Banned : LoginStatus::Failed_ClientOld;
break;
}
}
RakNet::BitStream bitStream;
LoginStatusPacket(loginStatus).write(&bitStream);
rakPeer->Send(&bitStream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, source, false);
@ -322,6 +288,9 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, LoginPac
LOGI("Adding new player... isCreative: %i\n", minecraft->isCreativeMode());
// The world is streamed in around the players: make sure the ground below the new player exists
level->ensureChunksAround((int)newPlayer->x, (int)newPlayer->z, 2);
// Reset the player so he doesn't spawn inside blocks
while (newPlayer->y > 0) {
newPlayer->setPos(newPlayer->x, newPlayer->y, newPlayer->z);
@ -361,6 +330,8 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ReadyPac
if (packet->type == ReadyPacket::READY_REQUESTEDCHUNKS)
onReady_RequestedChunks(source);
LOGI("Ready player two ready ready player two!!\n ");
}
void ServerSideNetworkHandler::onReady_ClientGeneration(const RakNet::RakNetGUID& source)
@ -388,6 +359,11 @@ void ServerSideNetworkHandler::onReady_ClientGeneration(const RakNet::RakNetGUID
for (unsigned int i = 0; i < players.size(); i++) {
Player* player = players[i];
if (!player->skinName.empty()) {
SetSkinPacket skinPacket(player->entityId, player->skinName);
sendPrivate(skinPacket, source);
}
bitStream.Reset();
AddPlayerPacket(player).write(&bitStream);
rakPeer->Send(&bitStream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, source, false);
@ -400,11 +376,13 @@ 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
LOGW("%s joined the game\n", newPlayer->name.c_str());
#endif
// Send all Entities to the new player
for (unsigned int i = 0; i < level->entities.size(); ++i) {
Entity* e = level->entities[i];
@ -420,6 +398,8 @@ 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();
@ -460,8 +440,6 @@ void ServerSideNetworkHandler::onReady_ClientGeneration(const RakNet::RakNetGUID
bitStream.Reset();
AddPlayerPacket(newPlayer).write(&bitStream);
rakPeer->Send(&bitStream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, source, true);
PluginsManager::get().emit("PlayerJoin", LuaPlayer(source));
}
//
@ -506,22 +484,16 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, MovePlay
// }
// }
PluginsManager::get().emit(
"PlayerMovement",
LuaPlayer(source),
packet->x, packet->y, packet->z, packet->yRot, packet->xRot, // newPos
player->x, player->y, player->z, player->yRot, player->xRot // oldPos
);
entity->xd = entity->yd = entity->zd = 0;
entity->lerpTo(packet->x, packet->y, packet->z, packet->yRot, packet->xRot, 3);
// broadcast this packet to other clients
redistributePacket(packet, source);
}
}
void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, RemoveBlockPacket* packet) {
void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, RemoveBlockPacket* packet){
if (!level) return;
Player* player = getPlayer(source);
@ -531,6 +503,13 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, RemoveBl
int x = packet->x, y = packet->y, z = packet->z;
if (LuaEngine::get().onBlockBreak(player, x, y, z)) {
// a mod cancelled it: put the block back on the client
UpdateBlockPacket restore(x, y, z, level->getTile(x, y, z), level->getData(x, y, z));
sendPrivate(restore, source);
return;
}
// code copied from GameMode.cpp
int oldId = level->getTile(x, y, z);
int data = level->getData(x, y, z);
@ -559,8 +538,6 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, RemoveBl
oldTile->destroy(level, x, y, z, data);
// RemoveEntityPacket packet(e->entityId);
// redistributePacket(&packet, rakPeer->GetMyGUID());
}
LOGI("Remove block [%i, %i, %i]\n", packet->x, packet->y, packet->z);
@ -684,6 +661,31 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, Interact
}
}
static bool validSkinName(const std::string& s) {
if (s.empty() || s.size() > 32) return false;
for (size_t i = 0; i < s.size(); ++i) {
char c = s[i];
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-'))
return false;
}
return true;
}
void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet)
{
if (!level) return;
Player* player = getPlayer(source);
if (!player) return;
std::string skin = packet->skin.C_String();
if (!validSkinName(skin)) skin.clear();
player->skinName = skin;
// everybody else needs to know (the sender already wears it)
SetSkinPacket out(player->entityId, skin);
redistributePacket(&out, source);
}
void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, AnimatePacket* packet)
{
if (!level)
@ -781,6 +783,21 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, UseItemP
Player* player = (Player*) entity;
int x = packet->x, y = packet->y, z = packet->z;
if (packet->face != 255 && LuaEngine::get().onUseItem(player, x, y, z, packet->face, &packet->item)) {
// cancelled by a mod: refresh the clicked block and the block that would have been placed
static const int dx[] = { 0, 0, 0, 0, -1, 1 };
static const int dy[] = { -1, 1, 0, 0, 0, 0 };
static const int dz[] = { 0, 0, -1, 1, 0, 0 };
UpdateBlockPacket a(x, y, z, level->getTile(x, y, z), level->getData(x, y, z));
sendPrivate(a, source);
if (packet->face < 6) {
int px = x + dx[packet->face], py = y + dy[packet->face], pz = z + dz[packet->face];
UpdateBlockPacket b(px, py, pz, level->getTile(px, py, pz), level->getData(px, py, pz));
sendPrivate(b, source);
}
return;
}
Tile* t = Tile::tiles[level->getTile(x, y, z)];
if (t == Tile::invisible_bedrock) return;

View file

@ -48,6 +48,7 @@ public:
//virtual void handle(const RakNet::RakNetGUID& source, TeleportEntityPacket* packet);
virtual void handle(const RakNet::RakNetGUID& source, InteractPacket* packet);
virtual void handle(const RakNet::RakNetGUID& source, AnimatePacket* packet);
virtual void handle(const RakNet::RakNetGUID& source, SetSkinPacket* packet);
virtual void handle(const RakNet::RakNetGUID& source, UseItemPacket* packet);
virtual void handle(const RakNet::RakNetGUID& source, EntityEventPacket* packet);
virtual void handle(const RakNet::RakNetGUID& source, PlayerActionPacket* packet);
@ -59,6 +60,7 @@ public:
virtual void handle(const RakNet::RakNetGUID& source, SignUpdatePacket* packet);
virtual void handle(const RakNet::RakNetGUID& source, ChatPacket* packet);
virtual void handle(const RakNet::RakNetGUID& source, MessagePacket* packet);
virtual void handle(const RakNet::RakNetGUID& source, WantCreatePacket* packet);
bool allowsIncomingConnections() { return _allowIncoming; }
@ -67,7 +69,7 @@ public:
Player* popPendingPlayer(const RakNet::RakNetGUID& source);
void displayGameMessage(const std::string& message);
private:
/**
* @brief Send packet to all players
*/
@ -80,8 +82,6 @@ public:
Player* getPlayer(const RakNet::RakNetGUID& source);
private:
Minecraft* minecraft;
Level* level;
IRakNetInstance* raknetInstance;

View file

@ -233,12 +233,8 @@ std::string CommandServer::parse(ConnectedClient& client, const std::string& s)
apiPosTranslate.from(x0, y0, z0);
apiPosTranslate.from(x1, y1, z1);
if (x0 < 0) x0 = 0;
if (y0 < 0) y0 = 0;
if (z0 < 0) z0 = 0;
if (x1 >= LevelConstants::LEVEL_WIDTH ) x1 = LevelConstants::LEVEL_WIDTH - 1;
if (y1 >= LevelConstants::LEVEL_HEIGHT) y1 = LevelConstants::LEVEL_HEIGHT - 1;
if (z1 >= LevelConstants::LEVEL_DEPTH ) z1 = LevelConstants::LEVEL_DEPTH - 1;
for (int y = y0; y <= y1; ++y)
for (int z = z0; z <= z1; ++z)

View file

@ -9,6 +9,7 @@
#include "AnimatePacket.h"
#include "AdventureSettingsPacket.h"
#include "ChatPacket.h"
#include "SetSkinPacket.h"
#include "ContainerAckPacket.h"
#include "ContainerOpenPacket.h"
#include "ContainerClosePacket.h"

View file

@ -0,0 +1,38 @@
#ifndef NET_MINECRAFT_NETWORK_PACKET__SetSkinPacket_H__
#define NET_MINECRAFT_NETWORK_PACKET__SetSkinPacket_H__
#include "../Packet.h"
// Tells everyone which skin file (data/images/skins/<name>.png) a player wears.
class SetSkinPacket: public Packet
{
public:
int entityId;
RakNet::RakString skin;
SetSkinPacket() : entityId(0) {}
SetSkinPacket(int entityId, const std::string& skin)
: entityId(entityId),
skin(skin.c_str())
{}
void write(RakNet::BitStream* bitStream)
{
bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SETSKIN));
bitStream->Write(entityId);
bitStream->Write(skin);
}
void read(RakNet::BitStream* bitStream)
{
bitStream->Read(entityId);
bitStream->Read(skin);
}
void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback)
{
callback->handle(source, (SetSkinPacket*)this);
}
};
#endif /*NET_MINECRAFT_NETWORK_PACKET__SetSkinPacket_H__*/

View file

@ -10,13 +10,10 @@
static const char* errIdString = 0;
void checkError() {
ALenum err = alGetError();
if(err == AL_NO_ERROR) return;
while (1) {
ALenum err = alGetError();
if(err == AL_NO_ERROR) return;
LOGI("### SoundSystemAL error: %d ####: %s\n", err, errIdString==0?"(none)":errIdString);
}
LOGI("### SoundSystemAL error: %d ####: %s\n", err, errIdString==0?"(none)":errIdString);
}
//typedef ALvoid AL_APIENTRY (*alBufferDataStaticProcPtr) (const ALint bid, ALenum format, ALvoid *data, ALsizei size, ALsizei freq);

View file

@ -1,160 +0,0 @@
#pragma once
#include <cstdint>
#include <raknet/RakNetTypes.h>
#include <plugins/PluginsManager.hpp>
#include <network/ServerSideNetworkHandler.h>
#include <world/entity/player/Player.h>
#include <client/Minecraft.h>
#include <network/packet/ChatPacket.h>
#include <network/packet/MovePlayerPacket.h>
#include <network/packet/RemoveItemPacket.h>
#include <network/packet/SetHealthPacket.h>
#include <network/packet/TakeItemPacket.h>
#include <world/entity/player/Inventory.h>
// TODO: Optimize includes
class LuaPlayer {
public:
LuaPlayer(const RakNet::RakNetGUID source) : m_source(source) {}
Player* getPlayer() {
auto mc = PluginsManager::get().getMinecraft();
ServerSideNetworkHandler* ss = (ServerSideNetworkHandler*) mc->netCallback;
auto plr = ss->getPlayer(m_source);
return plr;
}
std::string getNickname() {
auto plr = getPlayer();
if (plr != nullptr) return plr->name;
return "";
}
std::tuple<float, float, float, float, float> getPos() {
auto plr = getPlayer();
if (plr != nullptr) return {plr->x, plr->y, plr->z, plr->yRot, plr->xRot};
return {0, 0, 0, 0, 0};
}
void setPos(float x, float y, float z, float yRot, float xRot) {
auto plr = getPlayer();
if (plr == nullptr) return;
auto mc = PluginsManager::get().getMinecraft();
ServerSideNetworkHandler* ss = (ServerSideNetworkHandler*) mc->netCallback;
// plr->x = x;
// plr->y = y;
// plr->z = z;
// plr->yRot = yRot;
// plr->xRot = xRot;
plr->xd = plr->yd = plr->zd = 0;
plr->lerpTo(x, y, z, yRot, xRot, 3);
MovePlayerPacket move(plr->entityId, x, y, z, yRot, xRot);
ss->sendPrivate(move, m_source);
}
void sendMessage(std::string msg) {
auto mc = PluginsManager::get().getMinecraft();
ServerSideNetworkHandler* ss = (ServerSideNetworkHandler*) mc->netCallback;
ChatPacket packet(msg);
ss->sendPrivate(packet, m_source);
}
void addItem(int id, int count, int auxValue) {
auto plr = getPlayer();
if (plr == nullptr) return;
auto mc = PluginsManager::get().getMinecraft();
ServerSideNetworkHandler* ss = (ServerSideNetworkHandler*) mc->netCallback;
auto item = new ItemInstance(id, count, auxValue);
if (!plr->inventory->add(item)) {
plr->inventory->add(item);
}
TakeItemPacket itemAdd(plr->entityId, count, auxValue, id);
ss->sendPrivate(itemAdd, m_source);
}
std::tuple<int, int, int> getItem(int index) {
auto plr = getPlayer();
if (plr == nullptr) return {0, 0, 0};
auto item = plr->inventory->getItem(index);
if (item != nullptr) {
return {item->id, item->count, item->getAuxValue()};
} else {
return {0, 0, 0};
}
}
void clearInventory() {
auto plr = getPlayer();
if (plr == nullptr) return;
auto mc = PluginsManager::get().getMinecraft();
ServerSideNetworkHandler* ss = (ServerSideNetworkHandler*) mc->netCallback;
for (int i = Inventory::MAX_SELECTION_SIZE; i < plr->inventory->getContainerSize(); i++) {
auto itm = plr->inventory->getItem(i);
if (itm != NULL) {
printf("remove %d \n", plr->inventory->removeResource(ItemInstance(itm->id, itm->count, itm->getAuxValue())));
RemoveItemPacket itemAdd(plr->entityId, itm->count, itm->getAuxValue(), itm->id);
ss->sendPrivate(itemAdd, m_source);
}
}
}
sol::table getInventory() {
auto plr = getPlayer();
if (plr == nullptr) return {};
sol::table inv = PluginsManager::get().getLua().create_table();
for (int i = Inventory::MAX_SELECTION_SIZE; i < plr->inventory->getContainerSize(); i++) {
auto itm = plr->inventory->getItem(i);
if (itm != NULL) {
inv[i - 8] = {itm->id, itm->count, itm->getAuxValue()};
} else {
inv[i - 8] = sol::lua_nil;
}
}
return inv;
}
int getHp() {
auto plr = getPlayer();
if (plr == nullptr) return -1;
return plr->health;
}
void setHp(int hp) {
auto plr = getPlayer();
if (plr == nullptr) return;
plr->health = hp;
auto mc = PluginsManager::get().getMinecraft();
ServerSideNetworkHandler* ss = (ServerSideNetworkHandler*) mc->netCallback;
SetHealthPacket hpPacket(plr->health);
ss->sendPrivate(hpPacket, m_source);
}
private:
const RakNet::RakNetGUID m_source;
};

View file

@ -1,11 +0,0 @@
#include <plugins/LuaServer.hpp>
#include <plugins/PluginsManager.hpp>
#include <network/ServerSideNetworkHandler.h>
#include <client/Minecraft.h>
void LuaServer::sendServerMessage(std::string msg) {
auto mc = PluginsManager::get().getMinecraft();
ServerSideNetworkHandler* ss = (ServerSideNetworkHandler*) mc->netCallback;
ss->displayGameMessage(msg);
}

View file

@ -1,7 +0,0 @@
#pragma once
#include <string>
class LuaServer {
public:
void sendServerMessage(std::string msg);
};

View file

@ -1,9 +0,0 @@
#pragma once
class MessageEvent {
public:
bool m_decline;
void setDecline(bool decline) { m_decline = decline; }
private:
};

View file

@ -1,103 +0,0 @@
#include <plugins/PluginsManager.hpp>
#include <plugins/LuaPlayer.hpp>
#include <plugins/LuaServer.hpp>
#include <client/Minecraft.h>
#include <filesystem>
#include "MessageEvent.hpp"
namespace fs = std::filesystem;
int PluginsManager::emitCommands(std::string command, const RakNet::RakNetGUID& source) {
std::vector<std::string> args;
std::string cmd;
int i = 0;
std::string word;
std::stringstream ss(command);
while (ss >> word) {
if (i == 0) {
cmd = word;
} else {
args.push_back(word);
}
i++;
}
auto it = m_luaCommands.find(cmd);
if (it == m_luaCommands.end()) return 1;
for (auto& callback : it->second) {
sol::protected_function_result result = callback(LuaPlayer(source), sol::as_table(args));
if (!result.valid()) {
sol::error err = result;
std::cout << err.what() << std::endl;
}
}
return 0;
}
void PluginsManager::init(Minecraft& minecraft) {
m_lua.open_libraries(sol::lib::base, sol::lib::package, sol::lib::string, sol::lib::math, sol::lib::table, sol::lib::io);
registerTypes();
m_minecraft = &minecraft;
}
void PluginsManager::registerTypes() {
// @note you cant just do that, because lua doesnt have access to the class in this case
// m_lua.set_function("subscribe", &PluginsManager::subscribe);
m_lua.set_function("subscribe", [this](std::string event, sol::protected_function func) {
m_callbacks[event].push_back(func);
});
m_lua.set_function("addCommand", [this](std::string commandName, sol::function func) {
m_luaCommands[commandName].push_back(func);
});
m_lua.new_usertype<LuaServer>(
"Server",
"sendMessage", &LuaServer::sendServerMessage
);
m_lua.new_usertype<LuaPlayer>(
"Player",
"getNickname", &LuaPlayer::getNickname,
"getPos", &LuaPlayer::getPos,
"setPos", &LuaPlayer::setPos,
"sendMessage", &LuaPlayer::sendMessage,
"getInventory", &LuaPlayer::getInventory,
"addItem", &LuaPlayer::addItem,
"getItem", &LuaPlayer::getItem,
"clearInventory", &LuaPlayer::clearInventory,
"getHp", &LuaPlayer::getHp,
"setHp", &LuaPlayer::setHp
);
m_lua.new_usertype<MessageEvent>(
"MessageEvent",
"setDecline", &MessageEvent::setDecline
);
m_lua["Server"] = &m_srv;
}
void PluginsManager::loadPlugins() {
std::string path = "plugins/";
if (fs::exists(path)) {
for (const auto& entry : fs::directory_iterator(path)) {
if (!fs::is_directory(entry.path().string())) {
m_lua.script_file(entry.path().string());
}
}
} else {
std::filesystem::create_directory(path);
}
}

View file

@ -1,56 +0,0 @@
#pragma once
#include <unordered_map>
#include <sol/sol.hpp>
#include <vector>
#include <iostream>
#include <plugins/LuaServer.hpp>
#include <raknet/RakNetTypes.h>
class Minecraft;
class PluginsManager {
public:
static inline PluginsManager& get() {
static PluginsManager inst;
return inst;
}
void init(Minecraft& minecraft);
void registerTypes();
void loadPlugins();
sol::state& getLua() { return m_lua; }
// @ai @note maybe we should rewrite it...
// problem that i dont know how to pass args in sol::function dynamically
// so i used ai
// sry :(
template<typename... Args>
void emit(std::string event, Args&&... args) {
auto it = m_callbacks.find(event);
if (it == m_callbacks.end()) return;
for (auto& callback : it->second) {
sol::protected_function_result result = callback(std::forward<Args>(args)...);
if (!result.valid()) {
sol::error err = result;
std::cout << err.what() << std::endl;
}
}
}
int emitCommands(std::string command, const RakNet::RakNetGUID& source);
Minecraft* getMinecraft() { return m_minecraft; }
private:
std::unordered_map<std::string, std::vector<sol::function>> m_callbacks;
std::unordered_map<std::string, std::vector<sol::function>> m_luaCommands;
LuaServer m_srv;
sol::state m_lua;
Minecraft* m_minecraft;
};

View file

@ -142,8 +142,8 @@ void seedMT( unsigned int seed, unsigned int *state, unsigned int *&next, int &l
// so-- that's why the only change I made is to restrict to odd seeds.
//
unsigned int x = ( seed | 1U ) & 0xFFFFFFFFU, *s = state;
int j;
register unsigned int x = ( seed | 1U ) & 0xFFFFFFFFU, *s = state;
register int j;
for ( left = 0, *s++ = x, j = N; --j;
*s++ = ( x *= 69069U ) & 0xFFFFFFFFU )
@ -154,8 +154,8 @@ void seedMT( unsigned int seed, unsigned int *state, unsigned int *&next, int &l
unsigned int reloadMT( unsigned int *state, unsigned int *&next, int &left )
{
unsigned int * p0 = state, *p2 = state + 2, *pM = state + M, s0, s1;
int j;
register unsigned int * p0 = state, *p2 = state + 2, *pM = state + M, s0, s1;
register int j;
if ( left < -1 )
seedMT( 4357U );

View file

@ -878,10 +878,10 @@ bool Entity::load( CompoundTag* tag )
float yy = pos->getFloat(1);
float zz = pos->getFloat(2);
// Add a small padding if standing next to the world edges
// The world is infinite, only keep the position inside the coordinate system
const float padding = bbWidth * 0.5f + 0.001f;
xx = Mth::clamp(xx, padding, (float)LevelConstants::LEVEL_WIDTH - padding);
zz = Mth::clamp(zz, padding, (float)LevelConstants::LEVEL_DEPTH - padding);
xx = Mth::clamp(xx, -(float)LevelConstants::LEVEL_WIDTH + padding, (float)LevelConstants::LEVEL_WIDTH - padding);
zz = Mth::clamp(zz, -(float)LevelConstants::LEVEL_DEPTH + padding, (float)LevelConstants::LEVEL_DEPTH - padding);
xo = xOld = x = xx;
yo = yOld = y = yy;

View file

@ -224,7 +224,7 @@ void Mob::baseTick()
if (hurtTime > 0) hurtTime--;
if (invulnerableTime > 0) invulnerableTime--;
if (health <= 0) {
if (this->hasDied()) {
deathTime++;
if (deathTime > SharedConstants::TicksPerSecond) {
beforeRemove();
@ -437,7 +437,8 @@ void Mob::setSize( float w, float h )
void Mob::heal( int heal )
{
if (health <= 0) return;
if (this->hasDied()) return;
health += heal;
if (health > 20) health = 20;
invulnerableTime = invulnerableDuration / 2;
@ -447,7 +448,8 @@ bool Mob::hurt( Entity* source, int dmg )
{
if (level->isClientSide) return false;
noActionTime = 0;
if (health <= 0) return false;
if (this->hasDied()) return false;
this->walkAnimSpeed = 1.5f;
@ -485,7 +487,7 @@ bool Mob::hurt( Entity* source, int dmg )
}
}
if (health <= 0) {
if (this->hasDied()) {
if (sound) level->playSound(this, getDeathSound(), getSoundVolume(), getVoicePitch());
die(source);
} else {
@ -892,7 +894,7 @@ void Mob::newServerAiStep() {
bool Mob::isImmobile()
{
return health <= 0;
return this->hasDied();
}
void Mob::jumpFromGround()

View file

@ -127,6 +127,8 @@ public:
virtual ItemInstance* getCarriedItem() {return NULL;}
virtual int getUseItemDuration() {return 0;}
virtual void swing();
inline bool hasDied() { return health <= 0; }
protected:
virtual void causeFallDamage(float distance);

View file

@ -390,7 +390,7 @@ void Player::travel(float xa, float ya) {
/*protected*/
bool Player::isImmobile() {
return health <= 0 || isSleeping();
return hasDied() || isSleeping();
}
/*protected*/
@ -447,8 +447,8 @@ void Player::aiStep() {
float tBob = (float) Mth::sqrt(xd * xd + zd * zd);
float tTilt = (float) Mth::atan(-yd * 0.2f) * 15.f;
if (tBob > 0.1f) tBob = 0.1f;
if (!onGround || health <= 0) tBob = 0;
if (onGround || health <= 0) tTilt = 0;
if (!onGround || hasDied()) tBob = 0;
if (onGround || hasDied()) tTilt = 0;
bob += (tBob - bob) * 0.4f;
tilt += (tTilt - tilt) * 0.8f;
@ -518,14 +518,6 @@ bool Player::isCreativeModeAllowed() {
return true;
}
//void Player::drop() {
// //drop(inventory.removeItem(inventory.selected, 1), false);
//}
void Player::drop(ItemInstance* item) {
drop(item, false);
}
void Player::drop(ItemInstance* item, bool randomly) {
if (item == NULL || item->isNull())
return;
@ -559,11 +551,6 @@ void Player::drop(ItemInstance* item, bool randomly) {
thrownItem->zd += Mth::sin(dir) * pow;
}
reallyDrop(thrownItem);
}
/*protected*/
void Player::reallyDrop(ItemEntity* thrownItem) {
level->addEntity(thrownItem);
}
@ -680,7 +667,7 @@ bool Player::hurt(Entity* source, int dmg) {
if (abilities.invulnerable) return false;
noActionTime = 0;
if (health <= 0) return false;
if (hasDied()) return false;
if(isSleeping() && !level->isClientSide) {
stopSleepInBed(true, true, false);
}

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