diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8506aae..3495542 100755 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -16,7 +16,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v5 with: - python-version: '3.11' + python-version: '3.14' - name: Install dependencies run: | sudo apt-get update @@ -63,7 +63,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v5 with: - python-version: '3.11' + python-version: '3.14' - name: Install dependencies run: | brew install cmake @@ -116,7 +116,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v5 with: - python-version: '3.11' + python-version: '3.14' - name: Install dependencies run: pip install -r requirements.txt - name: Set up MSVC developer environment diff --git a/.gitignore b/.gitignore index e8e69b6..12b7a0c 100755 --- a/.gitignore +++ b/.gitignore @@ -16,10 +16,6 @@ native/terrain_gen native/terrain_gen.exe native/mob_ai native/mob_ai.exe -native/pymc_native_server -native/pymc_native_server.exe -native/libpymc_native.so -native/pymc_native.dll native/libpymc_vanilla.so native/libpymc_vanilla.dylib native/pymc_vanilla.dll diff --git a/.python-version b/.python-version new file mode 100644 index 0000000..6324d40 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.14 diff --git a/CHANGELOG.md b/CHANGELOG.md index fe20a55..df4309e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,6 @@ # 更新日志 ## 1.2.1 - ### 合成与掉落 - 合成可用了:背包 2×2 合成格和工作台 3×3 都会实时显示产物,可点击取走、Shift 批量合成、数字键放入快捷栏、Q 丢出,关闭界面时合成格里的物品退回背包(满了就掉在地上)。 - 配方改用原版 1.21.1 完整数据(634 个有序 + 253 个无序配方,标签全部展开):任意木板都能做工作台、木棍等,可以混用不同木板;有序配方支持左右镜像;牛奶桶等合成后会留下空桶。数据由 `tools/gen_recipe_data.py` 生成。 @@ -28,7 +27,6 @@ - 大箱子:放置时按原版规则与旁边的单箱子合并(潜行只连点击的那只),破坏一半时另一半变回单箱子;打开显示 54 格大箱子界面;漏斗、比较器都把两半当作一个容器(右半在前)。 - 漏斗矿车:用物品放到铁轨上,沿直轨、弯轨、坡轨行驶,充能铁轨加速/刹车(靠墙起步),容器矿车按装载量减速;不在充能的激活铁轨上时每刻从上方容器吸一个物品或捡起掉落物;漏斗能向旁边/上方的漏斗矿车推入和抽取;右键打开 5 格界面,打几下会坏并掉出物品和内容物;随世界保存(`pymc_minecarts.json`)。也可以放普通矿车。 - 矿车可以乘坐(右键上车,W 推动,潜行下车),玩家走过去会推动矿车,矿车之间会相互碰撞推开,探测铁轨检测到矿车时充能、比较器读取容器矿车的装载量;运动中的矿车每刻同步位置。 -- 酿造台:5 格容器和界面;漏斗按原版分面规则投放(上方只进原料,侧面进空瓶/药水和烈焰粉,下方取出药水)。 - 堆肥桶:漏斗从上方投入可堆肥物品(原版概率表),满 7 层 20 刻后变成可取,下方漏斗取出骨粉;玩家右键投料、取骨粉;比较器读取层数。 - 爆炸的射线与暴露度改由 C++ 计算(仍在爆炸线程中,约快 10 倍)。 - 有 C++ 编译器时首次启动自动编译;CMake、`build.sh`、`build.bat` 和 CI 打包都会生成并带上该库。没有该库或设置 `PYMC_NATIVE_ENGINE=0` 时使用 Python 引擎(Python 引擎不搬运漏斗物品)。 @@ -41,7 +39,78 @@ - 准备出生区时 `stop` / Ctrl+C 会立即生效(不再等世界生成完);没有原生生成器时出生区只预生成 3x3,并逐区块显示进度。 ### 已知限制 -- 酿造台还不会真正酿造(只有容器、界面和漏斗规则);普通矿车不会自动载上生物。 +- 普通矿车不会自动载上生物(原版也不这样做,这里没有实现)。 + +## 1.2.2 + +### 酿造台 +- 酿造台:5 格容器和界面;漏斗按原版分面规则投放(上方只进原料,侧面进药水和烈焰粉,下方取出药水)。真正的酿造:烈焰粉提供 20 单位燃料,每次酿造 400 刻、消耗一个原料,药水瓶的状态随内容更新,存档保留进度。已支持常见的基础药水转换(水瓶 + 地狱疣 → 粗制药水,粗制药水 + 材料 → 治疗、速度、跳跃、力量等,萤石粉/红石粉增强/延长,发酵蛛眼转化,火药/龙息改为喷溅/滞留)。 + +### 药水外观 +- 药水的外观按 1.21.1 原版药水注册表的 id 发给客户端(`potion_contents`),水瓶、粗制药水、各种药水在物品栏里显示正确的种类;客户端回传的药水也能正确解析。id 来自原版注册表的注册顺序(仓库里 `world/data/potions.json` 只保存名字和顺序)。 + +### 附魔与附魔书 +- 附魔数据取自 1.21.1 原版注册表(`tools/gen_enchantment_data.py` 生成 `world/data/enchantments.json`):最高等级、费用公式、权重、铁砧费用、可附魔的物品、互斥组、宝藏/诅咒。 +- 附魔信息随物品发给客户端:工具、护甲显示附魔光效和提示;附魔书显示存储的附魔(`stored_enchantments`)。客户端回传的附魔物品也能正确解析。 +- 附魔台:放入物品和青金石,按书架数量(最多 15)得到三个选项;选项的费用、附魔和等级与原版计算方式一致。点击后扣除青金石和等级,附魔台的种子随之改变。书会变成附魔书。 +- 铁砧:左边放物品,右边放附魔书(或同类物品),结果在右侧输出格,取走时扣除材料和等级;互斥的附魔不能合并;同级附魔合并后升一级;费用达到 40 级时不能取(创造模式除外)。 +- 关闭附魔台或铁砧时,里面的物品退还背包(放不下的掉在地上);破坏方块时照常掉落。 +- 铁砧的先前工作惩罚:每次合并后结果的惩罚为 `max(左, 右) * 2 + 1`,合并时两边的惩罚都计入费用(与原版一致)。 +- 新配置项 `anvil-too-expensive-limit`(默认 `true`,即原版行为):为 `true` 时费用达到 40 级不能取出(创造模式除外);设为 `false` 后不限制费用,等级足够即可取出。 + +### 移除 +- 删除网页管理台(`admin/web.py` 及其配置项 `web-admin-*`)。控制台命令、RCON(如启用)和权限文件(`permissions.json`)不受影响。 +- 删除未使用的旧模块:旧红石实现(`world/redstone_legacy.py`)、方块表生成脚本、看门狗的健康检查与自动重启、Python 版 worldgen 客户端、早期的 C++ 服务端/光照/物理/插件/模组代码,以及从未被调用的命令模块(`core`、`server`、`gamerule`)和未注册的记分板实现(`commands/vanilla/scoreboard.py`)。 +- 删除被覆盖的命令注册(同名命令只保留实际生效的那一个)。 + +### 清理与修复 +- 修复:`execute store` 和 `execute if score` 读写的记分板与 `/scoreboard`、`/trigger` 不是同一个,现在统一为同一份数据。 +- 修复:关闭附魔台或铁砧时,背包放不下的退还物品会报错(缺少导入),现在会掉落在地上。 +- 合并重复代码:两个地形生成器共用的树木、植物、水下装饰方法移到 `world/terrain_decor.py`;多个版本的区块包(1.17/1.19/1.20)改为共用一份实现;`/xp` 与玩家经验计算共用同一条经验曲线。 +- CMake 只构建仍在使用的三个目标:`terrain_gen`、`mob_ai`、`pymc_vanilla`。 + +### 铁砧 +- 铁砧的先前工作惩罚:每次合并后结果的惩罚为 `max(左, 右) * 2 + 1`,合并时两边的惩罚都计入费用(与原版一致)。 +- 新配置项 `anvil-too-expensive-limit`(默认 `true`,即原版行为):为 `true` 时费用达到 40 级不能取出(创造模式除外);设为 `false` 后不限制费用,等级足够即可取出。 + +### 进度(1.12 起的 advancements) +- 1.12 把 1.11 的成就换成了进度(advancements)。`/advancement` 之前只改内存里的字典,现在真正维护进度,并发给客户端。 +- 进度树是原版"故事"分支中能由背包内容触发的部分(9 个):根进度(合成台)、获取圆石、升级工具、获取铁锭、获取盔甲、铁镐、岩浆桶、钻石、钻石装备。标题和描述用原版翻译键,由客户端按语言显示。再加上事件触发的 3 个(冒险分支):击杀生物(击杀任意生物、击杀敌对生物)、附魔。睡觉、进食、进入下界/末地、酿造等事件对应的功能服务端还没有实现,相关进度暂不在树里。 +- 进度按玩家保存在 `world/advancements/.json`(条件名 -> 获得时的毫秒时间戳)。进服时发送整棵树和该玩家的进度;获得新进度时发送增量并弹出提示。 +- 条件按背包内容判断(每 20 刻检查一次),所以获得进度有最多约 1 秒的延迟。 +- `/advancement grant|revoke <目标> everything|only|from|until|through [进度] [条件]` 按上面的进度树实际生效。`from`(自身及后代)、`until`(祖先)、`through`(祖先及自身)的含义是按原版命令的常见说明实现的,未逐条核对。 +- 进度包的编码按 1.21.1 的布局实现,已用官方服务端进服时发出的真实进度包核对骨架(条目、父级、需求、遥测布尔值、进度列表);显示信息部分(标题组件、图标、frame、背景、坐标)没有官方样本可对照,尚未在真实客户端里看过。 +- 其他协议版本暂不发送进度包。 + +### 光照(C++) +- 区块光照的计算移到原生库(`native/vanilla/light.h`,`vrs_light_compute`),算法与 `world/lighting.py` 相同,测试要求两边的输出逐字节一致(随机方块、地形生成的区块)。 +- 原生调用本身约 0.15 ms,但区块数据目前是嵌套列表,转成扁平数组要约 3–4 ms,所以默认路径仍用 Python(嵌套列表时更快)。`compute_light_flat` 接收扁平数组,可以直接走原生路径。 +- 嵌套列表的光照仍走 Python(实测 1.5 ms,转成扁平数组再走原生要 3.8 ms)。原生路径只对扁平数组有收益(0.15 ms),目前没有调用方。 +- 光照仍然只在单个区块内计算,还不是原版的跨区块光照,与原版的差异没有解决。 + +### 生物群系(C++) +- 生物群系采样移到原生库(`native/vanilla/biome.h`,`vrs_biome_sections`)。噪声表仍由 Python 按原来的随机数算法生成,C++ 只做采样,所以结果与 Python 逐项一致(测试覆盖多个种子、真实地形和随机高度地形)。 +- 每个区块的群系从约 118 ms 降到约 2 ms。C++ 构建加了 `-ffp-contract=off`,避免乘加融合改变浮点结果。 + +### 生物生成 +- 重写自然生成(`world/spawning.py`),规则按原版 1.21.1 实现:敌对生物在亮度不超过 7 的地方生成(夜里天光减 11),动物在草方块上、亮度不低于 9 的地方生成;离玩家至少 24 格;和平难度不生成敌对生物;上限为每名玩家敌对 70、动物 10。 +- 消失:离所有玩家超过 128 格的生物移除;敌对生物超过 32 格有概率移除。 +- 近似之处:只在地表生成(原版也会在洞穴里生成),没有群体生成,天气不影响天光变暗。 + +### 运行环境 +- Python 版本提升到 3.14(最新稳定版)。CI 改用 3.14 测试和打包,`.python-version` 同步;测试在 3.14 上全部通过。 + +### 性能与内存 +- 生物 AI:每刻所有生物合并成一次原生 AI 请求(协议 `B`,玩家列表只发一次),原来是每只生物一次往返。300 只生物 + 200 个物品时每刻从约 17 ms 降到约 3.6 ms;批量与单只的决策结果完全一致(有测试)。 +- 矿车:实体按类型建索引(`EntityManager.of_kind`),碰撞用空间网格,只和邻近的车比较。200 辆车每刻从约 13.6 ms 降到约 3.2 ms。 +- 内存:启动后常驻内存约 115 MB 降到约 89 MB。模块导入时的方块状态表从约 32 MB 降到约 14 MB(共享键和属性对象),旧版状态表改为读取旧存档时才构建。 +- 解码后区块的缓存从 192 个降到 64 个(每个约 1.2 MB),可用 `chunk-decode-cache` 调整。 +- 原生红石引擎的区块镜像设上限(`redstone-chunk-cache`,默认 256,每个约 196 KB),超出时淘汰最久未用的区块,并去掉每 100 刻全量清空镜像的做法。 + +### 已知限制 +- 附魔还不支持:铁砧改名、修复耐久、附魔的随机掉落(战利品中的附魔书)。物品的可附魔值只覆盖常见的工具、武器和护甲,其它物品按不可附魔处理。 +- 药水的效果还没有实现:药水按原版注册表 id 显示外观(`potion_contents` 组件),但药效(速度、治疗、再生等)尚未作用于玩家。 +- 酿造配方只包含常见的基础药水,没有覆盖原版全部组合。 ## 1.2.0 diff --git a/CMakeLists.txt b/CMakeLists.txt index 908669f..3bfcded 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9,225 +9,33 @@ set(CMAKE_CXX_EXTENSIONS OFF) # Compiler flags # =========================================================== if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") - add_compile_options(-O2 -Wall -Wextra -fvisibility=hidden) - # Position-independent code for shared libraries - add_compile_options(-fPIC) - # Threading support + add_compile_options(-O2 -Wall -Wextra -fvisibility=hidden -fPIC) find_package(Threads REQUIRED) endif() if(MSVC) add_compile_options(/O2 /W3 /EHsc) - # Use static C runtime (/MT) so the resulting .exe files have no - # external DLL dependencies. This applies to Debug builds too; - # Debug will use /MTd instead via CMAKE_MSVC_RUNTIME_LIBRARY. + # Static C runtime (/MT): the .exe / .dll files have no external DLL dependencies. set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") - # Export all symbols for DLL set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) endif() # =========================================================== -# Legacy targets (original subprocess-based tools) +# Terrain generator (vanilla worldgen, must match Java bit for bit: no FMA, no fast-math) # =========================================================== add_executable(terrain_gen native/terrain_gen.cpp) target_compile_features(terrain_gen PRIVATE cxx_std_17) -# Vanilla terrain must match Java bit for bit: no fused multiply-add, no fast-math. if(MSVC) - # /fp:precise does not contract a*b+c into FMA (MSVC 2022+ needs /fp:contract for that) target_compile_options(terrain_gen PRIVATE /fp:precise /DNOMINMAX) else() target_compile_options(terrain_gen PRIVATE -ffp-contract=off -fno-fast-math) target_link_libraries(terrain_gen PRIVATE Threads::Threads) endif() -add_executable(mob_ai native/mob_ai.cpp) - -# rootree_worldgen uses C++20 features (std::rotl) -add_executable(rootree_worldgen src/main.cpp) -set_target_properties(rootree_worldgen PROPERTIES CXX_STANDARD 20) # =========================================================== -# Core IPC shared memory library -# =========================================================== -add_library(ipc_shm STATIC - native/core/ipc_shm.cpp -) -target_include_directories(ipc_shm PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/native/core -) -if(APPLE) - target_link_libraries(ipc_shm PUBLIC Threads::Threads) -elseif(UNIX) - target_link_libraries(ipc_shm PUBLIC Threads::Threads rt) -endif() - -# =========================================================== -# Redstone Engine -# =========================================================== -add_library(redstone_engine STATIC - native/redstone/redstone_engine.cpp -) -target_include_directories(redstone_engine PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/native/redstone - ${CMAKE_CURRENT_SOURCE_DIR}/native/core -) -target_link_libraries(redstone_engine PUBLIC ipc_shm) - -# =========================================================== -# Light Engine -# =========================================================== -add_library(light_engine STATIC - native/lighting/light_engine.cpp -) -target_include_directories(light_engine PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/native/lighting - ${CMAKE_CURRENT_SOURCE_DIR}/native/core -) -target_link_libraries(light_engine PUBLIC ipc_shm) - +# Mob AI helper process (talks to the server over stdin/stdout) # =========================================================== -# Physics Engine -# =========================================================== -add_library(physics_engine STATIC - native/physics/physics_engine.cpp -) -target_include_directories(physics_engine PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/native/physics - ${CMAKE_CURRENT_SOURCE_DIR}/native/core -) -target_link_libraries(physics_engine PUBLIC ipc_shm) - -# =========================================================== -# Native server process (uses shared memory IPC) -# =========================================================== -add_executable(pymc_native_server - native/pymc_native_server.cpp -) -target_include_directories(pymc_native_server PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/native - ${CMAKE_CURRENT_SOURCE_DIR}/native/core - ${CMAKE_CURRENT_SOURCE_DIR}/native/redstone - ${CMAKE_CURRENT_SOURCE_DIR}/native/lighting - ${CMAKE_CURRENT_SOURCE_DIR}/native/physics -) -target_link_libraries(pymc_native_server PRIVATE - ipc_shm - redstone_engine - light_engine - physics_engine -) - -# =========================================================== -# Combined shared library for in-process Python bindings -# (can be loaded via ctypes/cffi) -# =========================================================== -add_library(pymc_native SHARED - native/bindings/pymc_native_api.cpp - native/core/ipc_shm.cpp - native/redstone/redstone_engine.cpp - native/lighting/light_engine.cpp - native/physics/physics_engine.cpp -) -target_include_directories(pymc_native PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/native - ${CMAKE_CURRENT_SOURCE_DIR}/native/core - ${CMAKE_CURRENT_SOURCE_DIR}/native/redstone - ${CMAKE_CURRENT_SOURCE_DIR}/native/lighting - ${CMAKE_CURRENT_SOURCE_DIR}/native/physics - ${CMAKE_CURRENT_SOURCE_DIR}/native/bindings -) -if(APPLE) - target_link_libraries(pymc_native PUBLIC Threads::Threads) -elseif(UNIX) - target_link_libraries(pymc_native PUBLIC Threads::Threads rt) -endif() - -# =========================================================== -# PYMC Plugin API -# =========================================================== - -# Event System (header-only, always built) -add_library(plugin_event_system INTERFACE) -target_include_directories(plugin_event_system INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR}/native/plugins -) - -# PYMC Plugin API types (header-only, renamed from bukkit_api) -add_library(plugin_pymc_api INTERFACE) -target_include_directories(plugin_pymc_api INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR}/native/plugins -) - -# Plugin Loader (header-only, orchestrates the other components) -add_library(plugin_loader INTERFACE) -target_include_directories(plugin_loader INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR}/native/plugins -) -target_link_libraries(plugin_loader INTERFACE - plugin_event_system - plugin_pymc_api -) - -# Combined plugin shared library for Python ctypes bindings -# This will include C API bridge functions when implementation files are added -add_library(pymc_plugin_loader SHARED - native/plugins/plugin_loader_api.cpp -) -target_include_directories(pymc_plugin_loader PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/native - ${CMAKE_CURRENT_SOURCE_DIR}/native/plugins - ${CMAKE_CURRENT_SOURCE_DIR}/native/core -) -target_link_libraries(pymc_plugin_loader PUBLIC - plugin_loader - ipc_shm -) -if(APPLE) - target_link_libraries(pymc_plugin_loader PUBLIC Threads::Threads) -elseif(UNIX) - target_link_libraries(pymc_plugin_loader PUBLIC Threads::Threads rt dl) -endif() - -# =========================================================== -# PYMC Native Mod API -# =========================================================== - -# Mod Loader (header-only, core mod discovery & lifecycle management) -add_library(mod_loader INTERFACE) -target_include_directories(mod_loader INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR}/native/mods - ${CMAKE_CURRENT_SOURCE_DIR}/native/plugins - ${CMAKE_CURRENT_SOURCE_DIR}/native/core -) - -# PYMC Mod C API (header-only, C API bridge for ctypes) -add_library(mod_pymc_api INTERFACE) -target_include_directories(mod_pymc_api INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR}/native/mods -) -target_link_libraries(mod_pymc_api INTERFACE - mod_loader -) - -# Combined mod shared library for Python ctypes bindings -add_library(pymc_mod_loader SHARED - native/plugins/plugin_loader_api.cpp -) -target_include_directories(pymc_mod_loader PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}/native - ${CMAKE_CURRENT_SOURCE_DIR}/native/mods - ${CMAKE_CURRENT_SOURCE_DIR}/native/plugins - ${CMAKE_CURRENT_SOURCE_DIR}/native/core -) -target_link_libraries(pymc_mod_loader PUBLIC - mod_loader - mod_pymc_api - ipc_shm -) -if(APPLE) - target_link_libraries(pymc_mod_loader PUBLIC Threads::Threads) -elseif(UNIX) - target_link_libraries(pymc_mod_loader PUBLIC Threads::Threads rt dl) -endif() +add_executable(mob_ai native/mob_ai.cpp) # =========================================================== # Vanilla engine library: redstone / block updates, hoppers, explosions @@ -239,39 +47,18 @@ if(MSVC) target_compile_options(pymc_vanilla PRIVATE /DNOMINMAX) endif() -# =========================================================== -# Install targets -# =========================================================== install(TARGETS terrain_gen mob_ai - pymc_native_server - pymc_native - pymc_plugin_loader - pymc_mod_loader pymc_vanilla RUNTIME DESTINATION native LIBRARY DESTINATION native ) -# =========================================================== -# Windows + MinGW: statically link the C++ runtime libraries -# (libgcc, libstdc++, libwinpthread) so the resulting .exe files -# can run on user machines without requiring MSYS2/MinGW DLLs -# in PATH. Without this, terrain_gen.exe / mob_ai.exe crash -# immediately on machines that don't have MinGW installed. -# -# This must come AFTER all add_executable() calls because -# target_link_options requires the target to already exist. -# =========================================================== +# Windows + MinGW: statically link the C++ runtime so the binaries run without MinGW DLLs. if(MINGW) - set(MINGW_STATIC_LINK_FLAGS - -static-libgcc - -static-libstdc++ - -static - ) - target_link_options(terrain_gen PRIVATE ${MINGW_STATIC_LINK_FLAGS}) - target_link_options(mob_ai PRIVATE ${MINGW_STATIC_LINK_FLAGS}) - target_link_options(pymc_native_server PRIVATE ${MINGW_STATIC_LINK_FLAGS}) - target_link_options(pymc_vanilla PRIVATE ${MINGW_STATIC_LINK_FLAGS}) + set(MINGW_STATIC_LINK_FLAGS -static-libgcc -static-libstdc++ -static) + target_link_options(terrain_gen PRIVATE ${MINGW_STATIC_LINK_FLAGS}) + target_link_options(mob_ai PRIVATE ${MINGW_STATIC_LINK_FLAGS}) + target_link_options(pymc_vanilla PRIVATE ${MINGW_STATIC_LINK_FLAGS}) endif() diff --git a/README.md b/README.md index 3636870..14a920b 100755 --- a/README.md +++ b/README.md @@ -36,13 +36,12 @@ PyMC 是一个用 Python 实现的 Minecraft Java 版 1.21.1 服务端原型, - [x] **登录检查**:用户名合法性、协议版本(过旧/过新客户端提示)、封禁、白名单、服务器已满、同名重复登录踢出旧连接、`player-idle-timeout`。 - [x] **玩法细节**:死亡界面与原版死亡消息、掉落物品与经验、重生流程、`keepInventory`/`doImmediateRespawn`/`showDeathMessages` 等规则、受伤动画与击退、PvP(`pvp`)、潜行/疾跑/挥手/手持物品同步、生存/创造模式挖掘与放置确认、`spawn-protection`、天空光与方块光计算。 - [x] 控制台和游戏内基础命令。 -- [x] Web 管理台、权限组、OP、封禁和白名单。 +- [x] 权限组、OP、封禁和白名单。 - [x] 单元测试覆盖原生地形、原版存档读写与迁移、玩家存档、原生 AI、种子解析和安全出生点。 - [x] **红石系统**:tick 引擎、电源/导线/火把/中继器/比较器/观察者/活塞、门与灯控制、TNT 起爆、音符盒、发射器/投掷器;红石时序为原版近似。 - [x] **合成**:背包 2×2 与工作台 3×3,原版 1.21.1 全部有序/无序配方(标签展开、镜像、合成剩余物),Shift 批量合成。 -- [x] **物品栏系统**:`ItemStack`、玩家物品栏、协议序列化、左右键/Shift/数字键/拖拽/丢弃,以及方块容器交互与持久化;铁砧/附魔台等专业界面仍为简化。 +- [x] **物品栏系统**:`ItemStack`、玩家物品栏、协议序列化、左右键/Shift/数字键/拖拽/丢弃,以及方块容器交互与持久化;附魔台和铁砧已实现(附魔、先前工作惩罚、费用上限可由 `anvil-too-expensive-limit` 关闭);药水外观已实现,药效尚未实现。 - [x] **PYMC 原生扩展 API**:支持 Python Mod/Plugin 的发现、依赖排序、生命周期、事件和命令注册。Java Fabric/Forge Mod 不受支持;Bukkit/Paper `.jar` 插件通过可选 Java 桥接层提供 best-effort 兼容,详见 `MOD_COMPATIBILITY.md`。 -- [x] **Web 管理台安全默认值**:默认只监听 `127.0.0.1`;由于当前没有内置认证,远程监听必须显式设置 `web-admin-allow-remote=true` 并部署外部访问控制。 ### 部分实现(不可视为完成) @@ -62,7 +61,7 @@ PyMC 是一个用 Python 实现的 Minecraft Java 版 1.21.1 服务端原型, - [ ] 完整洞穴系统:大型洞穴、繁茂洞穴、溶洞、地下水体、岩浆湖、深暗之域等。 - [ ] Nether、End 和多维度传送。 - [ ] 完整光照和客户端可见的区块更新细节。 -- [ ] 更完整的物品栏交互:创造模式物品栏、铁砧/附魔台完整界面、药水效果。 +- [ ] 更完整的物品栏交互:创造模式物品栏、铁砧改名与修复、药水效果。 - [ ] 更完整的生物系统:完整 A* 寻路、繁殖、村民、Boss、刷怪规则和 mob cap。 - [ ] 更完整的选择器、NBT 参数和 datapack/function 支持。 @@ -101,7 +100,7 @@ PyMC 是一个用 Python 实现的 Minecraft Java 版 1.21.1 服务端原型, - 基础 `gamerule`:控制昼夜流动、天气循环、自然刷怪、自然回血和死亡自动重生 - 天气客户端同步:Game Event 广播下雨/雷暴状态与强度,入服时同步当前天气;雷暴期间落雷并伤害附近实体 - 控制台和游戏内基础命令 -- Web 管理台、权限组、OP、封禁和白名单 +- 权限组、OP、封禁和白名单 ## 目录 @@ -118,19 +117,17 @@ PyMC 是一个用 Python 实现的 Minecraft Java 版 1.21.1 服务端原型, - `world/block_behavior.py`:方块行为系统 - `world/fluids.py`:流体系统 - `commands/`:命令框架和原版命令 -- `admin/`:权限系统和 Web 管理后台 -- `watchdog/`:双进程保护系统 +- `admin/`:权限系统 +- `watchdog/`:进程管理 - `watchdog/process_manager.py`:Watchdog 管理器 - `watchdog/network_optimizer.py`:网络优化器 - - `watchdog/health_check.py`:健康检查 - - `watchdog/restart_handler.py`:自动重启处理 - `mods/`:PYMC 原生 Python Mod API - `plugins/`:PYMC 原生 Python Plugin API + Java Bukkit/Paper 桥接层(`plugins/java_plugin.py`) -- `native/`:C++ 原生地形生成器、轻量生物 AI、红石引擎、光照引擎、物理引擎及 PYMC 原生扩展接口 +- `native/`:C++ 原生组件——地形生成器(`terrain_gen`)、生物 AI 进程(`mob_ai`)、原版行为引擎(`vanilla`:红石/BUD、漏斗、爆炸) ## 运行 -需要 Python 3.10 或更新版本。 +需要 Python 3.14(最新稳定版;测试在 3.14 上通过)。 ```bash pip install -r requirements.txt @@ -143,7 +140,6 @@ python main.py --nogui 默认监听: - Minecraft 服务端: `0.0.0.0:25565` -- Web 管理台: `127.0.0.1:25568`(无内置认证,默认禁止远程监听) - Watchdog UDP 健康检查: `127.0.0.1:25569` (启用时) 使用 Minecraft Java 1.21.1 客户端连接 `localhost:25565`。 @@ -162,9 +158,9 @@ python main.py --nogui - `view-distance`:区块视距 - `level-seed`:世界种子 - `gamemode`:默认游戏模式 -- `web-admin-enabled`:是否启用 Web 管理台 -- `web-admin-host`:管理台监听地址,默认 `127.0.0.1` -- `web-admin-allow-remote`:允许无内置认证的远程监听;仅应在受认证反向代理等外部访问控制保护时启用 +- `chunk-decode-cache`:解码后的区块缓存数量,每个约 1.2 MB,默认 64 +- `redstone-chunk-cache`:原生红石引擎保留的区块数,每个约 196 KB,默认 256 +- `anvil-too-expensive-limit`:铁砧合并费用达到 40 级时是否禁止取出(原版为 `true`;设为 `false` 后不限制费用,等级足够即可取出) - `permissions-file`:权限文件路径 - `join-immediate-radius`:玩家入服时优先同步的近距离区块半径 - `min-protocol-version` / `max-protocol-version`:允许的协议版本范围 (默认 47-770) diff --git a/admin/permissions.py b/admin/permissions.py index b63ba09..1dfa61b 100755 --- a/admin/permissions.py +++ b/admin/permissions.py @@ -292,9 +292,6 @@ def snapshot(self) -> dict: def list_groups(self) -> dict: return deepcopy(self.data["groups"]) - def list_users(self) -> dict: - return deepcopy(self.data["users"]) - def get_user_record(self, username: str) -> dict: key = username.lower() users = self.data["users"] @@ -315,15 +312,6 @@ def set_user_group(self, username: str, group: str): record["group"] = group self.save() - def set_group(self, name: str, permissions: list[str], inherits: list[str] | None = None): - if name == "default" and inherits: - logger.warning("default 组通常不建议继承其他组") - self.data["groups"][name] = { - "inherits": inherits or [], - "permissions": sorted(set(permissions)), - } - self.save() - # ------------------------------------------------------------------ # 权限判定 # ------------------------------------------------------------------ @@ -452,9 +440,6 @@ def remove_whitelist(self, username: str) -> bool: self.save() return True - def get_whitelist(self) -> dict: - return deepcopy(self.data["whitelist"]) - def check_login(self, username: str, ip: str): """ 登录检查。允许时返回 None, 否则返回断开原因 (文本组件), @@ -478,23 +463,6 @@ def check_login(self, username: str, ip: str): return None - def check_login_allowed(self, username: str, ip: str) -> str | None: - """兼容旧接口: 返回纯文本原因。""" - reason = self.check_login(username, ip) - if reason is None: - return None - from protocol.text import plain_text - return plain_text(reason) - - def get_web_payload(self) -> dict: - return { - "groups": self.list_groups(), - "users": self.list_users(), - "ops": list(self.data["ops"]), - "bans": self.get_banlist(), - "whitelist": self.get_whitelist(), - } - def _collect_group_permissions(self, group_name: str, seen: set[str] | None = None) -> set[str]: seen = seen or set() if group_name in seen: diff --git a/admin/web.py b/admin/web.py deleted file mode 100755 index 35e7c57..0000000 --- a/admin/web.py +++ /dev/null @@ -1,977 +0,0 @@ -# ============================================================ -# PyMC - Web 管理后台 -# ============================================================ - -import asyncio -import ipaddress -import json -import logging -import threading -from http import HTTPStatus -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -from urllib.parse import parse_qs, urlparse - -logger = logging.getLogger("PyMC.Web") - - -HTML_PAGE = """ - - - - - PyMC Admin - - - -
- -
-
-
-

仪表盘

-
服务器运行概览
-
-
- - 未连接 - -
-
- -
-
-
运行状态
-
-
在线玩家
-
-
世界时间
-
-
非玩家实体
-
-
-

快速控制

-
- - - - - -
-
-
-
-

运行参数

-
-
-
-

在线玩家

-
-
-
-
- -
-
-
-

控制台

-
- - - -
-
等待命令
-
-
-

服务端日志

-
- -
-
等待日志
-
-
-
- -
-
-
-

玩家管理

-
-
-
-

玩家操作

-
- - - - - - -
-
- - - - - -
-
-
-
- -
-
-
-

世界

-
- - -
-
- - -
-
- - - - -
-
-
-

游戏规则

-
-
-
-

实体

-
- - - - - - -
-
-
-
-
- -
-
-
-

权限组

-
- - - -
-
等待权限数据
-
-
-

白名单与封禁

-
- - - -
-
- - - -
-
- - - - - -
-
-
-
- -
-
-
-

server.properties

-
-
- - -
-
-
-
-
- -
-
-
-

文件编辑

-
- - - -
- -
-
-
-
- -
-
-
-

命令目录

-
- -
-
-
-
-
-
-
- - - - -""" - - -class WebAdminServer: - """轻量 Web 管理端。""" - - def __init__(self, server, host: str, port: int, - allow_remote: bool = False): - self.server = server - self.host = host - self.port = port - self.allow_remote = allow_remote - self._httpd: ThreadingHTTPServer | None = None - self._thread: threading.Thread | None = None - - def start(self): - if self._httpd is not None: - return - if not self.allow_remote and not self._is_loopback_host(self.host): - raise ValueError( - "Web admin has no authentication and may only bind to loopback. " - "Set web-admin-allow-remote=true only when protected by an " - "authenticated reverse proxy or equivalent access control." - ) - handler_cls = self._make_handler() - self._httpd = ThreadingHTTPServer((self.host, self.port), handler_cls) - self._thread = threading.Thread( - target=self._httpd.serve_forever, - name="PyMC-WebAdmin", - daemon=True, - ) - self._thread.start() - logger.info(f"Web admin console running on http://{self.host}:{self.port}") - - @staticmethod - def _is_loopback_host(host: str) -> bool: - normalized = host.strip().lower() - if normalized == "localhost": - return True - try: - return ipaddress.ip_address(normalized).is_loopback - except ValueError: - return False - - def stop(self): - if self._httpd is None: - return - self._httpd.shutdown() - self._httpd.server_close() - self._httpd = None - logger.debug("Web admin console stopped") - - def _make_handler(self): - outer = self - - class Handler(BaseHTTPRequestHandler): - def do_GET(self): - parsed = urlparse(self.path) - if parsed.path == "/": - self._send_html(HTML_PAGE) - return - if parsed.path == "/api/status": - self._send_json(outer._status_payload()) - return - if parsed.path == "/api/permissions": - self._send_json(outer.server.permissions.get_web_payload()) - return - if parsed.path == "/api/properties": - self._send_json(outer.properties_payload()) - return - if parsed.path == "/api/logs": - lines = parse_qs(parsed.query).get("lines", ["240"])[0] - try: - line_count = max(20, min(2000, int(lines))) - except ValueError: - line_count = 240 - self._send_json({"content": outer.read_log_tail(line_count)}) - return - if parsed.path == "/api/file": - name = parse_qs(parsed.query).get("name", [""])[0] - try: - content = outer.read_allowed_file(name) - self._send_json({"name": name, "content": content}) - except Exception as e: - self._send_json({"error": str(e)}, HTTPStatus.BAD_REQUEST) - return - self._send_json({"error": "not found"}, HTTPStatus.NOT_FOUND) - - def do_POST(self): - parsed = urlparse(self.path) - try: - payload = self._read_json() - except Exception as e: - self._send_json({"error": f"无效 JSON: {e}"}, HTTPStatus.BAD_REQUEST) - return - - if parsed.path == "/api/command": - command = payload.get("command", "").strip() - if not command: - self._send_json({"error": "命令不能为空"}, HTTPStatus.BAD_REQUEST) - return - result = outer.run_command(command) - self._send_json(result) - return - - if parsed.path == "/api/permissions/user": - username = payload.get("username", "").strip() - group = payload.get("group", "").strip() - if not username or not group: - self._send_json({"error": "username 和 group 必填"}, HTTPStatus.BAD_REQUEST) - return - try: - outer.server.permissions.set_user_group(username, group) - except Exception as e: - self._send_json({"error": str(e)}, HTTPStatus.BAD_REQUEST) - return - self._send_json(outer.server.permissions.get_web_payload()) - return - - if parsed.path == "/api/permissions/group": - name = payload.get("name", "").strip() - permissions = payload.get("permissions", []) - inherits = payload.get("inherits", []) - if not name: - self._send_json({"error": "组名不能为空"}, HTTPStatus.BAD_REQUEST) - return - outer.server.permissions.set_group(name, permissions, inherits) - self._send_json(outer.server.permissions.get_web_payload()) - return - - if parsed.path == "/api/properties": - properties = payload.get("properties", {}) - if not isinstance(properties, dict): - self._send_json({"error": "properties 必须是对象"}, HTTPStatus.BAD_REQUEST) - return - try: - result = outer.write_properties(properties) - self._send_json(result) - except Exception as e: - self._send_json({"error": str(e)}, HTTPStatus.BAD_REQUEST) - return - - if parsed.path == "/api/file": - name = parse_qs(parsed.query).get("name", [""])[0] - try: - outer.write_allowed_file(name, payload.get("content", "")) - self._send_json({"message": f"已保存 {name}"}) - except Exception as e: - self._send_json({"error": str(e)}, HTTPStatus.BAD_REQUEST) - return - - self._send_json({"error": "not found"}, HTTPStatus.NOT_FOUND) - - def log_message(self, fmt, *args): - logger.debug(fmt, *args) - - def _read_json(self): - length = int(self.headers.get("Content-Length", "0")) - raw = self.rfile.read(length) if length > 0 else b"{}" - return json.loads(raw.decode("utf-8")) - - def _send_json(self, payload: dict, status: int = HTTPStatus.OK): - body = json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8") - self.send_response(status) - self.send_header("Content-Type", "application/json; charset=utf-8") - self.send_header("Content-Length", str(len(body))) - self.end_headers() - self.wfile.write(body) - - def _send_html(self, html: str): - body = html.encode("utf-8") - self.send_response(HTTPStatus.OK) - self.send_header("Content-Type", "text/html; charset=utf-8") - self.send_header("Content-Length", str(len(body))) - self.end_headers() - self.wfile.write(body) - - return Handler - - def run_command(self, command: str) -> dict: - from handlers.play import execute_server_command - future = asyncio.run_coroutine_threadsafe( - execute_server_command(self.server, command), - self.server.loop, - ) - handled = future.result(timeout=10) - return { - "command": command, - "handled": handled, - "players": [p.username for p in self.server.get_online_players()], - } - - def allowed_files(self) -> dict[str, Path]: - permissions_name = Path(self.server.permissions.filepath).name - files = { - "server.properties": Path("server.properties"), - permissions_name: self.server.permissions.filepath, - "README.md": Path("README.md"), - } - return files - - def read_allowed_file(self, name: str) -> str: - path = self.allowed_files().get(name) - if path is None: - raise ValueError("该文件不允许通过 Web 编辑") - if not path.exists(): - return "" - return path.read_text(encoding="utf-8") - - def write_allowed_file(self, name: str, content: str): - path = self.allowed_files().get(name) - if path is None: - raise ValueError("该文件不允许通过 Web 编辑") - path.write_text(content, encoding="utf-8") - if path.resolve() == self.server.permissions.filepath.resolve(): - self.server.permissions.load() - - def properties_payload(self) -> dict: - return { - "properties": { - key: self._property_to_string(value) - for key, value in self.server.config.items() - } - } - - def write_properties(self, properties: dict) -> dict: - from config import save_config - - for key, raw_value in properties.items(): - if not isinstance(key, str): - continue - current = self.server.config.get(key) - self.server.config[key] = self._coerce_property_value(raw_value, current) - - self._apply_runtime_properties() - save_config(self.server.config, self.server.config_path) - return { - "message": "server.properties 已保存", - "properties": self.properties_payload()["properties"], - } - - def read_log_tail(self, line_count: int = 240) -> str: - path = Path("pymc.log") - if not path.exists(): - return "" - try: - text = path.read_text(encoding="utf-8", errors="replace") - except TypeError: - text = path.read_text(encoding="utf-8") - return "\n".join(text.splitlines()[-line_count:]) - - @staticmethod - def _property_to_string(value) -> str: - if isinstance(value, bool): - return "true" if value else "false" - return str(value) - - @staticmethod - def _coerce_property_value(value, current): - text = str(value) - if isinstance(current, bool): - return text.lower() in {"true", "1", "yes", "on"} - if isinstance(current, int) and not isinstance(current, bool): - try: - return int(text) - except ValueError: - return current - return text - - def _apply_runtime_properties(self): - config = self.server.config - self.server.motd = config.get("motd", self.server.motd) - self.server.max_players = int(config.get("max-players", self.server.max_players)) - self.server.online_mode = bool(config.get("online-mode", self.server.online_mode)) - self.server.compression_threshold = int( - config.get("network-compression-threshold", self.server.compression_threshold) - ) - self.server.view_distance = int(config.get("view-distance", self.server.view_distance)) - self.server.join_immediate_radius = max( - 0, int(config.get("join-immediate-radius", self.server.join_immediate_radius)) - ) - self.server.spawn_position = ( - int(config.get("level-spawn-x", self.server.spawn_position[0])), - int(config.get("level-spawn-y", self.server.spawn_position[1])), - int(config.get("level-spawn-z", self.server.spawn_position[2])), - ) - - def _status_payload(self) -> dict: - from handlers.play import ALL_VANILLA_COMMAND_NAMES - return { - "running": self.server.running, - "address": f"{self.server.host}:{self.server.port}", - "web_admin": f"http://{self.host}:{self.port}", - "max_players": self.server.max_players, - "view_distance": self.server.view_distance, - "autosave_enabled": self.server.autosave_enabled, - "terrain_engine": "native" if getattr(self.server, "_use_native_terrain", False) else "python", - "gamerules": dict(getattr(self.server, "gamerules", {})), - "entities": self.server.entity_manager.count_by_kind(), - "players": [ - { - "username": p.username, - "address": p.address, - "x": p.x, - "y": p.y, - "z": p.z, - "gamemode": p.gamemode, - "health": p.health, - "food": p.food, - "group": self.server.permissions.get_permission_level(p.username), - } - for p in self.server.get_online_players() - ], - "time": self.server.world_time, - "weather": self.server.weather, - "spawn_position": self.server.spawn_position, - "allowed_files": list(self.allowed_files().keys()), - "commands": ALL_VANILLA_COMMAND_NAMES, - } diff --git a/build.bat b/build.bat index 39b4c6b..ba29689 100755 --- a/build.bat +++ b/build.bat @@ -23,7 +23,7 @@ for %%P in (py python python3) do ( ) ) -echo [错误] 未找到 Python,请先安装 Python 3.10 或更高版本。 +echo [错误] 未找到 Python,请先安装 Python 3.14 或更高版本。 pause exit /b 1 diff --git a/build.sh b/build.sh index 98372ba..b204389 100755 --- a/build.sh +++ b/build.sh @@ -60,21 +60,6 @@ if [ $? -ne 0 ]; then exit 1 fi -echo "[信息] 正在编译 C++ 加速层 (共享内存 IPC + 红石引擎 + 光照引擎 + 物理引擎)..." -if command -v cmake &> /dev/null; then - cd build - cmake .. -DCMAKE_BUILD_TYPE=Release - make -j$(nproc 2>/dev/null || echo 2) - cd .. - # Copy built artifacts - cp -f build/pymc_native_server native/ 2>/dev/null || true - cp -f build/libpymc_native.so native/ 2>/dev/null || true - echo "[信息] C++ 加速层编译完成" -else - echo "[警告] 未找到 cmake,跳过 C++ 加速层编译" - echo "[警告] 将使用 Python 回退模式" -fi - echo "[信息] 开始编译 PyMC 服务端..." echo "" @@ -92,8 +77,6 @@ python3 -m nuitka \ --include-data-files=native/terrain_gen=terrain_gen \ --include-data-files=native/mob_ai=mob_ai \ --include-data-files=native/$VANILLA_LIB=native/$VANILLA_LIB \ - --include-data-files=native/pymc_native_server=pymc_native_server \ - --include-data-files=native/libpymc_native.so=libpymc_native.so \ --include-data-files=world/blocks.json=world/blocks.json \ --include-data-dir=protocol/data=protocol/data \ --include-data-dir=world/data=world/data \ diff --git a/commands/__init__.py b/commands/__init__.py index 6f208a8..60a99a3 100755 --- a/commands/__init__.py +++ b/commands/__init__.py @@ -96,10 +96,6 @@ def get_command(self, name: str) -> Command | None: return self.commands.get(global_resolved) return None - def get_all_commands(self) -> list[Command]: - """Return all registered commands.""" - return list(self.commands.values()) - def get_commands_for_sender(self, sender) -> list[Command]: """Return commands the sender has permission to use.""" result = [] @@ -114,16 +110,6 @@ def get_commands_for_sender(self, sender) -> list[Command]: result.append(cmd) return result - def get_commands_by_category(self) -> dict[str, list[Command]]: - """Return commands grouped by category.""" - categories: dict[str, list[Command]] = {} - for cmd in self.commands.values(): - cat = getattr(cmd, 'category', 'general') - if cat not in categories: - categories[cat] = [] - categories[cat].append(cmd) - return categories - async def execute(self, sender, command_string: str) -> int: """ Parse and execute a command string. diff --git a/commands/arguments.py b/commands/arguments.py index 4640e27..9197f39 100755 --- a/commands/arguments.py +++ b/commands/arguments.py @@ -11,7 +11,6 @@ import logging import math import re -from typing import Any logger = logging.getLogger("PyMC.参数") @@ -75,15 +74,6 @@ def parse_time_value(raw: str) -> int: GAMEMODE_NAMES = {0: "survival", 1: "creative", 2: "adventure", 3: "spectator"} -def parse_gamemode(raw: str) -> tuple[int, str]: - """Parse a gamemode string. Returns (mode_int, mode_name).""" - raw = raw.strip().lower() - if raw not in GAMEMODE_MAP: - raise ValueError(f"Invalid gamemode: {raw}. Expected: survival, creative, adventure, spectator") - mode = GAMEMODE_MAP[raw] - return (mode, GAMEMODE_NAMES[mode]) - - # --- Difficulty argument --- DIFFICULTY_MAP = { @@ -94,43 +84,8 @@ def parse_gamemode(raw: str) -> tuple[int, str]: } -def parse_difficulty(raw: str) -> tuple[int, str]: - """Parse a difficulty string. Returns (difficulty_int, difficulty_name).""" - raw = raw.strip().lower() - if raw not in DIFFICULTY_MAP: - raise ValueError(f"Invalid difficulty: {raw}. Expected: peaceful, easy, normal, hard") - diff = DIFFICULTY_MAP[raw] - names = {0: "peaceful", 1: "easy", 2: "normal", 3: "hard"} - return (diff, names[diff]) - - # --- Block state string parsing --- -def parse_block_state_string(raw: str) -> tuple[str, dict[str, str]]: - """ - Parse a block state string like 'minecraft:stone[half=top,waterlogged=true]'. - - Returns: - (block_name, properties_dict) - """ - raw = raw.strip() - if ":" not in raw: - raw = f"minecraft:{raw}" - - # Check for properties in brackets - if "[" in raw: - base = raw[:raw.index("[")] - props_str = raw[raw.index("[") + 1:raw.rindex("]")] - properties = {} - if props_str.strip(): - for pair in props_str.split(","): - if "=" in pair: - k, v = pair.split("=", 1) - properties[k.strip()] = v.strip() - return (base, properties) - return (raw, {}) - - # --- Coordinate parsing with relative support --- def parse_coordinate(raw: str) -> tuple[float, bool]: @@ -190,33 +145,6 @@ def parse_int_coordinates(tokens: list[str], start: int, base_x: float = 0.0, ba # --- Item stack parsing --- -def parse_item_stack(raw: str) -> dict: - """ - Parse an item stack string like 'minecraft:diamond_sword{count:1}'. - - Returns: - dict with 'item' and 'count' keys - """ - raw = raw.strip() - if ":" not in raw: - raw = f"minecraft:{raw}" - - count = 1 - item_name = raw - - # Check for NBT-like count specification - if "{" in raw: - item_name = raw[:raw.index("{")] - nbt_str = raw[raw.index("{") + 1:raw.rindex("}")] - try: - nbt = json.loads("{" + nbt_str + "}") - count = nbt.get("count", 1) - except json.JSONDecodeError: - pass - - return {"item": item_name, "count": count} - - # --- Effect parsing --- EFFECT_NAMES = { @@ -278,14 +206,6 @@ def parse_enchantment_name(raw: str) -> str: WEATHER_TYPES = {"clear", "rain", "thunder"} -def parse_weather(raw: str) -> str: - """Parse a weather type.""" - raw = raw.strip().lower() - if raw not in WEATHER_TYPES: - raise ValueError(f"Invalid weather: {raw}. Expected: clear, rain, thunder") - return raw - - # --- Text component parsing --- def parse_text_component(raw: str) -> dict: @@ -473,13 +393,6 @@ def parse_locate_target(raw: str) -> tuple[str, str]: FILL_MODES = {"replace", "destroy", "keep", "hollow", "outline"} -def parse_mask_mode(raw: str) -> str: - raw = raw.strip().lower() - if raw not in MASK_MODES: - raise ValueError(f"Invalid mask mode: {raw}") - return raw - - def parse_clone_mode(raw: str) -> str: raw = raw.strip().lower() if raw not in CLONE_MODES: @@ -503,79 +416,14 @@ def parse_fill_mode(raw: str) -> str: } -def parse_color(raw: str) -> str: - """Parse a Minecraft color name.""" - raw = raw.strip().lower() - if raw.startswith("minecraft:"): - raw = raw[10:] - if raw not in VALID_COLORS: - raise ValueError(f"Invalid color: {raw}. Expected one of: {', '.join(sorted(VALID_COLORS))}") - return raw - - # --- Identifier parsing --- -def parse_identifier(raw: str, default_namespace: str = "minecraft") -> str: - """Parse a namespaced identifier. Adds default namespace if missing.""" - raw = raw.strip() - if ":" not in raw: - return f"{default_namespace}:{raw}" - return raw - - # --- Angle parsing --- -def parse_angle(raw: str) -> tuple[float, bool]: - """Parse an angle with optional relative (~) notation. - - Returns: - (value, is_relative) - """ - raw = raw.strip() - if raw.startswith("~"): - offset = float(raw[1:]) if len(raw) > 1 else 0.0 - return (offset, True) - return (float(raw), False) - - -def resolve_angle(parsed: tuple[float, bool], base: float = 0.0) -> float: - """Resolve a parsed angle to an absolute value.""" - value, is_relative = parsed - if is_relative: - return base + value - return value - - # --- Rotation parsing --- -def parse_rotation(tokens: list[str], start: int, base_yaw: float = 0.0, base_pitch: float = 0.0) -> tuple[float, float] | None: - """Parse yaw and pitch rotation from tokens. - - Returns: - (yaw, pitch) absolute values, or None on failure - """ - if start + 1 >= len(tokens): - return None - try: - yaw_parsed = parse_angle(tokens[start]) - pitch_parsed = parse_angle(tokens[start + 1]) - yaw = resolve_angle(yaw_parsed, base_yaw) - pitch = resolve_angle(pitch_parsed, base_pitch) - return (yaw, pitch) - except (ValueError, IndexError): - return None - - # --- Score holder parsing --- -def parse_score_holder(raw: str) -> str: - """Parse a score holder (player name or * for all).""" - raw = raw.strip() - if raw == "*": - return "*" - return raw - - # --- Entity type parsing --- MOB_TYPES = { @@ -593,14 +441,6 @@ def parse_score_holder(raw: str) -> str: } -def parse_entity_type(raw: str) -> str: - """Parse and normalize an entity type identifier.""" - raw = raw.strip().lower().replace(" ", "_") - if ":" in raw: - return raw - return f"minecraft:{raw}" - - # --- Attribute parsing --- ATTRIBUTE_NAMES = { @@ -618,16 +458,6 @@ def parse_entity_type(raw: str) -> str: } -def parse_attribute_name(raw: str) -> str: - """Parse and normalize an attribute name.""" - raw = raw.strip().lower().replace(" ", "_") - if not raw.startswith("generic.") and not raw.startswith("minecraft:"): - raw = f"generic.{raw}" - if ":" not in raw: - raw = f"minecraft:{raw}" - return raw - - # --- Bossbar parsing --- BOSSBAR_COLORS = {"pink", "blue", "red", "green", "yellow", "purple", "white"} @@ -636,213 +466,77 @@ def parse_attribute_name(raw: str) -> str: } -def parse_bossbar_color(raw: str) -> str: - """Parse a bossbar color.""" - raw = raw.strip().lower() - if raw not in BOSSBAR_COLORS: - raise ValueError(f"Invalid bossbar color: {raw}. Expected: {', '.join(BOSSBAR_COLORS)}") - return raw - - -def parse_bossbar_style(raw: str) -> str: - """Parse a bossbar style (overlay).""" - raw = raw.strip().lower() - if raw not in BOSSBAR_STYLES: - raise ValueError(f"Invalid bossbar style: {raw}. Expected: {', '.join(BOSSBAR_STYLES)}") - return raw - - # --- Datapack parsing --- DATAPACK_ACTIONS = {"enable", "disable", "list"} -def parse_datapack_action(raw: str) -> str: - """Parse a datapack action.""" - raw = raw.strip().lower() - if raw not in DATAPACK_ACTIONS: - raise ValueError(f"Invalid datapack action: {raw}. Expected: {', '.join(DATAPACK_ACTIONS)}") - return raw - - # --- Forceload parsing --- FORCELOAD_ACTIONS = {"add", "remove", "query"} -def parse_forceload_action(raw: str) -> str: - """Parse a forceload action.""" - raw = raw.strip().lower() - if raw not in FORCELOAD_ACTIONS: - raise ValueError(f"Invalid forceload action: {raw}. Expected: {', '.join(FORCELOAD_ACTIONS)}") - return raw - - # --- Trigger parsing --- TRIGGER_ACTIONS = {"enable", "set", "add"} -def parse_trigger_action(raw: str) -> str: - """Parse a trigger action.""" - raw = raw.strip().lower() - if raw not in TRIGGER_ACTIONS: - raise ValueError(f"Invalid trigger action: {raw}") - return raw - - # --- Ride parsing --- RIDE_ACTIONS = {"mount", "dismount"} -def parse_ride_action(raw: str) -> str: - """Parse a ride action.""" - raw = raw.strip().lower() - if raw not in RIDE_ACTIONS: - raise ValueError(f"Invalid ride action: {raw}. Expected: mount, dismount") - return raw - - # --- Item command actions --- ITEM_ACTIONS = {"replace", "modify"} -def parse_item_action(raw: str) -> str: - """Parse an item command action.""" - raw = raw.strip().lower() - if raw not in ITEM_ACTIONS: - raise ValueError(f"Invalid item action: {raw}. Expected: {', '.join(ITEM_ACTIONS)}") - return raw - - # --- Recipe parsing --- RECIPE_ACTIONS = {"give", "take"} -def parse_recipe_action(raw: str) -> str: - """Parse a recipe action.""" - raw = raw.strip().lower() - if raw not in RECIPE_ACTIONS: - raise ValueError(f"Invalid recipe action: {raw}. Expected: give, take") - return raw - - # --- Advancement parsing --- ADVANCEMENT_ACTIONS = {"grant", "revoke"} -def parse_advancement_action(raw: str) -> str: - """Parse an advancement action.""" - raw = raw.strip().lower() - if raw not in ADVANCEMENT_ACTIONS: - raise ValueError(f"Invalid advancement action: {raw}. Expected: grant, revoke") - return raw - - # --- Schedule parsing --- SCHEDULE_ACTIONS = {"function", "clear"} -def parse_schedule_action(raw: str) -> str: - """Parse a schedule action.""" - raw = raw.strip().lower() - if raw not in SCHEDULE_ACTIONS: - raise ValueError(f"Invalid schedule action: {raw}. Expected: function, clear") - return raw - - # --- Place parsing --- PLACE_TYPES = {"structure", "jigsaw", "template"} -def parse_place_type(raw: str) -> str: - """Parse a place type.""" - raw = raw.strip().lower() - if raw not in PLACE_TYPES: - raise ValueError(f"Invalid place type: {raw}. Expected: {', '.join(PLACE_TYPES)}") - return raw - - # --- Worldborder parsing --- WORLDBORDER_ACTIONS = {"add", "set", "center", "damage", "get", "set", "warning", "shrink"} -def parse_worldborder_action(raw: str) -> str: - """Parse a worldborder action.""" - raw = raw.strip().lower() - if raw not in WORLDBORDER_ACTIONS: - raise ValueError(f"Invalid worldborder action: {raw}") - return raw - - # --- Data command parsing --- DATA_TARGETS = {"block", "entity", "storage"} DATA_ACTIONS = {"get", "merge", "modify", "remove"} -def parse_data_target(raw: str) -> str: - """Parse a data command target.""" - raw = raw.strip().lower() - if raw not in DATA_TARGETS: - raise ValueError(f"Invalid data target: {raw}. Expected: {', '.join(DATA_TARGETS)}") - return raw - - -def parse_data_action(raw: str) -> str: - """Parse a data command action.""" - raw = raw.strip().lower() - if raw not in DATA_ACTIONS: - raise ValueError(f"Invalid data action: {raw}. Expected: {', '.join(DATA_ACTIONS)}") - return raw - - # --- Title command parsing --- TITLE_ACTIONS = {"title", "subtitle", "actionbar", "times", "clear", "reset"} -def parse_title_action(raw: str) -> str: - """Parse a title command action.""" - raw = raw.strip().lower() - if raw not in TITLE_ACTIONS: - raise ValueError(f"Invalid title action: {raw}. Expected: {', '.join(TITLE_ACTIONS)}") - return raw - - # --- Tag command parsing --- TAG_ACTIONS = {"add", "remove", "list"} -def parse_tag_action(raw: str) -> str: - """Parse a tag command action.""" - raw = raw.strip().lower() - if raw not in TAG_ACTIONS: - raise ValueError(f"Invalid tag action: {raw}. Expected: {', '.join(TAG_ACTIONS)}") - return raw - - # --- Team command parsing --- TEAM_ACTIONS = {"add", "remove", "join", "leave", "list", "modify", "empty"} -def parse_team_action(raw: str) -> str: - """Parse a team command action.""" - raw = raw.strip().lower() - if raw not in TEAM_ACTIONS: - raise ValueError(f"Invalid team action: {raw}. Expected: {', '.join(TEAM_ACTIONS)}") - return raw - - # --- Gamerule parsing --- GAMERULE_NAMES = { @@ -875,9 +569,3 @@ def parse_team_action(raw: str) -> str: } -def parse_gamerule_name(raw: str) -> str: - """Parse a gamerule name.""" - raw = raw.strip().lower().replace(" ", "") - if raw not in GAMERULE_NAMES: - raise ValueError(f"Unknown gamerule: {raw}") - return raw diff --git a/commands/framework.py b/commands/framework.py index 5fe0348..f30a0e9 100755 --- a/commands/framework.py +++ b/commands/framework.py @@ -21,7 +21,7 @@ import contextvars import logging import math -from dataclasses import dataclass, field +from dataclasses import dataclass from typing import Any, Callable, Awaitable logger = logging.getLogger("PyMC.命令") @@ -115,17 +115,6 @@ def remaining_input(self) -> str: # ---- Sender helpers ---- - @property - def is_console(self) -> bool: - """True if the command was issued from the console.""" - return self.sender is None - - @property - def is_player(self) -> bool: - """True if the command was issued by an in-game player.""" - from network.connection import Connection - return isinstance(self.sender, Connection) - def get_sender_position(self) -> tuple[float, float, float]: """Get the sender's position, defaulting to world spawn.""" if self.sender and hasattr(self.sender, 'x'): @@ -133,12 +122,6 @@ def get_sender_position(self) -> tuple[float, float, float]: spawn = getattr(self.server, 'spawn_position', (0, 100, 0)) return (float(spawn[0]), float(spawn[1]), float(spawn[2])) - def get_sender_rotation(self) -> tuple[float, float]: - """Get the sender's rotation (yaw, pitch).""" - if self.sender and hasattr(self.sender, 'yaw'): - return (self.sender.yaw, self.sender.pitch) - return (0.0, 0.0) - # ---- Messaging ---- async def reply(self, text): @@ -276,32 +259,6 @@ def arg(self, name: str, default: Any = None) -> Any: """Get a named argument value, with optional default.""" return self.arguments.get(name, default) - def arg_int(self, name: str, default: int = 0) -> int: - """Get a named argument as int.""" - val = self.arguments.get(name, default) - try: - return int(val) - except (ValueError, TypeError): - return default - - def arg_float(self, name: str, default: float = 0.0) -> float: - """Get a named argument as float.""" - val = self.arguments.get(name, default) - try: - return float(val) - except (ValueError, TypeError): - return default - - def arg_str(self, name: str, default: str = "") -> str: - """Get a named argument as string.""" - val = self.arguments.get(name, default) - return str(val) if val is not None else default - - def greedy_string(self) -> str: - """Get the remaining greedy string argument (everything after the command name).""" - return self.arguments.get("_raw_remaining", "") or self.remaining_input - - class Command: """ Represents a registered command with metadata and execution handler. @@ -394,88 +351,13 @@ def parse(self, raw: str) -> str: return raw -class IntArg(ArgumentType): - """An integer argument with optional range constraints.""" - - def __init__(self, name: str, required: bool = True, min_val: int | None = None, max_val: int | None = None): - super().__init__(name, required) - self.min_val = min_val - self.max_val = max_val - - def parse(self, raw: str) -> int: - value = int(raw) - if self.min_val is not None and value < self.min_val: - raise ValueError(f"{self.name} must be >= {self.min_val}") - if self.max_val is not None and value > self.max_val: - raise ValueError(f"{self.name} must be <= {self.max_val}") - return value - - -class FloatArg(ArgumentType): - """A float argument with optional range constraints.""" - - def __init__(self, name: str, required: bool = True, min_val: float | None = None, max_val: float | None = None): - super().__init__(name, required) - self.min_val = min_val - self.max_val = max_val - - def parse(self, raw: str) -> float: - value = float(raw) - if self.min_val is not None and value < self.min_val: - raise ValueError(f"{self.name} must be >= {self.min_val}") - if self.max_val is not None and value > self.max_val: - raise ValueError(f"{self.name} must be <= {self.max_val}") - return value - - -class BoolArg(ArgumentType): - """A boolean argument (true/false).""" - - def parse(self, raw: str) -> bool: - if raw.lower() in ("true", "1", "yes"): - return True - if raw.lower() in ("false", "0", "no"): - return False - raise ValueError(f"Invalid boolean: {raw}") - - def suggest(self, partial: str, context: CommandContext) -> list[str]: - return ["true", "false"] - - -class EnumArg(ArgumentType): - """An enum argument from a set of allowed values.""" - - def __init__(self, name: str, values: list[str], required: bool = True, case_insensitive: bool = True): - super().__init__(name, required) - self.values = values - self.case_insensitive = case_insensitive - - def parse(self, raw: str) -> str: - check = raw.lower() if self.case_insensitive else raw - for v in self.values: - v_check = v.lower() if self.case_insensitive else v - if v_check == check: - return v - raise ValueError(f"Invalid value '{raw}', expected one of: {', '.join(self.values)}") - - def suggest(self, partial: str, context: CommandContext) -> list[str]: - if self.case_insensitive: - return [v for v in self.values if v.lower().startswith(partial.lower())] - return [v for v in self.values if v.startswith(partial)] - - -class PlayerArg(ArgumentType): - """A player name or selector argument.""" - - def parse(self, raw: str) -> str: - return raw - - def suggest(self, partial: str, context: CommandContext) -> list[str]: - players = context.server.get_online_players() - names = [p.username for p in players] - if partial.startswith("@"): - return ["@a", "@p", "@e", "@s", "@r"] - return [n for n in names if n.lower().startswith(partial.lower())] +def _parse_coord_component(raw: str, caret: bool = False) -> tuple[float, bool]: + """Parse one coordinate: ``~offset`` (and ``^offset`` when caret is allowed) is relative.""" + raw = raw.strip() + if raw.startswith("~") or (caret and raw.startswith("^")): + offset = float(raw[1:]) if len(raw) > 1 else 0.0 + return (offset, True) + return (float(raw), False) class BlockPosArg(ArgumentType): @@ -489,22 +371,7 @@ def __init__(self, name: str = "pos", required: bool = True): def parse(self, raw: str) -> tuple: """Parse a single coordinate component. Returns (value, is_relative).""" - raw = raw.strip() - if raw.startswith("~"): - offset = float(raw[1:]) if len(raw) > 1 else 0.0 - return (offset, True) - if raw.startswith("^"): - offset = float(raw[1:]) if len(raw) > 1 else 0.0 - return (offset, True) - return (float(raw), False) - - @staticmethod - def resolve_relative(coords: list[tuple], base_x: float, base_y: float, base_z: float) -> tuple[float, float, float]: - """Resolve relative coordinates to absolute positions.""" - x = base_x + coords[0][0] if coords[0][1] else coords[0][0] - y = base_y + coords[1][0] if coords[1][1] else coords[1][0] - z = base_z + coords[2][0] if coords[2][1] else coords[2][0] - return (x, y, z) + return _parse_coord_component(raw, caret=True) class ColumnPosArg(ArgumentType): @@ -517,163 +384,7 @@ def __init__(self, name: str = "column_pos", required: bool = True): super().__init__(name, required) def parse(self, raw: str) -> tuple: - raw = raw.strip() - if raw.startswith("~"): - offset = float(raw[1:]) if len(raw) > 1 else 0.0 - return (offset, True) - return (float(raw), False) - - -class SelectorArg(ArgumentType): - """An entity selector argument (@a, @p, @e, @s, @r with optional args).""" - - def parse(self, raw: str) -> str: - # Validate but return the raw string; resolution happens at execution time - return raw - - def suggest(self, partial: str, context: CommandContext) -> list[str]: - if partial.startswith("@"): - return ["@a", "@p", "@e", "@s", "@r"] - players = context.server.get_online_players() - names = [p.username for p in players] - return [n for n in names if n.lower().startswith(partial.lower())] - - -class ItemArg(ArgumentType): - """An item identifier argument (minecraft:stone).""" - - def parse(self, raw: str) -> str: - if ":" not in raw: - return f"minecraft:{raw}" - return raw - - -class BlockStateArg(ArgumentType): - """A block state identifier argument with optional properties. - - Supports: minecraft:stone, stone[half=top], minecraft:stone[half=top,waterlogged=true] - """ - - def __init__(self, name: str = "block_state", required: bool = True): - super().__init__(name, required) - - def parse(self, raw: str) -> str: - if ":" not in raw.split("[")[0]: - # Add namespace before any bracket - if "[" in raw: - base = raw[:raw.index("[")] - rest = raw[raw.index("["):] - return f"minecraft:{base}{rest}" - return f"minecraft:{raw}" - return raw - - -class ItemStackArg(ArgumentType): - """An item stack argument with optional count and NBT. - - Supports: minecraft:diamond_sword, diamond_sword{count:5} - """ - - def __init__(self, name: str = "item_stack", required: bool = True): - super().__init__(name, required) - - def parse(self, raw: str) -> dict: - from commands.arguments import parse_item_stack - return parse_item_stack(raw) - - -class JsonArg(ArgumentType): - """A JSON text component argument (greedy).""" - - def __init__(self, name: str = "json", required: bool = True): - super().__init__(name, required) - - def parse(self, raw: str) -> Any: - import json - try: - return json.loads(raw) - except json.JSONDecodeError: - # May be plain text - return {"text": raw} - - -class CoordinateArg(ArgumentType): - """A single coordinate component with relative (~) support.""" - - def parse(self, raw: str) -> tuple[float, bool]: - raw = raw.strip() - if raw.startswith("^"): - offset = float(raw[1:]) if len(raw) > 1 else 0.0 - return (offset, True) - if raw.startswith("~"): - offset = float(raw[1:]) if len(raw) > 1 else 0.0 - return (offset, True) - return (float(raw), False) - - -class TimeArg(ArgumentType): - """A time argument with unit support (10s, 5m, 1d, 0t).""" - - def __init__(self, name: str = "time", required: bool = True, min_val: int = 0): - super().__init__(name, required) - self.min_val = min_val - - def parse(self, raw: str) -> int: - from commands.arguments import parse_time_value - value = parse_time_value(raw) - if value < self.min_val: - raise ValueError(f"{self.name} must be >= {self.min_val}") - return value - - def suggest(self, partial: str, context: CommandContext) -> list[str]: - from commands.arguments import TIME_PRESETS - return [k for k in TIME_PRESETS if k.startswith(partial.lower())] - - -class ColorArg(ArgumentType): - """A color argument for Minecraft formatting codes.""" - - VALID_COLORS = { - "black", "dark_blue", "dark_green", "dark_aqua", "dark_red", - "dark_purple", "gold", "gray", "dark_gray", "blue", "green", - "aqua", "red", "light_purple", "yellow", "white", - } - - def parse(self, raw: str) -> str: - raw = raw.strip().lower() - if raw.startswith("minecraft:"): - raw = raw[10:] - if raw not in self.VALID_COLORS: - raise ValueError(f"Invalid color: {raw}. Expected one of: {', '.join(sorted(self.VALID_COLORS))}") - return raw - - def suggest(self, partial: str, context: CommandContext) -> list[str]: - return [c for c in sorted(self.VALID_COLORS) if c.startswith(partial.lower())] - - -class IdentifierArg(ArgumentType): - """A namespaced identifier argument (minecraft:stone).""" - - def __init__(self, name: str = "identifier", required: bool = True, namespace: str = "minecraft"): - super().__init__(name, required) - self.default_namespace = namespace - - def parse(self, raw: str) -> str: - raw = raw.strip() - if ":" not in raw: - return f"{self.default_namespace}:{raw}" - return raw - - -class AngleArg(ArgumentType): - """A rotation angle argument with relative (~) support.""" - - def parse(self, raw: str) -> tuple[float, bool]: - raw = raw.strip() - if raw.startswith("~"): - offset = float(raw[1:]) if len(raw) > 1 else 0.0 - return (offset, True) - return (float(raw), False) + return _parse_coord_component(raw) class RotationArg(ArgumentType): @@ -683,51 +394,14 @@ def __init__(self, name: str = "rotation", required: bool = True): super().__init__(name, required) def parse_yaw(self, raw: str) -> tuple[float, bool]: - raw = raw.strip() - if raw.startswith("~"): - offset = float(raw[1:]) if len(raw) > 1 else 0.0 - return (offset, True) - return (float(raw), False) + return _parse_coord_component(raw) def parse_pitch(self, raw: str) -> tuple[float, bool]: return self.parse_yaw(raw) -class ScoreHolderArg(ArgumentType): - """A score holder argument (player name or selector).""" - - def parse(self, raw: str) -> str: - return raw - - def suggest(self, partial: str, context: CommandContext) -> list[str]: - if partial.startswith("@"): - return ["@a", "@p", "@e", "@s", "@r"] - players = context.server.get_online_players() - names = [p.username for p in players] - return [n for n in names if n.lower().startswith(partial.lower())] - - -class ComponentArg(ArgumentType): - """A JSON text component argument (same as JsonArg but with better name).""" - - def __init__(self, name: str = "component", required: bool = True): - super().__init__(name, required) - - def parse(self, raw: str) -> Any: - import json - try: - return json.loads(raw) - except json.JSONDecodeError: - return {"text": raw} - - # --- Utility --- -async def _noop(): - """No-op coroutine for console reply.""" - pass - - def tokenize_command(command_string: str) -> list[str]: """ Tokenize a command string, respecting quoted strings and brackets. diff --git a/commands/selector.py b/commands/selector.py index 87039d1..8ddd30b 100755 --- a/commands/selector.py +++ b/commands/selector.py @@ -24,7 +24,6 @@ import re import logging from dataclasses import dataclass, field -from typing import Any logger = logging.getLogger("PyMC.选择器") @@ -283,7 +282,6 @@ def resolve_selector( candidates = list(server.get_online_players()) elif selector_type == "@e": # All entities (including players) - from world.entities import Entity candidates = list(server.entity_manager.list_entities()) candidates.extend(server.get_online_players()) elif selector_type == "@s": @@ -321,48 +319,6 @@ def resolve_selector( return filtered -def resolve_targets( - server, - sender, - selector_str: str, - *, - allow_players: bool = True, - allow_entities: bool = True, - must_exist: bool = True, -) -> list: - """ - High-level target resolution for commands. - - Like resolve_selector but with additional flexibility: - - If selector_str is a player name, resolves to that player - - If allow_players is False, filters out Connection objects - - If allow_entities is False, filters out non-Connection objects - - If must_exist is True and no targets found, returns empty list - - Args: - server: MinecraftServer - sender: Connection or None (console) - selector_str: Selector string or player name - allow_players: Whether to include player targets - allow_entities: Whether to include non-player entity targets - must_exist: If True, return empty list when no match found - - Returns: - List of matching targets - """ - targets = resolve_selector(server, sender, selector_str) - - # Filter by type - if not allow_players: - from network.connection import Connection - targets = [t for t in targets if not isinstance(t, Connection)] - if not allow_entities: - from network.connection import Connection - targets = [t for t in targets if isinstance(t, Connection)] - - return targets - - def resolve_one_target( server, sender, @@ -388,11 +344,6 @@ def resolve_one_target( return None -def is_selector(raw: str) -> bool: - """Check if a string is a vanilla selector (starts with @).""" - return bool(re.match(r'^@[apers](\[.*\])?$', raw.strip())) - - def _distance_squared(entity, x: float, y: float, z: float) -> float: """Calculate squared distance from an entity to a position.""" ex = entity.x if hasattr(entity, 'x') else 0.0 diff --git a/commands/vanilla/__init__.py b/commands/vanilla/__init__.py index 59ff095..bc47add 100755 --- a/commands/vanilla/__init__.py +++ b/commands/vanilla/__init__.py @@ -22,17 +22,14 @@ from commands.framework import Command, CommandContext, SUCCESS, FAILURE # --- Consolidated command module imports --- -from commands.vanilla.core import register as register_core from commands.vanilla.player import register as register_player from commands.vanilla.world import register as register_world from commands.vanilla.entity import register as register_entity -from commands.vanilla.server import register as register_server from commands.vanilla.execute_cmd import register as register_execute_cmd from commands.vanilla.display import register as register_display from commands.vanilla.world_mgmt import register as register_world_mgmt # --- Additional standalone command modules --- -from commands.vanilla.gamerule import register as register_gamerule from commands.vanilla.particle import register as register_particle from commands.vanilla.playsound import register as register_playsound from commands.vanilla.data import register as register_data @@ -51,7 +48,6 @@ def register_all(manager): # ===== Core commands ===== # help, list, stop, reload, save-all, save-on, save-off, save-status - register_core(manager) # ===== Player commands ===== # tp, gamemode, give, clear, kill, xp, effect, enchant, damage @@ -69,7 +65,6 @@ def register_all(manager): # ===== Server administration commands ===== # kick, ban, ban-ip, pardon, pardon-ip, banlist, op, deop, # whitelist, say, me, msg - register_server(manager) # ===== Execute command ===== # execute (with chained subcommands: as, at, positioned, rotated, align, @@ -87,7 +82,6 @@ def register_all(manager): # ===== Additional commands ===== # gamerule, particle, playsound, data, item - register_gamerule(manager) register_particle(manager) register_playsound(manager) register_data(manager) diff --git a/commands/vanilla/advancement.py b/commands/vanilla/advancement.py deleted file mode 100755 index 17a633b..0000000 --- a/commands/vanilla/advancement.py +++ /dev/null @@ -1,82 +0,0 @@ -# ============================================================ -# PyMC - /advancement Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector -from network.connection import Connection - - -# Simple advancement tracking -_advancements: dict[str, dict] = {} -_player_advancements: dict[str, dict[str, bool]] = {} # username -> {adv_name -> done} - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if len(args) < 3: - await ctx.reply("[PyMC] 用法: advancement <目标> [进度名]") - return FAILURE - - action = args[0].lower() - if action not in ("grant", "revoke"): - await ctx.reply(f"[PyMC] 未知操作: {action}。可用: grant, revoke") - return FAILURE - - targets = resolve_selector(ctx.server, ctx.sender, args[1]) - players = [t for t in targets if isinstance(t, Connection)] - if not players: - await ctx.reply(f"[PyMC] 未找到目标: {args[1]}") - return FAILURE - - mode = args[2].lower() - - if mode == "everything": - count = 0 - for player in players: - if player.username not in _player_advancements: - _player_advancements[player.username] = {} - if action == "grant": - for adv_name in _advancements: - if not _player_advancements[player.username].get(adv_name): - _player_advancements[player.username][adv_name] = True - count += 1 - else: - count = len(_player_advancements[player.username]) - _player_advancements[player.username] = {} - action_cn = "授予" if action == "grant" else "撤销" - await ctx.reply(f"[PyMC] 已{action_cn} {len(players)} 个玩家的所有进度 ({count} 个)") - return SUCCESS - - if mode == "only": - if len(args) < 4: - await ctx.reply("[PyMC] 用法: advancement <目标> only <进度名>") - return FAILURE - adv_name = args[3] - count = 0 - for player in players: - if player.username not in _player_advancements: - _player_advancements[player.username] = {} - _player_advancements[player.username][adv_name] = (action == "grant") - count += 1 - action_cn = "授予" if action == "grant" else "撤销" - await ctx.reply(f"[PyMC] 已{action_cn} {len(players)} 个玩家进度: {adv_name}") - return SUCCESS - - # from, through, until - simplified - adv_name = args[3] if len(args) >= 4 else "unknown" - action_cn = "授予" if action == "grant" else "撤销" - await ctx.reply(f"[PyMC] 已{action_cn}进度: {adv_name} (from/through/until 模式暂简化处理)") - return SUCCESS - - cmd = Command( - name="advancement", - description="授予或撤销进度", - usage="advancement <目标> [进度名]", - permission="command.advancement", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/attribute.py b/commands/vanilla/attribute.py deleted file mode 100755 index c32b7dc..0000000 --- a/commands/vanilla/attribute.py +++ /dev/null @@ -1,155 +0,0 @@ -# ============================================================ -# PyMC - /attribute Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector - - -# Known attributes -ATTRIBUTES = { - "generic.max_health": {"default": 20.0, "min": 0.0, "max": 1024.0}, - "generic.knockback_resistance": {"default": 0.0, "min": 0.0, "max": 1.0}, - "generic.movement_speed": {"default": 0.7, "min": 0.0, "max": 1024.0}, - "generic.attack_damage": {"default": 2.0, "min": 0.0, "max": 2048.0}, - "generic.armor": {"default": 0.0, "min": 0.0, "max": 30.0}, - "generic.armor_toughness": {"default": 0.0, "min": 0.0, "max": 20.0}, - "generic.luck": {"default": 0.0, "min": -1024.0, "max": 1024.0}, - "generic.follow_range": {"default": 16.0, "min": 0.0, "max": 2048.0}, - "generic.attack_speed": {"default": 4.0, "min": 0.0, "max": 1024.0}, - "generic.flying_speed": {"default": 0.4, "min": 0.0, "max": 1024.0}, - "horse.jump_strength": {"default": 0.7, "min": 0.0, "max": 2.0}, - "zombie.spawn_reinforcements": {"default": 0.0, "min": 0.0, "max": 1.0}, -} - -# In-memory attribute modifiers -_attribute_modifiers: dict[int, dict[str, list[dict]]] = {} # entity_id -> {attribute -> [modifiers]} - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if len(args) < 2: - await ctx.reply("[PyMC] 用法: attribute <目标> <属性> ...") - return FAILURE - - targets = resolve_selector(ctx.server, ctx.sender, args[0]) - if not targets: - await ctx.reply(f"[PyMC] 未找到目标: {args[0]}") - return FAILURE - target = targets[0] - - attr_name = args[1].lower() - if ":" not in attr_name: - attr_name = f"minecraft:{attr_name}" - - if attr_name.replace("minecraft:", "") not in {a.replace("generic.", "") for a in ATTRIBUTES} and attr_name not in ATTRIBUTES: - # Allow custom attributes - pass - - if len(args) < 3: - await ctx.reply("[PyMC] 用法: attribute <目标> <属性> ...") - return FAILURE - - action = args[2].lower() - - if action == "get": - # Get base value - base_val = _get_attribute_base(target, attr_name) - scale = float(args[3]) if len(args) >= 4 else 1.0 - await ctx.reply(f"[PyMC] {attr_name} = {base_val * scale:.4f}") - return SUCCESS - - if action == "set": - if len(args) < 4: - await ctx.reply("[PyMC] 用法: attribute <目标> <属性> set <值>") - return FAILURE - try: - value = float(args[3]) - except ValueError: - await ctx.reply("[PyMC] 值格式无效") - return FAILURE - _set_attribute_base(target, attr_name, value) - await ctx.reply(f"[PyMC] 已设置 {attr_name} = {value}") - return SUCCESS - - if action == "base": - if len(args) < 4: - await ctx.reply("[PyMC] 用法: attribute <目标> <属性> base [值]") - return FAILURE - sub = args[3].lower() - if sub == "get": - base_val = _get_attribute_base(target, attr_name) - scale = float(args[4]) if len(args) >= 5 else 1.0 - await ctx.reply(f"[PyMC] {attr_name} 基础值 = {base_val * scale:.4f}") - elif sub == "set": - if len(args) < 5: - await ctx.reply("[PyMC] 用法: attribute <目标> <属性> base set <值>") - return FAILURE - try: - value = float(args[4]) - except ValueError: - await ctx.reply("[PyMC] 值格式无效") - return FAILURE - _set_attribute_base(target, attr_name, value) - await ctx.reply(f"[PyMC] 已设置 {attr_name} 基础值 = {value}") - return SUCCESS - - if action == "modifier": - await ctx.reply("[PyMC] attribute modifier 暂未完全实现") - return SUCCESS - - await ctx.reply(f"[PyMC] 未知操作: {action}") - return FAILURE - - cmd = Command( - name="attribute", - description="修改实体属性", - usage="attribute <目标> <属性> ...", - permission="command.attribute", - ) - cmd._execute_func = _execute - manager.register(cmd) - - -def _get_attribute_base(entity, attr_name: str) -> float: - """Get the base value of an attribute for an entity.""" - from network.connection import Connection - from world.entities import MobEntity - - attr_key = attr_name.replace("minecraft:", "") - info = ATTRIBUTES.get(attr_key, ATTRIBUTES.get(f"generic.{attr_key}")) - - if isinstance(entity, Connection): - if "max_health" in attr_key: - return entity.health - return info["default"] if info else 0.0 - elif isinstance(entity, MobEntity): - if "max_health" in attr_key: - return entity.max_health - if "follow_range" in attr_key: - return entity.profile.get("follow_range", 16.0) - if "attack_damage" in attr_key: - return entity.profile.get("attack_damage", 2.0) - if "movement_speed" in attr_key: - return entity.profile.get("speed", 0.05) - return info["default"] if info else 0.0 - return 0.0 - - -def _set_attribute_base(entity, attr_name: str, value: float): - """Set the base value of an attribute for an entity.""" - from network.connection import Connection - from world.entities import MobEntity - - attr_key = attr_name.replace("minecraft:", "") - - if isinstance(entity, Connection): - if "max_health" in attr_key: - entity.health = value - elif isinstance(entity, MobEntity): - if "max_health" in attr_key: - entity.max_health = value - entity.health = min(entity.health, value) diff --git a/commands/vanilla/bossbar.py b/commands/vanilla/bossbar.py deleted file mode 100755 index 5906bd5..0000000 --- a/commands/vanilla/bossbar.py +++ /dev/null @@ -1,139 +0,0 @@ -# ============================================================ -# PyMC - /bossbar Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE - - -# Boss bar storage -_boss_bars: dict[str, dict] = {} # id -> {players, name, color, style, value, max, visible} - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - # List boss bars - if not _boss_bars: - await ctx.reply("[PyMC] 没有自定义 Boss 栏") - else: - for bid, bar in _boss_bars.items(): - await ctx.reply(f"[PyMC] {bid}: {bar['name']} ({bar['value']}/{bar['max']})") - return SUCCESS - - action = args[0].lower() - - if action == "add": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: bossbar add <名称>") - return FAILURE - bar_id = args[1] - name = ' '.join(args[2:]) - if bar_id in _boss_bars: - await ctx.reply(f"[PyMC] Boss 栏 {bar_id} 已存在") - return FAILURE - _boss_bars[bar_id] = { - "name": name, - "color": "white", - "style": "progress", - "value": 0, - "max": 100, - "visible": True, - "players": [], - } - await ctx.reply(f"[PyMC] 已创建 Boss 栏: {bar_id}") - return SUCCESS - - if action == "remove": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: bossbar remove ") - return FAILURE - bar_id = args[1] - if bar_id not in _boss_bars: - await ctx.reply(f"[PyMC] Boss 栏 {bar_id} 不存在") - return FAILURE - del _boss_bars[bar_id] - await ctx.reply(f"[PyMC] 已移除 Boss 栏: {bar_id}") - return SUCCESS - - if action == "get": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: bossbar get ") - return FAILURE - bar_id = args[1] - prop = args[2].lower() - if bar_id not in _boss_bars: - await ctx.reply(f"[PyMC] Boss 栏 {bar_id} 不存在") - return FAILURE - bar = _boss_bars[bar_id] - if prop in bar: - await ctx.reply(f"[PyMC] {bar_id}.{prop} = {bar[prop]}") - else: - await ctx.reply(f"[PyMC] 未知属性: {prop}") - return SUCCESS - - if action == "set": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: bossbar set <属性> <值>") - return FAILURE - bar_id = args[1] - if bar_id not in _boss_bars: - await ctx.reply(f"[PyMC] Boss 栏 {bar_id} 不存在") - return FAILURE - bar = _boss_bars[bar_id] - prop = args[2].lower() - if len(args) < 4: - await ctx.reply("[PyMC] 缺少值") - return FAILURE - value = args[3] - - if prop == "name": - bar["name"] = ' '.join(args[3:]) - elif prop == "color": - bar["color"] = value.lower() - elif prop == "style": - bar["style"] = value.lower() - elif prop == "value": - try: - bar["value"] = int(value) - except ValueError: - await ctx.reply("[PyMC] 值格式无效") - return FAILURE - elif prop == "max": - try: - bar["max"] = int(value) - except ValueError: - await ctx.reply("[PyMC] 最大值格式无效") - return FAILURE - elif prop == "visible": - bar["visible"] = value.lower() in ("true", "1") - elif prop == "players": - bar["players"] = [value] - else: - await ctx.reply(f"[PyMC] 未知属性: {prop}") - return FAILURE - - await ctx.reply(f"[PyMC] 已设置 Boss 栏 {bar_id} 的 {prop}") - return SUCCESS - - if action == "list": - if not _boss_bars: - await ctx.reply("[PyMC] 没有自定义 Boss 栏") - else: - for bid, bar in _boss_bars.items(): - await ctx.reply(f"[PyMC] {bid}: {bar['name']}") - return SUCCESS - - await ctx.reply("[PyMC] 用法: bossbar ...") - return FAILURE - - cmd = Command( - name="bossbar", - description="管理自定义 Boss 栏", - usage="bossbar ...", - permission="command.bossbar", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/clear.py b/commands/vanilla/clear.py deleted file mode 100755 index d1eec61..0000000 --- a/commands/vanilla/clear.py +++ /dev/null @@ -1,68 +0,0 @@ -# ============================================================ -# PyMC - /clear Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - target = ctx.sender - item_filter = None - max_count = -1 - - # Parse target - if args: - from network.connection import Connection - targets = resolve_selector(ctx.server, ctx.sender, args[0]) - players = [t for t in targets if isinstance(t, Connection)] - if players: - target = players[0] - elif ctx.sender is None: - await ctx.reply(f"[PyMC] 未找到玩家: {args[0]}") - return FAILURE - - # Parse item filter - if len(args) >= 2: - item_filter = args[1].lower() - if ":" not in item_filter: - item_filter = f"minecraft:{item_filter}" - - # Parse max count - if len(args) >= 3: - try: - max_count = int(args[2]) - except ValueError: - await ctx.reply("[PyMC] 数量格式无效") - return FAILURE - - if target is None: - await ctx.reply("[PyMC] 未指定目标玩家") - return FAILURE - - # Clear inventory - cleared = 0 - if hasattr(target, 'inventory_obj') and target.inventory_obj is not None: - cleared = target.inventory_obj.clear_items(item_filter=item_filter, max_count=max_count) - target.inventory_state_id += 1 - else: - cleared = 0 - - if item_filter: - await ctx.reply(f"[PyMC] 已清除 {target.username} 的 {item_filter} x{cleared}") - else: - await ctx.reply(f"[PyMC] 已清除 {target.username} 的物品栏 (共 {cleared} 个物品)") - return SUCCESS - - cmd = Command( - name="clear", - description="清除玩家物品栏", - usage="clear [玩家] [物品] [最大数量]", - permission="command.clear", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/clone.py b/commands/vanilla/clone.py deleted file mode 100755 index 46c2c70..0000000 --- a/commands/vanilla/clone.py +++ /dev/null @@ -1,95 +0,0 @@ -# ============================================================ -# PyMC - /clone Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.arguments import parse_coordinate, resolve_coordinate, parse_mask_mode, parse_clone_mode - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - from world.editing import resolve_block_state, clone_box_detailed - from handlers.play.blocks import _sync_world_edit - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if len(args) < 9: - await ctx.reply("[PyMC] 用法: clone [replace|masked|filtered] [normal|force|move]") - return FAILURE - - bx, by, bz = 0.0, 100.0, 0.0 - if ctx.sender and hasattr(ctx.sender, 'x'): - bx, by, bz = ctx.sender.x, ctx.sender.y, ctx.sender.z - - try: - x1 = int(resolve_coordinate(parse_coordinate(args[0]), bx)) - y1 = int(resolve_coordinate(parse_coordinate(args[1]), by)) - z1 = int(resolve_coordinate(parse_coordinate(args[2]), bz)) - x2 = int(resolve_coordinate(parse_coordinate(args[3]), bx)) - y2 = int(resolve_coordinate(parse_coordinate(args[4]), by)) - z2 = int(resolve_coordinate(parse_coordinate(args[5]), bz)) - dest_x = int(resolve_coordinate(parse_coordinate(args[6]), bx)) - dest_y = int(resolve_coordinate(parse_coordinate(args[7]), by)) - dest_z = int(resolve_coordinate(parse_coordinate(args[8]), bz)) - except (ValueError, IndexError): - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - - volume = (abs(x2 - x1) + 1) * (abs(y2 - y1) + 1) * (abs(z2 - z1) + 1) - if volume > 32768: - await ctx.reply(f"[PyMC] clone 范围过大: {volume} 个方块,当前上限 32768") - return FAILURE - - mask_mode = "replace" - clone_mode = "normal" - filter_block_state = None - arg_index = 9 - - if len(args) > arg_index: - option = args[arg_index].lower() - if option in ("replace", "masked"): - mask_mode = option - arg_index += 1 - elif option == "filtered": - if len(args) <= arg_index + 1: - await ctx.reply("[PyMC] 用法: clone ... filtered <方块> [normal|force|move]") - return FAILURE - mask_mode = "filtered" - filter_block_state = resolve_block_state(args[arg_index + 1]) - if filter_block_state is None: - await ctx.reply(f"[PyMC] 未知方块: {args[arg_index + 1]}") - return FAILURE - arg_index += 2 - - if len(args) > arg_index: - try: - clone_mode = parse_clone_mode(args[arg_index]) - except ValueError: - await ctx.reply("[PyMC] clone 模式必须是 normal、force 或 move") - return FAILURE - - try: - changed, changed_chunks, changed_blocks = clone_box_detailed( - ctx.server, x1, y1, z1, x2, y2, z2, - dest_x, dest_y, dest_z, - mask_mode=mask_mode, - clone_mode=clone_mode, - filter_block_state=filter_block_state, - ) - except ValueError: - await ctx.reply("[PyMC] 源区域与目标区域重叠,请使用 force 或 move") - return FAILURE - - await _sync_world_edit(ctx.server, changed_chunks, changed_blocks) - await ctx.reply(f"[PyMC] 已复制 {changed} 个方块到 ({dest_x}, {dest_y}, {dest_z})") - return SUCCESS - - cmd = Command( - name="clone", - description="复制区域方块", - usage="clone [模式]", - permission="command.clone", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/core.py b/commands/vanilla/core.py deleted file mode 100755 index a3a0cce..0000000 --- a/commands/vanilla/core.py +++ /dev/null @@ -1,173 +0,0 @@ -# ============================================================ -# PyMC - Core Commands -# help, list, stop, reload, save-all, save-on, save-off -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE - - -def register(manager): - """Register all core server commands.""" - - # --- /help --- - async def _help(ctx: CommandContext) -> int: - cmd_name = ctx.arguments.get("command") - if cmd_name: - cmd = manager.get_command(cmd_name) - if cmd: - await ctx.reply(f"[PyMC] /{cmd.name}: {cmd.description}") - if cmd.usage: - await ctx.reply(f"[PyMC] 用法: {cmd.usage}") - return SUCCESS - await ctx.reply(f"[PyMC] 未知命令: /{cmd_name}") - return SUCCESS - - # Show available commands, grouped by category - available = manager.get_commands_for_sender(ctx.sender) - if ctx.sender is not None: - level = ctx.server.permissions.get_permission_level(ctx.sender.username) - await ctx.reply(f"[PyMC] 你的权限组: {level}") - - # Group by category - categories: dict[str, list] = {} - for cmd in sorted(available, key=lambda c: c.name): - cat = getattr(cmd, 'category', 'general') - if cat not in categories: - categories[cat] = [] - categories[cat].append(cmd) - - for cat_name, cmds in sorted(categories.items()): - cmd_list = ", ".join(f"/{cmd.name}" for cmd in cmds) - await ctx.reply(f"[PyMC] [{cat_name}] {cmd_list}") - - return SUCCESS - - def _help_suggest(ctx: CommandContext) -> list[str]: - return [f"/{cmd.name}" for cmd in manager.get_commands_for_sender(ctx.sender)] - - cmd_help = Command( - name="help", - description="显示可用命令列表", - usage="help [命令名]", - aliases=["?"], - permission="command.help", - category="core", - ) - cmd_help._execute_func = _help - cmd_help._suggest_func = _help_suggest - manager.register(cmd_help) - - # --- /list --- - async def _list(ctx: CommandContext) -> int: - players = ctx.server.get_online_players() - names = ", ".join(p.username for p in players) if players else "无" - await ctx.reply(f"[PyMC] 在线玩家 ({len(players)}/{ctx.server.max_players}): {names}") - return SUCCESS - - cmd_list = Command( - name="list", - description="显示在线玩家列表", - usage="list", - permission="command.list", - category="core", - ) - cmd_list._execute_func = _list - manager.register(cmd_list) - - # --- /stop --- - async def _stop(ctx: CommandContext) -> int: - if ctx.sender is not None: - from handlers.play.chat import send_system_message - await send_system_message(ctx.sender, "[PyMC] 正在关闭服务器...") - ctx.server.broadcast_system_message("[PyMC] 服务器正在关闭...") - import asyncio - asyncio.get_event_loop().call_soon(lambda: asyncio.ensure_future(ctx.server.stop())) - return SUCCESS - - cmd_stop = Command( - name="stop", - description="停止服务器", - usage="stop", - permission="command.stop", - category="core", - ) - cmd_stop._execute_func = _stop - manager.register(cmd_stop) - - # --- /reload --- - async def _reload(ctx: CommandContext) -> int: - ctx.server.permissions.load() - await ctx.reply("[PyMC] 已重载权限与白名单配置") - return SUCCESS - - cmd_reload = Command( - name="reload", - description="重载配置", - usage="reload", - permission="command.op", - category="core", - ) - cmd_reload._execute_func = _reload - manager.register(cmd_reload) - - # --- /save-all --- - async def _save_all(ctx: CommandContext) -> int: - ctx.server.save_all_player_states() - ctx.server.world_storage.flush() - await ctx.reply("[PyMC] 世界与玩家数据已保存") - return SUCCESS - - cmd_saveall = Command( - name="save-all", - description="保存所有数据", - usage="save-all", - permission="command.op", - category="core", - ) - cmd_saveall._execute_func = _save_all - manager.register(cmd_saveall) - - # --- /save-on / save-off --- - async def _save_toggle(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - cmd_name = tokens[0].lower() - ctx.server.autosave_enabled = (cmd_name == "save-on") - await ctx.reply(f"[PyMC] 自动保存已{'开启' if ctx.server.autosave_enabled else '关闭'}") - return SUCCESS - - cmd_saveon = Command( - name="save-on", - description="开启自动保存", - usage="save-on", - permission="command.op", - category="core", - ) - cmd_saveon._execute_func = _save_toggle - manager.register(cmd_saveon) - - cmd_saveoff = Command( - name="save-off", - description="关闭自动保存", - usage="save-off", - permission="command.op", - category="core", - ) - cmd_saveoff._execute_func = _save_toggle - manager.register(cmd_saveoff) - - # --- /save-status --- - async def _save_status(ctx: CommandContext) -> int: - autosave = getattr(ctx.server, 'autosave_enabled', True) - status = "开启" if autosave else "关闭" - await ctx.reply(f"[PyMC] 自动保存状态: {status}") - return SUCCESS - - cmd_savestatus = Command( - name="save-status", - description="查看保存状态", - usage="save-status", - permission="command.list", - category="core", - ) - cmd_savestatus._execute_func = _save_status - manager.register(cmd_savestatus) diff --git a/commands/vanilla/damage.py b/commands/vanilla/damage.py deleted file mode 100755 index fe4e5f9..0000000 --- a/commands/vanilla/damage.py +++ /dev/null @@ -1,62 +0,0 @@ -# ============================================================ -# PyMC - /damage Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector -from commands.arguments import parse_damage_type -from network.connection import Connection - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - from handlers.play.join import _damage_player - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: damage <目标> <伤害值> [伤害类型]") - return FAILURE - - # Parse target - targets = resolve_selector(ctx.server, ctx.sender, args[0]) - players = [t for t in targets if isinstance(t, Connection)] - if not players: - if ctx.sender is None: - await ctx.reply(f"[PyMC] 未找到目标: {args[0]}") - return FAILURE - players = [ctx.sender] if isinstance(ctx.sender, Connection) else [] - - if len(args) < 2: - await ctx.reply("[PyMC] 用法: damage <目标> <伤害值> [伤害类型]") - return FAILURE - - try: - amount = float(args[1]) - except ValueError: - await ctx.reply("[PyMC] 伤害值格式无效") - return FAILURE - - damage_type = "generic" - if len(args) >= 3: - try: - damage_type = parse_damage_type(args[2]) - except ValueError: - damage_type = args[2] - - for player in players: - await _damage_player(player, max(0.0, amount), damage_type, ctx.server) - - names = ", ".join(p.username for p in players) - await ctx.reply(f"[PyMC] 已对 {names} 造成 {amount:.1f} 点{damage_type}伤害") - return SUCCESS - - cmd = Command( - name="damage", - description="对实体造成伤害", - usage="damage <目标> <伤害值> [伤害类型]", - permission="command.damage", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/data.py b/commands/vanilla/data.py index efdd6c1..ee1c9bb 100755 --- a/commands/vanilla/data.py +++ b/commands/vanilla/data.py @@ -14,7 +14,7 @@ def register(manager): async def _execute(ctx: CommandContext) -> int: - from network.connection import Connection + pass tokens = ctx.arguments.get("_raw_tokens", []) args = tokens[1:] if len(tokens) > 1 else [] diff --git a/commands/vanilla/datapack.py b/commands/vanilla/datapack.py deleted file mode 100755 index 5958c8d..0000000 --- a/commands/vanilla/datapack.py +++ /dev/null @@ -1,90 +0,0 @@ -# ============================================================ -# PyMC - /datapack Command -# ============================================================ - -import os -import json -import logging - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE - -logger = logging.getLogger("PyMC.数据包") - - -# Loaded datapacks -_loaded_datapacks: dict[str, dict] = {} - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - # List datapacks - if not _loaded_datapacks: - await ctx.reply("[PyMC] 没有已加载的数据包") - else: - for name, pack in _loaded_datapacks.items(): - status = "启用" if pack.get("enabled", True) else "禁用" - await ctx.reply(f"[PyMC] {name}: {status} ({pack.get('description', '')})") - return SUCCESS - - action = args[0].lower() - - if action == "list": - available = "可用" if len(args) >= 2 and args[1] == "available" else "已启用" - if available == "已启用": - for name, pack in _loaded_datapacks.items(): - if pack.get("enabled", True): - await ctx.reply(f"[PyMC] {name}") - else: - # Scan datapack directory - search_dirs = ["world/datapacks", "datapacks"] - found = set() - for d in search_dirs: - if os.path.isdir(d): - for entry in os.listdir(d): - if entry.endswith(".zip") or os.path.isdir(os.path.join(d, entry)): - found.add(entry.replace(".zip", "")) - if found: - await ctx.reply(f"[PyMC] 可用数据包: {', '.join(sorted(found))}") - else: - await ctx.reply("[PyMC] 没有找到可用的数据包") - return SUCCESS - - if action == "enable": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: datapack enable <名称>") - return FAILURE - pack_name = args[1] - if pack_name in _loaded_datapacks: - _loaded_datapacks[pack_name]["enabled"] = True - else: - _loaded_datapacks[pack_name] = {"enabled": True, "description": "自定义数据包"} - await ctx.reply(f"[PyMC] 已启用数据包: {pack_name}") - return SUCCESS - - if action == "disable": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: datapack disable <名称>") - return FAILURE - pack_name = args[1] - if pack_name in _loaded_datapacks: - _loaded_datapacks[pack_name]["enabled"] = False - await ctx.reply(f"[PyMC] 已禁用数据包: {pack_name}") - else: - await ctx.reply(f"[PyMC] 数据包不存在: {pack_name}") - return FAILURE - - await ctx.reply("[PyMC] 用法: datapack ...") - return FAILURE - - cmd = Command( - name="datapack", - description="管理数据包", - usage="datapack <名称>", - permission="command.datapack", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/default_commands.py b/commands/vanilla/default_commands.py index a553bb9..fe76897 100755 --- a/commands/vanilla/default_commands.py +++ b/commands/vanilla/default_commands.py @@ -4,254 +4,22 @@ # ============================================================ from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector -from network.connection import Connection def register(manager): # --- /say --- - async def _say(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: say <消息>") - return FAILURE - message = ' '.join(tokens[1:]) - full_text = f"[Server] {message}" - ctx.server.broadcast_system_message(full_text) - return SUCCESS - - cmd_say = Command(name="say", description="广播服务器消息", usage="say <消息>", permission="command.say") - cmd_say._execute_func = _say - manager.register(cmd_say) - # --- /me --- - async def _me(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: /me <动作>") - return FAILURE - action = ' '.join(tokens[1:]) - ctx.server.broadcast_system_message(f"* {ctx.source_name} {action}") - return SUCCESS - - cmd_me = Command(name="me", description="发送动作消息", usage="me <动作>", permission="command.me") - cmd_me._execute_func = _me - manager.register(cmd_me) - # --- /msg --- - async def _msg(ctx: CommandContext) -> int: - from handlers.play.chat import send_system_message - - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 3: - await ctx.reply("[PyMC] 用法: /msg <玩家> <消息>") - return FAILURE - - target = ctx.server.find_player(tokens[1]) - if target is None: - await ctx.reply(f"[PyMC] 未找到玩家: {tokens[1]}") - return FAILURE - - message = ' '.join(tokens[2:]) - await send_system_message(target, f"[私聊] {ctx.source_name}: {message}") - if ctx.sender is not None and target != ctx.sender: - await send_system_message(ctx.sender, f"[私聊 -> {target.username}] {message}") - return SUCCESS - - cmd_msg = Command( - name="msg", description="发送私聊消息", - usage="msg <玩家> <消息>", - aliases=["tell", "w"], - permission="command.msg", - ) - cmd_msg._execute_func = _msg - manager.register(cmd_msg) - # --- /kick --- - async def _kick(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: kick <玩家> [原因]") - return FAILURE - - target = ctx.server.find_player(tokens[1]) - if target is None: - await ctx.reply(f"[PyMC] 未找到玩家: {tokens[1]}") - return FAILURE - - reason = ' '.join(tokens[2:]) if len(tokens) >= 3 else "已被管理员移出服务器" - await target.disconnect(reason) - await ctx.reply(f"[PyMC] 已踢出 {target.username}: {reason}") - return SUCCESS - - cmd_kick = Command(name="kick", description="踢出玩家", usage="kick <玩家> [原因]", permission="command.kick") - cmd_kick._execute_func = _kick - manager.register(cmd_kick) - # --- /ban --- - async def _ban(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: ban <玩家> [原因]") - return FAILURE - - reason = ' '.join(tokens[2:]) if len(tokens) >= 3 else "" - ctx.server.permissions.ban_player(tokens[1], reason) - target = ctx.server.find_player(tokens[1]) - if target is not None: - await target.disconnect(reason or "你已被封禁") - await ctx.reply(f"[PyMC] 已封禁玩家: {tokens[1]}") - return SUCCESS - - cmd_ban = Command(name="ban", description="封禁玩家", usage="ban <玩家> [原因]", permission="command.ban") - cmd_ban._execute_func = _ban - manager.register(cmd_ban) - # --- /pardon --- - async def _pardon(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: pardon <玩家>") - return FAILURE - ctx.server.permissions.pardon_player(tokens[1]) - await ctx.reply(f"[PyMC] 已解除封禁: {tokens[1]}") - return SUCCESS - - cmd_pardon = Command(name="pardon", description="解除封禁", usage="pardon <玩家>", permission="command.ban") - cmd_pardon._execute_func = _pardon - manager.register(cmd_pardon) - # --- /ban-ip --- - async def _ban_ip(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: ban-ip [原因]") - return FAILURE - - reason = ' '.join(tokens[2:]) if len(tokens) >= 3 else "" - ctx.server.permissions.ban_ip(tokens[1], reason) - for player in ctx.server.get_online_players(): - address = player.address.split(":")[0] - if address == tokens[1]: - await player.disconnect(reason or "你的 IP 已被封禁") - await ctx.reply(f"[PyMC] 已封禁 IP: {tokens[1]}") - return SUCCESS - - cmd_banip = Command(name="ban-ip", description="封禁 IP", usage="ban-ip [原因]", permission="command.ban") - cmd_banip._execute_func = _ban_ip - manager.register(cmd_banip) - # --- /pardon-ip --- - async def _pardon_ip(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: pardon-ip ") - return FAILURE - ctx.server.permissions.pardon_ip(tokens[1]) - await ctx.reply(f"[PyMC] 已解除 IP 封禁: {tokens[1]}") - return SUCCESS - - cmd_pardonip = Command(name="pardon-ip", description="解除 IP 封禁", usage="pardon-ip ", permission="command.ban") - cmd_pardonip._execute_func = _pardon_ip - manager.register(cmd_pardonip) - # --- /banlist --- - async def _banlist(ctx: CommandContext) -> int: - banlist = ctx.server.permissions.get_banlist() - players = ", ".join(sorted(entry["name"] for entry in banlist["players"].values())) or "无" - ips = ", ".join(sorted(banlist["ips"].keys())) or "无" - await ctx.reply(f"[PyMC] 玩家封禁: {players}") - await ctx.reply(f"[PyMC] IP 封禁: {ips}") - return SUCCESS - - cmd_banlist = Command(name="banlist", description="查看封禁列表", usage="banlist", permission="command.ban") - cmd_banlist._execute_func = _banlist - manager.register(cmd_banlist) - # --- /op --- - async def _op(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: op <玩家>") - return FAILURE - ctx.server.permissions.op(tokens[1]) - ctx.server.permissions.set_user_group(tokens[1], "admin") - await ctx.reply(f"[PyMC] 已授予 OP: {tokens[1]}") - return SUCCESS - - cmd_op = Command(name="op", description="授予 OP 权限", usage="op <玩家>", permission="command.op") - cmd_op._execute_func = _op - manager.register(cmd_op) - # --- /deop --- - async def _deop(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: deop <玩家>") - return FAILURE - ctx.server.permissions.deop(tokens[1]) - ctx.server.permissions.set_user_group(tokens[1], "default") - await ctx.reply(f"[PyMC] 已移除 OP: {tokens[1]}") - return SUCCESS - - cmd_deop = Command(name="deop", description="移除 OP 权限", usage="deop <玩家>", permission="command.op") - cmd_deop._execute_func = _deop - manager.register(cmd_deop) - # --- /whitelist --- - async def _whitelist(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - whitelist = ctx.server.permissions.get_whitelist() - status = "开启" if whitelist["enabled"] else "关闭" - players = ", ".join(whitelist["players"]) or "无" - await ctx.reply(f"[PyMC] 白名单状态: {status}") - await ctx.reply(f"[PyMC] 白名单玩家: {players}") - return SUCCESS - - action = tokens[1].lower() - if action == "on": - ctx.server.permissions.set_whitelist_enabled(True) - await ctx.reply("[PyMC] 白名单已开启") - elif action == "off": - ctx.server.permissions.set_whitelist_enabled(False) - await ctx.reply("[PyMC] 白名单已关闭") - elif action == "list": - whitelist = ctx.server.permissions.get_whitelist() - players = ", ".join(whitelist["players"]) or "无" - await ctx.reply(f"[PyMC] 白名单玩家: {players}") - elif action == "add" and len(tokens) >= 3: - ctx.server.permissions.add_whitelist(tokens[2]) - await ctx.reply(f"[PyMC] 已加入白名单: {tokens[2]}") - elif action == "remove" and len(tokens) >= 3: - ctx.server.permissions.remove_whitelist(tokens[2]) - await ctx.reply(f"[PyMC] 已移除白名单: {tokens[2]}") - elif action == "reload": - ctx.server.permissions.load() - await ctx.reply("[PyMC] 白名单与权限文件已重载") - else: - await ctx.reply("[PyMC] 用法: whitelist ") - return FAILURE - return SUCCESS - - cmd_whitelist = Command(name="whitelist", description="管理白名单", usage="whitelist ", permission="command.whitelist") - cmd_whitelist._execute_func = _whitelist - manager.register(cmd_whitelist) - # --- /stop --- - async def _stop(ctx: CommandContext) -> int: - if ctx.sender is not None: - from handlers.play.chat import send_system_message - await send_system_message(ctx.sender, "[PyMC] 正在关闭服务器...") - ctx.server.broadcast_system_message("[PyMC] 服务器正在关闭...") - import asyncio - asyncio.get_event_loop().call_soon(lambda: asyncio.ensure_future(ctx.server.stop())) - return SUCCESS - - cmd_stop = Command(name="stop", description="停止服务器", usage="stop", permission="command.stop") - cmd_stop._execute_func = _stop - manager.register(cmd_stop) - # --- /reload --- async def _reload(ctx: CommandContext) -> int: ctx.server.permissions.load() @@ -263,122 +31,10 @@ async def _reload(ctx: CommandContext) -> int: manager.register(cmd_reload) # --- /save-all --- - async def _save_all(ctx: CommandContext) -> int: - ctx.server.save_all_player_states() - ctx.server.world_storage.flush() - await ctx.reply("[PyMC] 世界与玩家数据已保存") - return SUCCESS - - cmd_saveall = Command(name="save-all", description="保存所有数据", usage="save-all", permission="command.op") - cmd_saveall._execute_func = _save_all - manager.register(cmd_saveall) - # --- /save-on / save-off --- - async def _save_toggle(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - cmd_name = tokens[0].lower() - ctx.server.autosave_enabled = (cmd_name == "save-on") - await ctx.reply(f"[PyMC] 自动保存已{'开启' if ctx.server.autosave_enabled else '关闭'}") - return SUCCESS - - cmd_saveon = Command(name="save-on", description="开启自动保存", usage="save-on", permission="command.op") - cmd_saveon._execute_func = _save_toggle - manager.register(cmd_saveon) - - cmd_saveoff = Command(name="save-off", description="关闭自动保存", usage="save-off", permission="command.op") - cmd_saveoff._execute_func = _save_toggle - manager.register(cmd_saveoff) - # --- /defaultgamemode --- - async def _defaultgamemode(ctx: CommandContext) -> int: - from commands.arguments import parse_gamemode - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: defaultgamemode ") - return FAILURE - try: - _, normalized = parse_gamemode(tokens[1]) - except ValueError: - await ctx.reply("[PyMC] 无效模式") - return FAILURE - ctx.server.config["gamemode"] = normalized - ctx.server.save_runtime_config() - await ctx.reply(f"[PyMC] 默认游戏模式已设置为 {normalized}") - return SUCCESS - - cmd_dgm = Command(name="defaultgamemode", description="设置默认游戏模式", usage="defaultgamemode <模式>", permission="command.gamemode") - cmd_dgm._execute_func = _defaultgamemode - manager.register(cmd_dgm) - # --- /setworldspawn --- - async def _setworldspawn(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) >= 4: - try: - x = int(float(tokens[1])) - y = int(float(tokens[2])) - z = int(float(tokens[3])) - except ValueError: - await ctx.reply("[PyMC] 用法: setworldspawn ") - return FAILURE - else: - x = int(ctx.server.spawn_position[0]) - y = int(ctx.server.spawn_position[1]) - z = int(ctx.server.spawn_position[2]) - ctx.server.spawn_position = (x, y, z) - ctx.server.save_runtime_config() - await ctx.reply(f"[PyMC] 世界出生点已设置为 ({x}, {y}, {z})") - return SUCCESS - - cmd_sws = Command(name="setworldspawn", description="设置世界出生点", usage="setworldspawn [x y z]", permission="command.op") - cmd_sws._execute_func = _setworldspawn - manager.register(cmd_sws) - # --- /spawnpoint --- - async def _spawnpoint(ctx: CommandContext) -> int: - import math - tokens = ctx.arguments.get("_raw_tokens", []) - target = ctx.sender - coord_index = 1 - - if len(tokens) >= 2 and ctx.sender is None: - target = ctx.server.find_player(tokens[1]) - coord_index = 2 - if target is None: - await ctx.reply(f"[PyMC] 未找到玩家: {tokens[1]}") - return FAILURE - elif len(tokens) >= 2 and ctx.sender is not None: - maybe_target = ctx.server.find_player(tokens[1]) - if maybe_target is not None: - target = maybe_target - coord_index = 2 - - if target is None: - await ctx.reply("[PyMC] 用法: spawnpoint [玩家] [x y z]") - return FAILURE - - if len(tokens) >= coord_index + 3: - try: - spawn_x = int(float(tokens[coord_index])) - spawn_y = int(float(tokens[coord_index + 1])) - spawn_z = int(float(tokens[coord_index + 2])) - except ValueError: - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - else: - spawn_x = math.floor(target.x) - spawn_y = math.floor(target.y) - spawn_z = math.floor(target.z) - - target.personal_spawn = (spawn_x, spawn_y, spawn_z) - ctx.server.save_player_state(target) - await ctx.reply(f"[PyMC] 已将 {target.username or '玩家'} 的个人出生点设置为 ({spawn_x}, {spawn_y}, {spawn_z})") - return SUCCESS - - cmd_sp = Command(name="spawnpoint", description="设置个人出生点", usage="spawnpoint [玩家] [x y z]", permission="command.op") - cmd_sp._execute_func = _spawnpoint - manager.register(cmd_sp) - # --- /entities --- async def _entities(ctx: CommandContext) -> int: counts = ctx.server.entity_manager.count_by_kind() diff --git a/commands/vanilla/difficulty.py b/commands/vanilla/difficulty.py deleted file mode 100755 index 9002be8..0000000 --- a/commands/vanilla/difficulty.py +++ /dev/null @@ -1,40 +0,0 @@ -# ============================================================ -# PyMC - /difficulty Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.arguments import parse_difficulty - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply(f"[PyMC] 当前难度: {ctx.server.config.get('difficulty', 'normal')}") - return SUCCESS - - try: - diff_int, diff_name = parse_difficulty(args[0]) - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - - ctx.server.config["difficulty"] = diff_name - ctx.server.save_runtime_config() - await ctx.reply(f"[PyMC] 难度已设置为 {diff_name}") - return SUCCESS - - def _suggest(ctx: CommandContext) -> list[str]: - return ["peaceful", "easy", "normal", "hard"] - - cmd = Command( - name="difficulty", - description="设置游戏难度", - usage="difficulty ", - permission="command.difficulty", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) diff --git a/commands/vanilla/display.py b/commands/vanilla/display.py index d22b352..0af95fe 100755 --- a/commands/vanilla/display.py +++ b/commands/vanilla/display.py @@ -8,7 +8,6 @@ import json import logging -from typing import Any from commands.framework import Command, CommandContext, SUCCESS, FAILURE from commands.selector import resolve_selector diff --git a/commands/vanilla/effect.py b/commands/vanilla/effect.py deleted file mode 100755 index ce63dee..0000000 --- a/commands/vanilla/effect.py +++ /dev/null @@ -1,146 +0,0 @@ -# ============================================================ -# PyMC - /effect Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector -from commands.arguments import parse_effect_name, EFFECT_NAMES - - -# In-memory active effects per player -_active_effects: dict[str, dict[str, dict]] = {} # username -> {effect_name -> {amplifier, duration, ambient}} - - -def get_active_effects(username: str) -> dict[str, dict]: - """Get active effects for a player.""" - return _active_effects.get(username, {}) - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - from network.connection import Connection - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: effect give <目标> <效果> [秒数] [放大器] [是否环境] | effect clear <目标> [效果]") - return FAILURE - - sub = args[0].lower() - - if sub == "give": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: effect give <目标> <效果> [秒数] [放大器]") - return FAILURE - - targets = resolve_selector(ctx.server, ctx.sender, args[1]) - players = [t for t in targets if isinstance(t, Connection)] - if not players: - await ctx.reply(f"[PyMC] 未找到目标: {args[1]}") - return FAILURE - - try: - effect_name = parse_effect_name(args[2]) - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - - duration = 600 # 30 seconds default - if len(args) >= 4: - try: - duration = int(args[3]) * 20 # seconds to ticks - if duration == 0: - duration = 600 - except ValueError: - await ctx.reply("[PyMC] 持续时间格式无效") - return FAILURE - - amplifier = 0 - if len(args) >= 5: - try: - amplifier = int(args[4]) - amplifier = max(0, min(255, amplifier)) - except ValueError: - await ctx.reply("[PyMC] 放大器格式无效") - return FAILURE - - ambient = False - if len(args) >= 6: - ambient = args[5].lower() in ("true", "1", "yes") - - # Store the effect - for player in players: - if player.username not in _active_effects: - _active_effects[player.username] = {} - _active_effects[player.username][effect_name] = { - "amplifier": amplifier, - "duration": duration, - "ambient": ambient, - "effect_id": EFFECT_NAMES.get(effect_name, 0), - } - - names = ", ".join(p.username for p in players) - await ctx.reply(f"[PyMC] 已给予 {names} {effect_name} 效果 (等级 {amplifier + 1}, {duration // 20}秒)") - return SUCCESS - - elif sub == "clear": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: effect clear <目标> [效果]") - return FAILURE - - targets = resolve_selector(ctx.server, ctx.sender, args[1]) - players = [t for t in targets if isinstance(t, Connection)] - if not players: - await ctx.reply(f"[PyMC] 未找到目标: {args[1]}") - return FAILURE - - effect_to_clear = None - if len(args) >= 3: - try: - effect_to_clear = parse_effect_name(args[2]) - except ValueError: - await ctx.reply(f"[PyMC] 未知效果: {args[2]}") - return FAILURE - - total_cleared = 0 - for player in players: - if player.username in _active_effects: - if effect_to_clear: - if effect_to_clear in _active_effects[player.username]: - del _active_effects[player.username][effect_to_clear] - total_cleared += 1 - else: - total_cleared += len(_active_effects[player.username]) - _active_effects[player.username] = {} - - names = ", ".join(p.username for p in players) - if effect_to_clear: - await ctx.reply(f"[PyMC] 已清除 {names} 的 {effect_to_clear} 效果") - else: - await ctx.reply(f"[PyMC] 已清除 {names} 的所有效果 (共 {total_cleared} 个)") - return SUCCESS - - await ctx.reply("[PyMC] 用法: effect ...") - return FAILURE - - def _suggest(ctx: CommandContext) -> list[str]: - tokens = ctx.input_string.split() - if len(tokens) == 2: - return ["give", "clear"] - if len(tokens) >= 3 and tokens[1] == "give": - if len(tokens) == 3: - return ["@a", "@p", "@s"] - if len(tokens) == 4: - return list(EFFECT_NAMES.keys()) - return [] - - cmd = Command( - name="effect", - description="给予或清除状态效果", - usage="effect give <目标> <效果> [秒数] [放大器] | effect clear <目标> [效果]", - permission="command.effect", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) diff --git a/commands/vanilla/enchant.py b/commands/vanilla/enchant.py deleted file mode 100755 index 6e42ef8..0000000 --- a/commands/vanilla/enchant.py +++ /dev/null @@ -1,100 +0,0 @@ -# ============================================================ -# PyMC - /enchant Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector -from commands.arguments import parse_enchantment_name, ENCHANTMENT_NAMES - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - from network.connection import Connection - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: enchant <目标> <附魔> [等级]") - return FAILURE - - target = ctx.sender - target_spec = args[0] - - if ctx.sender is None or (len(args) >= 2 and not _is_number(args[1]) and args[1].lower() not in ENCHANTMENT_NAMES): - targets = resolve_selector(ctx.server, ctx.sender, target_spec) - players = [t for t in targets if isinstance(t, Connection)] - if players: - target = players[0] - elif ctx.sender is None: - await ctx.reply(f"[PyMC] 未找到目标: {target_spec}") - return FAILURE - - # Find the enchantment argument - enchant_idx = 1 if target != ctx.sender else 0 - if enchant_idx >= len(args): - await ctx.reply("[PyMC] 用法: enchant <目标> <附魔> [等级]") - return FAILURE - - try: - enchant_name = parse_enchantment_name(args[enchant_idx]) - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - - level = 1 - if len(args) > enchant_idx + 1: - try: - level = int(args[enchant_idx + 1]) - level = max(1, min(255, level)) - except ValueError: - await ctx.reply("[PyMC] 等级格式无效") - return FAILURE - - if target is None: - await ctx.reply("[PyMC] 未找到目标") - return FAILURE - - # Apply enchantment (record on inventory item if available) - if hasattr(target, 'inventory_obj') and target.inventory_obj is not None: - slot = target.selected_hotbar_slot - item = target.inventory_obj.get_slot(slot) - if item is not None and not item.is_empty: - from world.item_properties import add_enchantment - add_enchantment(item, enchant_name, level) - from world.inventory import send_inventory_sync - await send_inventory_sync(target) - await ctx.reply(f"[PyMC] 已附魔 {target.username} 手持物品: {enchant_name} {level}") - return SUCCESS - else: - await ctx.reply(f"[PyMC] {target.username} 手中没有物品") - return FAILURE - - # Fallback - await ctx.reply(f"[PyMC] 已附魔 {target.username}: {enchant_name} {level}") - return SUCCESS - - def _suggest(ctx: CommandContext) -> list[str]: - tokens = ctx.input_string.split() - if len(tokens) >= 3: - partial = tokens[-1] if tokens[-1] else "" - return [e for e in ENCHANTMENT_NAMES if e.startswith(partial)] - return [] - - cmd = Command( - name="enchant", - description="给手持物品添加附魔", - usage="enchant <目标> <附魔> [等级]", - permission="command.enchant", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) - - -def _is_number(s: str) -> bool: - try: - float(s) - return True - except ValueError: - return False diff --git a/commands/vanilla/entity.py b/commands/vanilla/entity.py index 6f69501..6532427 100755 --- a/commands/vanilla/entity.py +++ b/commands/vanilla/entity.py @@ -5,7 +5,7 @@ from commands.framework import Command, CommandContext, SUCCESS, FAILURE from commands.selector import resolve_selector -from commands.arguments import parse_coordinate, resolve_coordinate, parse_damage_type +from commands.arguments import parse_damage_type from network.connection import Connection @@ -13,81 +13,6 @@ def register(manager): """Register all entity-related commands.""" # --- /summon --- - async def _summon(ctx: CommandContext) -> int: - from handlers.play.entities import broadcast_entity_spawn - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: summon <实体类型> [x] [y] [z] [NBT]") - return FAILURE - - entity_type = args[0].lower() - if ":" in entity_type: - entity_type = entity_type.split(":", 1)[1] - - bx, by, bz = 0.0, 100.0, 0.0 - if ctx.sender and hasattr(ctx.sender, 'x'): - bx, by, bz = ctx.sender.x, ctx.sender.y, ctx.sender.z - - if len(args) >= 4: - try: - x = resolve_coordinate(parse_coordinate(args[1]), bx) - y = resolve_coordinate(parse_coordinate(args[2]), by) - z = resolve_coordinate(parse_coordinate(args[3]), bz) - except (ValueError, IndexError): - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - else: - x, y, z = bx, by, bz - - entity = None - if entity_type == "experience_orb" or entity_type == "orb": - count = 1 - if len(args) >= 5: - try: - count = max(1, int(args[4])) - except ValueError: - pass - entity = ctx.server.entity_manager.create_experience_orb(x, y, z, count=count) - await broadcast_entity_spawn(ctx.server, entity) - await ctx.reply(f"[PyMC] 已生成经验球实体 #{entity.entity_id} x{count}") - elif entity_type == "item": - item_name = "minecraft:stone" - count = 1 - if len(args) >= 5: - item_name = args[4] - if ":" not in item_name: - item_name = f"minecraft:{item_name}" - if len(args) >= 6: - try: - count = max(1, int(args[5])) - except ValueError: - pass - entity = ctx.server.entity_manager.create_item(x, y, z, item_name=item_name, count=count) - await ctx.reply(f"[PyMC] 已生成 item 实体 #{entity.entity_id}: {item_name} x{count}") - elif entity_type in ("pig", "cow", "sheep", "zombie", "skeleton", "creeper", "spider"): - entity = ctx.server.entity_manager.create_mob(x, y, z, mob_type=entity_type) - await broadcast_entity_spawn(ctx.server, entity) - await ctx.reply(f"[PyMC] 已生成 {entity_type} 实体 #{entity.entity_id}") - else: - entity = ctx.server.entity_manager.create_mob(x, y, z, mob_type=entity_type) - await broadcast_entity_spawn(ctx.server, entity) - await ctx.reply(f"[PyMC] 已生成 {entity_type} 实体 #{entity.entity_id}") - - return SUCCESS - - cmd_summon = Command( - name="summon", - description="生成实体", - usage="summon <实体类型> [x] [y] [z] [NBT]", - permission="command.summon", - category="entity", - ) - cmd_summon._execute_func = _summon - manager.register(cmd_summon) - # --- /damage --- async def _damage(ctx: CommandContext) -> int: from handlers.play.join import _damage_player diff --git a/commands/vanilla/essentials.py b/commands/vanilla/essentials.py index cd2c869..3d2d6a0 100644 --- a/commands/vanilla/essentials.py +++ b/commands/vanilla/essentials.py @@ -981,11 +981,9 @@ async def _kill(ctx: CommandContext) -> int: # ---------------- experience ---------------- def _points_for_level(level: int) -> int: - if level >= 30: - return 112 + (level - 30) * 9 - if level >= 15: - return 37 + (level - 15) * 5 - return 7 + level * 2 + # vanilla experience curve, shared with the player experience code + from handlers.play.join import _experience_needed_for_next_level + return _experience_needed_for_next_level(level) def _total_for_level(level: int) -> int: return sum(_points_for_level(i) for i in range(max(0, level))) diff --git a/commands/vanilla/execute.py b/commands/vanilla/execute.py deleted file mode 100755 index ae1afe1..0000000 --- a/commands/vanilla/execute.py +++ /dev/null @@ -1,606 +0,0 @@ -# ============================================================ -# PyMC - /execute Command -# The most complex vanilla command. Supports chained subcommands. -# ============================================================ - -from __future__ import annotations - -import math -import logging -from typing import Any - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE, ERROR -from commands.selector import resolve_selector, parse_selector, parse_int_range - -logger = logging.getLogger("PyMC.命令执行") - - -class ExecuteContext: - """Mutable context for an /execute chain. - - Tracks the current executor, position, rotation, dimension, - anchor point, and store targets as the chain is processed. - """ - - def __init__(self, server, sender): - self.server = server - self.original_sender = sender - self.executor = sender # Current executing entity - self.position = ( - sender.x if sender and hasattr(sender, 'x') else 0.0, - sender.y if sender and hasattr(sender, 'y') else 100.0, - sender.z if sender and hasattr(sender, 'z') else 0.0, - ) - self.yaw = sender.yaw if sender and hasattr(sender, 'yaw') else 0.0 - self.pitch = sender.pitch if sender and hasattr(sender, 'pitch') else 0.0 - self.dimension = "overworld" - self.anchor = "feet" # "feet" or "eyes" - self.store_targets: list[dict] = [] - self.condition_result: bool | None = None - - def clone(self) -> ExecuteContext: - """Create a copy of this context for branching (e.g., 'as' with multiple targets).""" - new = ExecuteContext(self.server, self.original_sender) - new.executor = self.executor - new.position = self.position - new.yaw = self.yaw - new.pitch = self.pitch - new.dimension = self.dimension - new.anchor = self.anchor - new.store_targets = list(self.store_targets) - new.condition_result = self.condition_result - return new - - -def _tokenize_execute(args_str: str) -> list[str]: - """Tokenize the execute subcommand chain, respecting quoted strings and brackets.""" - tokens = [] - current = [] - in_quotes = False - depth = 0 - - for ch in args_str: - if ch == '"': - in_quotes = not in_quotes - current.append(ch) - elif ch == '[' and not in_quotes: - depth += 1 - current.append(ch) - elif ch == ']' and not in_quotes: - depth -= 1 - current.append(ch) - elif ch == '{' and not in_quotes: - depth += 1 - current.append(ch) - elif ch == '}' and not in_quotes: - depth -= 1 - current.append(ch) - elif ch == ' ' and not in_quotes and depth == 0: - if current: - tokens.append(''.join(current)) - current = [] - else: - current.append(ch) - - if current: - tokens.append(''.join(current)) - - return tokens - - -# ============================================================ -# Condition evaluation -# ============================================================ - -async def _evaluate_condition(ctx: CommandContext, exec_ctx: ExecuteContext, condition_type: str, tokens: list[str], index: int) -> tuple[bool, int]: - """Evaluate a condition for if/unless. - - Returns: - (result, next_index) where next_index is the token index after this condition - """ - if condition_type == "entity": - if index >= len(tokens): - return (False, index) - targets = resolve_selector(exec_ctx.server, exec_ctx.executor, tokens[index]) - return (len(targets) > 0, index + 1) - - if condition_type == "score": - if index + 3 >= len(tokens): - return (False, index + 4) - from commands.vanilla.scoreboard import get_scoreboard_manager - sb = get_scoreboard_manager() - target_player = tokens[index] - target_obj = tokens[index + 1] - operation = tokens[index + 2] - - target_score = sb.get_score(target_obj, target_player) - - if operation == "matches": - if index + 3 < len(tokens): - try: - min_val, max_val = parse_int_range(tokens[index + 3]) - if min_val is not None and target_score < min_val: - return (False, index + 4) - if max_val is not None and target_score > max_val: - return (False, index + 4) - return (True, index + 4) - except ValueError: - return (False, index + 4) - return (False, index + 4) - - # Binary comparison: score - if index + 5 >= len(tokens): - return (False, index + 5) - source_player = tokens[index + 3] - source_obj = tokens[index + 4] - source_score = sb.get_score(source_obj, source_player) - - if operation == "<": - result = target_score < source_score - elif operation == "<=": - result = target_score <= source_score - elif operation == ">": - result = target_score > source_score - elif operation == ">=": - result = target_score >= source_score - elif operation == "=": - result = target_score == source_score - else: - result = False - return (result, index + 5) - - if condition_type == "block": - # if block - if index + 3 >= len(tokens): - return (False, index + 4) - try: - from commands.arguments import parse_coordinate, resolve_coordinate - bx, by, bz = exec_ctx.position - x = int(resolve_coordinate(parse_coordinate(tokens[index]), bx)) - y = int(resolve_coordinate(parse_coordinate(tokens[index + 1]), by)) - z = int(resolve_coordinate(parse_coordinate(tokens[index + 2]), bz)) - except (ValueError, IndexError): - return (False, index + 4) - - # Get the block at the position - block_name = tokens[index + 3] if index + 3 < len(tokens) else "" - if ":" not in block_name: - block_name = f"minecraft:{block_name}" - - # Check world block - try: - from world.editing import resolve_block_state - target_state = resolve_block_state(block_name) - if target_state is None: - return (False, index + 4) - - # Get the actual block at position - chunk_x = (x >> 4) + 13 # Adjust for internal chunk offset - chunk_z = (z >> 4) + 13 - section_y = (y + 64) // 16 - - world = exec_ctx.server.world - if chunk_x < 0 or chunk_x >= 27 or chunk_z < 0 or chunk_z >= 27: - return (False, index + 4) - - chunk_data = world.chunks.get((chunk_x, chunk_z)) - if chunk_data is None: - return (False, index + 4) - - actual_state = chunk_data.get_block(x & 0xF, y, z & 0xF) - result = (actual_state == target_state) - except Exception: - result = False - - return (result, index + 4) - - if condition_type == "blocks": - # if blocks - # Simplified: just check if area exists - return (True, index + 13) - - if condition_type == "predicate": - # Not fully supported - return (True, index + 1) - - if condition_type == "function": - # if function - check if function returns success - return (True, index + 1) - - if condition_type == "loaded": - # if loaded - check if position is in loaded chunk - if index + 2 >= len(tokens): - return (False, index + 3) - try: - from commands.arguments import parse_coordinate, resolve_coordinate - bx, by, bz = exec_ctx.position - x = int(resolve_coordinate(parse_coordinate(tokens[index]), bx)) - z = int(resolve_coordinate(parse_coordinate(tokens[index + 2]), bz)) - chunk_x = (x >> 4) + 13 - chunk_z = (z >> 4) + 13 - world = exec_ctx.server.world - loaded = (chunk_x, chunk_z) in world.chunks - return (loaded, index + 3) - except (ValueError, IndexError): - return (False, index + 3) - - return (False, index + 1) - - -def _skip_condition_tokens(tokens: list[str], index: int, condition_type: str) -> int: - """Skip past the tokens of a condition to find the next subcommand.""" - if condition_type == "entity": - return index + 1 - if condition_type == "score": - # score - # or score matches - if index + 2 < len(tokens): - op = tokens[index + 2] - if op == "matches": - return index + 4 - return index + 5 - return index + 4 - if condition_type == "block": - return index + 4 - if condition_type == "blocks": - return index + 13 # Rough estimate - if condition_type == "predicate": - return index + 1 - if condition_type == "function": - return index + 1 - if condition_type == "loaded": - return index + 3 - return index + 1 - - -# ============================================================ -# Execute chain processor -# ============================================================ - -async def _execute_chain(ctx: CommandContext, exec_ctx: ExecuteContext, tokens: list[str], index: int) -> int: - """Recursively process an /execute subcommand chain.""" - if index >= len(tokens): - return FAILURE - - subcommand = tokens[index].lower() - - # --- as --- - if subcommand == "as": - if index + 1 >= len(tokens): - await ctx.reply("[PyMC] execute as: 缺少目标") - return FAILURE - targets = resolve_selector(exec_ctx.server, exec_ctx.executor, tokens[index + 1]) - if not targets: - return FAILURE - # Run the rest of the chain for each target as executor - results = [] - for target in targets: - new_ctx = exec_ctx.clone() - new_ctx.executor = target - result = await _execute_chain(ctx, new_ctx, tokens, index + 2) - results.append(result) - return SUCCESS if any(r == SUCCESS for r in results) else FAILURE - - # --- at --- - if subcommand == "at": - if index + 1 >= len(tokens): - await ctx.reply("[PyMC] execute at: 缺少目标") - return FAILURE - targets = resolve_selector(exec_ctx.server, exec_ctx.executor, tokens[index + 1]) - if not targets: - return FAILURE - target = targets[0] - exec_ctx.position = (target.x, target.y, target.z) if hasattr(target, 'x') else exec_ctx.position - exec_ctx.yaw = target.yaw if hasattr(target, 'yaw') else exec_ctx.yaw - exec_ctx.pitch = target.pitch if hasattr(target, 'pitch') else exec_ctx.pitch - return await _execute_chain(ctx, exec_ctx, tokens, index + 2) - - # --- positioned / positioned as / positioned over --- - if subcommand == "positioned": - if index + 1 >= len(tokens): - await ctx.reply("[PyMC] execute positioned: 缺少参数") - return FAILURE - if tokens[index + 1].lower() == "as": - if index + 2 >= len(tokens): - await ctx.reply("[PyMC] execute positioned as: 缺少目标") - return FAILURE - targets = resolve_selector(exec_ctx.server, exec_ctx.executor, tokens[index + 2]) - if targets: - t = targets[0] - exec_ctx.position = (t.x, t.y, t.z) if hasattr(t, 'x') else exec_ctx.position - return await _execute_chain(ctx, exec_ctx, tokens, index + 3) - elif tokens[index + 1].lower() == "over": - # positioned over - anchor can be "feet" or "eyes" - if index + 2 >= len(tokens): - await ctx.reply("[PyMC] execute positioned over: 缺少锚点") - return FAILURE - # In vanilla, "over" adjusts position to the anchor point - anchor = tokens[index + 2].lower() - if anchor == "eyes" and exec_ctx.executor and hasattr(exec_ctx.executor, 'height'): - x, y, z = exec_ctx.position - exec_ctx.position = (x, y + getattr(exec_ctx.executor, 'eye_height', 1.62), z) - return await _execute_chain(ctx, exec_ctx, tokens, index + 3) - else: - if index + 3 >= len(tokens): - await ctx.reply("[PyMC] execute positioned: 需要 x y z") - return FAILURE - try: - from commands.arguments import parse_coordinate, resolve_coordinate - bx, by, bz = exec_ctx.position - x = resolve_coordinate(parse_coordinate(tokens[index + 1]), bx) - y = resolve_coordinate(parse_coordinate(tokens[index + 2]), by) - z = resolve_coordinate(parse_coordinate(tokens[index + 3]), bz) - exec_ctx.position = (x, y, z) - except ValueError: - await ctx.reply("[PyMC] execute positioned: 坐标格式无效") - return FAILURE - return await _execute_chain(ctx, exec_ctx, tokens, index + 4) - - # --- rotated / rotated as --- - if subcommand == "rotated": - if index + 1 >= len(tokens): - await ctx.reply("[PyMC] execute rotated: 缺少参数") - return FAILURE - if tokens[index + 1].lower() == "as": - if index + 2 >= len(tokens): - await ctx.reply("[PyMC] execute rotated as: 缺少目标") - return FAILURE - targets = resolve_selector(exec_ctx.server, exec_ctx.executor, tokens[index + 2]) - if targets: - t = targets[0] - exec_ctx.yaw = t.yaw if hasattr(t, 'yaw') else exec_ctx.yaw - exec_ctx.pitch = t.pitch if hasattr(t, 'pitch') else exec_ctx.pitch - return await _execute_chain(ctx, exec_ctx, tokens, index + 3) - else: - if index + 2 >= len(tokens): - await ctx.reply("[PyMC] execute rotated: 需要 yaw pitch") - return FAILURE - try: - exec_ctx.yaw = float(tokens[index + 1]) - exec_ctx.pitch = float(tokens[index + 2]) - except ValueError: - await ctx.reply("[PyMC] execute rotated: 旋转格式无效") - return FAILURE - return await _execute_chain(ctx, exec_ctx, tokens, index + 3) - - # --- align --- - if subcommand == "align": - if index + 1 >= len(tokens): - await ctx.reply("[PyMC] execute align: 缺少坐标轴") - return FAILURE - axes = tokens[index + 1].lower() - x, y, z = exec_ctx.position - if 'x' in axes: - x = math.floor(x) - if 'y' in axes: - y = math.floor(y) - if 'z' in axes: - z = math.floor(z) - exec_ctx.position = (x, y, z) - return await _execute_chain(ctx, exec_ctx, tokens, index + 2) - - # --- anchored --- - if subcommand == "anchored": - if index + 1 >= len(tokens): - await ctx.reply("[PyMC] execute anchored: 缺少锚点") - return FAILURE - anchor = tokens[index + 1].lower() - if anchor not in ("feet", "eyes"): - await ctx.reply("[PyMC] execute anchored: 锚点必须是 feet 或 eyes") - return FAILURE - exec_ctx.anchor = anchor - return await _execute_chain(ctx, exec_ctx, tokens, index + 2) - - # --- facing / facing entity --- - if subcommand == "facing": - if index + 1 >= len(tokens): - await ctx.reply("[PyMC] execute facing: 缺少参数") - return FAILURE - if tokens[index + 1].lower() == "entity": - if index + 3 >= len(tokens): - await ctx.reply("[PyMC] execute facing entity: 缺少目标或锚点") - return FAILURE - targets = resolve_selector(exec_ctx.server, exec_ctx.executor, tokens[index + 2]) - if targets: - t = targets[0] - if hasattr(t, 'x'): - tx, ty, tz = t.x, t.y, t.z - if tokens[index + 3].lower() == "eyes" and hasattr(t, 'height'): - ty += 1.62 - x, y, z = exec_ctx.position - dx, dy, dz = tx - x, ty - y, tz - z - h = math.sqrt(dx * dx + dz * dz) - if h > 0: - exec_ctx.yaw = math.degrees(math.atan2(-dx, dz)) - exec_ctx.pitch = -math.degrees(math.atan2(dy, h)) - return await _execute_chain(ctx, exec_ctx, tokens, index + 4) - else: - if index + 3 >= len(tokens): - await ctx.reply("[PyMC] execute facing: 需要 x y z") - return FAILURE - try: - from commands.arguments import parse_coordinate, resolve_coordinate - bx, by, bz = exec_ctx.position - fx = resolve_coordinate(parse_coordinate(tokens[index + 1]), bx) - fy = resolve_coordinate(parse_coordinate(tokens[index + 2]), by) - fz = resolve_coordinate(parse_coordinate(tokens[index + 3]), bz) - x, y, z = exec_ctx.position - dx, dy, dz = fx - x, fy - y, fz - z - h = math.sqrt(dx * dx + dz * dz) - if h > 0: - exec_ctx.yaw = math.degrees(math.atan2(-dx, dz)) - exec_ctx.pitch = -math.degrees(math.atan2(dy, h)) - except ValueError: - await ctx.reply("[PyMC] execute facing: 坐标格式无效") - return FAILURE - return await _execute_chain(ctx, exec_ctx, tokens, index + 4) - - # --- in --- - if subcommand == "in": - if index + 1 >= len(tokens): - await ctx.reply("[PyMC] execute in: 缺少维度") - return FAILURE - exec_ctx.dimension = tokens[index + 1].lower() - return await _execute_chain(ctx, exec_ctx, tokens, index + 2) - - # --- if / unless --- - if subcommand in ("if", "unless"): - if index + 1 >= len(tokens): - await ctx.reply(f"[PyMC] execute {subcommand}: 缺少条件") - return FAILURE - condition_type = tokens[index + 1].lower() - result, next_index = await _evaluate_condition(ctx, exec_ctx, condition_type, tokens, index + 2) - passed = (subcommand == "if" and result) or (subcommand == "unless" and not result) - if not passed: - return FAILURE - return await _execute_chain(ctx, exec_ctx, tokens, next_index) - - # --- store --- - if subcommand == "store": - if index + 1 >= len(tokens): - await ctx.reply("[PyMC] execute store: 缺少参数") - return FAILURE - store_type = tokens[index + 1].lower() - # Parse store target - store_info = {"type": store_type} - if store_type == "result" or store_type == "success": - if index + 2 >= len(tokens): - await ctx.reply("[PyMC] execute store: 缺少存储目标") - return FAILURE - target_type = tokens[index + 2].lower() - store_info["target_type"] = target_type - if target_type == "score": - if index + 5 >= len(tokens): - await ctx.reply("[PyMC] execute store score: 缺少参数") - return FAILURE - store_info["player"] = tokens[index + 3] - store_info["objective"] = tokens[index + 4] - exec_ctx.store_targets.append(store_info) - return await _execute_chain(ctx, exec_ctx, tokens, index + 5) - elif target_type == "bossbar": - if index + 4 >= len(tokens): - await ctx.reply("[PyMC] execute store bossbar: 缺少参数") - return FAILURE - store_info["id"] = tokens[index + 3] - store_info["value"] = tokens[index + 4].lower() - exec_ctx.store_targets.append(store_info) - return await _execute_chain(ctx, exec_ctx, tokens, index + 5) - elif target_type == "block": - # store result block - if index + 8 >= len(tokens): - await ctx.reply("[PyMC] execute store block: 缺少参数") - return FAILURE - store_info["x"] = tokens[index + 3] - store_info["y"] = tokens[index + 4] - store_info["z"] = tokens[index + 5] - store_info["path"] = tokens[index + 6] - store_info["datatype"] = tokens[index + 7] - store_info["scale"] = tokens[index + 8] if index + 8 < len(tokens) else "1" - exec_ctx.store_targets.append(store_info) - return await _execute_chain(ctx, exec_ctx, tokens, index + 9) - elif target_type == "entity": - # store result entity - if index + 7 >= len(tokens): - await ctx.reply("[PyMC] execute store entity: 缺少参数") - return FAILURE - store_info["target"] = tokens[index + 3] - store_info["path"] = tokens[index + 4] - store_info["datatype"] = tokens[index + 5] - store_info["scale"] = tokens[index + 6] if index + 6 < len(tokens) else "1" - exec_ctx.store_targets.append(store_info) - return await _execute_chain(ctx, exec_ctx, tokens, index + 7) - else: - next_idx = index + 3 - exec_ctx.store_targets.append(store_info) - return await _execute_chain(ctx, exec_ctx, tokens, next_idx) - await ctx.reply(f"[PyMC] execute store: 未知存储类型 {store_type}") - return FAILURE - - # --- on --- - if subcommand == "on": - # execute on - not fully implemented - if index + 1 >= len(tokens): - await ctx.reply("[PyMC] execute on: 缺少参数") - return FAILURE - return await _execute_chain(ctx, exec_ctx, tokens, index + 2) - - # --- summon --- - if subcommand == "summon": - # execute summon [pos] [nbt] - summon and set executor - if index + 1 >= len(tokens): - await ctx.reply("[PyMC] execute summon: 缺少实体类型") - return FAILURE - # Just pass through to the run subcommand with a summon command - command_str = ' '.join(tokens[index:]) - from commands import CommandManager - result = await ctx.server.command_manager.execute(exec_ctx.executor, command_str) - return result - - # --- run --- - if subcommand == "run": - if index + 1 >= len(tokens): - await ctx.reply("[PyMC] execute run: 缺少命令") - return FAILURE - # Join remaining tokens as the command to run - command_str = ' '.join(tokens[index + 1:]) - - # Temporarily modify sender position if needed - old_x = old_y = old_z = old_yaw = old_pitch = None - if exec_ctx.executor and hasattr(exec_ctx.executor, 'x'): - old_x, old_y, old_z = exec_ctx.executor.x, exec_ctx.executor.y, exec_ctx.executor.z - old_yaw, old_pitch = exec_ctx.executor.yaw, exec_ctx.executor.pitch - exec_ctx.executor.x, exec_ctx.executor.y, exec_ctx.executor.z = exec_ctx.position - exec_ctx.executor.yaw, exec_ctx.executor.pitch = exec_ctx.yaw, exec_ctx.pitch - - # Execute the command - from commands import CommandManager - result = await ctx.server.command_manager.execute(exec_ctx.executor, command_str) - - # Restore position - if old_x is not None and exec_ctx.executor: - exec_ctx.executor.x, exec_ctx.executor.y, exec_ctx.executor.z = old_x, old_y, old_z - exec_ctx.executor.yaw, exec_ctx.executor.pitch = old_yaw, old_pitch - - # Handle store targets - if exec_ctx.store_targets: - for store_info in exec_ctx.store_targets: - if store_info.get("target_type") == "score": - from commands.vanilla.scoreboard import get_scoreboard_manager - sb = get_scoreboard_manager() - try: - sb.set_score(store_info["objective"], store_info["player"], result) - except ValueError: - pass - - return result - - await ctx.reply(f"[PyMC] execute: 未知子命令 '{subcommand}'") - return FAILURE - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: execute <子命令> ...") - return FAILURE - - args_str = ' '.join(tokens[1:]) - sub_tokens = _tokenize_execute(args_str) - - exec_ctx = ExecuteContext(ctx.server, ctx.sender) - return await _execute_chain(ctx, exec_ctx, sub_tokens, 0) - - def _suggest(ctx: CommandContext) -> list[str]: - return ["as", "at", "positioned", "rotated", "align", "anchored", - "facing", "in", "if", "unless", "store", "on", "summon", "run"] - - cmd = Command( - name="execute", - description="执行命令链,可改变执行者、位置和条件", - usage="execute ...", - permission="command.execute", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) diff --git a/commands/vanilla/execute_cmd.py b/commands/vanilla/execute_cmd.py index 1a638eb..66390ab 100755 --- a/commands/vanilla/execute_cmd.py +++ b/commands/vanilla/execute_cmd.py @@ -9,10 +9,9 @@ import math import logging -from typing import Any -from commands.framework import Command, CommandContext, SUCCESS, FAILURE, ERROR -from commands.selector import resolve_selector, parse_selector, parse_int_range +from commands.framework import Command, CommandContext, SUCCESS, FAILURE +from commands.selector import resolve_selector, parse_int_range logger = logging.getLogger("PyMC.命令执行") @@ -109,7 +108,7 @@ async def _evaluate_condition(ctx: CommandContext, exec_ctx: ExecuteContext, con if condition_type == "score": if index + 3 >= len(tokens): return (False, index + 4) - from commands.vanilla.scoreboard import get_scoreboard_manager + from commands.vanilla.display import get_scoreboard_manager sb = get_scoreboard_manager() target_player = tokens[index] target_obj = tokens[index + 1] @@ -229,32 +228,6 @@ async def _evaluate_condition(ctx: CommandContext, exec_ctx: ExecuteContext, con return (False, index + 1) -def _skip_condition_tokens(tokens: list[str], index: int, condition_type: str) -> int: - """Skip past the tokens of a condition to find the next subcommand.""" - if condition_type == "entity": - return index + 1 - if condition_type == "score": - # score - # or score matches - if index + 2 < len(tokens): - op = tokens[index + 2] - if op == "matches": - return index + 4 - return index + 5 - return index + 4 - if condition_type == "block": - return index + 4 - if condition_type == "blocks": - return index + 13 # Rough estimate - if condition_type == "predicate": - return index + 1 - if condition_type == "function": - return index + 1 - if condition_type == "loaded": - return index + 3 - return index + 1 - - # ============================================================ # Execute chain processor # ============================================================ @@ -534,7 +507,6 @@ async def _execute_chain(ctx: CommandContext, exec_ctx: ExecuteContext, tokens: return FAILURE # Just pass through to the run subcommand with a summon command command_str = ' '.join(tokens[index:]) - from commands import CommandManager result = await ctx.server.command_manager.execute(exec_ctx.executor, command_str) return result @@ -555,7 +527,6 @@ async def _execute_chain(ctx: CommandContext, exec_ctx: ExecuteContext, tokens: exec_ctx.executor.yaw, exec_ctx.executor.pitch = exec_ctx.yaw, exec_ctx.pitch # Execute the command - from commands import CommandManager result = await ctx.server.command_manager.execute(exec_ctx.executor, command_str) # Restore position @@ -567,7 +538,7 @@ async def _execute_chain(ctx: CommandContext, exec_ctx: ExecuteContext, tokens: if exec_ctx.store_targets: for store_info in exec_ctx.store_targets: if store_info.get("target_type") == "score": - from commands.vanilla.scoreboard import get_scoreboard_manager + from commands.vanilla.display import get_scoreboard_manager sb = get_scoreboard_manager() try: sb.set_score(store_info["objective"], store_info["player"], result) diff --git a/commands/vanilla/fill.py b/commands/vanilla/fill.py deleted file mode 100755 index aa2df8a..0000000 --- a/commands/vanilla/fill.py +++ /dev/null @@ -1,74 +0,0 @@ -# ============================================================ -# PyMC - /fill Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.arguments import parse_coordinate, resolve_coordinate, parse_fill_mode, parse_mask_mode - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - from world.editing import resolve_block_state, fill_box_detailed - from handlers.play.blocks import _sync_world_edit - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if len(args) < 7: - await ctx.reply("[PyMC] 用法: fill <方块> [模式]") - return FAILURE - - bx, by, bz = 0.0, 100.0, 0.0 - if ctx.sender and hasattr(ctx.sender, 'x'): - bx, by, bz = ctx.sender.x, ctx.sender.y, ctx.sender.z - - try: - x1 = int(resolve_coordinate(parse_coordinate(args[0]), bx)) - y1 = int(resolve_coordinate(parse_coordinate(args[1]), by)) - z1 = int(resolve_coordinate(parse_coordinate(args[2]), bz)) - x2 = int(resolve_coordinate(parse_coordinate(args[3]), bx)) - y2 = int(resolve_coordinate(parse_coordinate(args[4]), by)) - z2 = int(resolve_coordinate(parse_coordinate(args[5]), bz)) - except (ValueError, IndexError): - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - - block_state = resolve_block_state(args[6]) - if block_state is None: - await ctx.reply(f"[PyMC] 未知方块: {args[6]}") - return FAILURE - - # Check for fill mode and mask mode - fill_mode = "replace" - arg_index = 7 - if len(args) > arg_index: - try: - fill_mode = parse_fill_mode(args[arg_index]) - arg_index += 1 - except ValueError: - # Might be a mask block for "replace" mode - if args[arg_index].lower() != "replace": - fill_mode = args[arg_index].lower() - arg_index += 1 - - volume = (abs(x2 - x1) + 1) * (abs(y2 - y1) + 1) * (abs(z2 - z1) + 1) - if volume > 32768: - await ctx.reply(f"[PyMC] fill 范围过大: {volume} 个方块,当前上限 32768") - return FAILURE - - changed, changed_chunks, changed_blocks = fill_box_detailed( - ctx.server, x1, y1, z1, x2, y2, z2, block_state - ) - - await _sync_world_edit(ctx.server, changed_chunks, changed_blocks) - await ctx.reply(f"[PyMC] 已填充 {changed} 个方块为 {args[6]}") - return SUCCESS - - cmd = Command( - name="fill", - description="填充区域方块", - usage="fill <方块> [模式]", - permission="command.fill", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/fillbiome.py b/commands/vanilla/fillbiome.py deleted file mode 100755 index cf9a73f..0000000 --- a/commands/vanilla/fillbiome.py +++ /dev/null @@ -1,72 +0,0 @@ -# ============================================================ -# PyMC - /fillbiome Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.arguments import parse_coordinate, resolve_coordinate - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if len(args) < 7: - await ctx.reply("[PyMC] 用法: fillbiome <生物群系>") - return FAILURE - - bx, by, bz = 0.0, 100.0, 0.0 - if ctx.sender and hasattr(ctx.sender, 'x'): - bx, by, bz = ctx.sender.x, ctx.sender.y, ctx.sender.z - - try: - x1 = int(resolve_coordinate(parse_coordinate(args[0]), bx)) - y1 = int(resolve_coordinate(parse_coordinate(args[1]), by)) - z1 = int(resolve_coordinate(parse_coordinate(args[2]), bz)) - x2 = int(resolve_coordinate(parse_coordinate(args[3]), bx)) - y2 = int(resolve_coordinate(parse_coordinate(args[4]), by)) - z2 = int(resolve_coordinate(parse_coordinate(args[5]), bz)) - except (ValueError, IndexError): - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - - biome_name = args[6].lower() - if ":" not in biome_name: - biome_name = f"minecraft:{biome_name}" - - # Apply biome to chunks in the region - # This modifies the biome data in affected chunks - min_cx, max_cx = min(x1, x2) >> 4, max(x1, x2) >> 4 - min_cz, max_cz = min(z1, z2) >> 4, max(z1, z2) >> 4 - - from world.biomes import BiomeSampler - biome_id = BiomeSampler.BIOME_NAME_TO_ID.get(biome_name) - - if biome_id is None: - await ctx.reply(f"[PyMC] 未知生物群系: {biome_name} (将记录但不立即应用)") - # Still record the change - await ctx.reply(f"[PyMC] 已标记区域 ({x1},{y1},{z1})-({x2},{y2},{z2}) 为 {biome_name}") - return SUCCESS - - # Modify biome data in chunks - changed_chunks = 0 - for cx in range(min_cx, max_cx + 1): - for cz in range(min_cz, max_cz + 1): - chunk_blocks = ctx.server.world_storage.load_generated_chunk(cx, cz) - if chunk_blocks is not None: - chunk_biomes = ctx.server.biome_sampler.build_chunk_biome_sections(cx, cz, chunk_blocks) - # Override biomes in the affected region - ctx.server.world_storage.save_generated_chunk(cx, cz, chunk_blocks, chunk_biomes) - changed_chunks += 1 - - await ctx.reply(f"[PyMC] 已将区域生物群系设置为 {biome_name} ({changed_chunks} 个区块受影响)") - return SUCCESS - - cmd = Command( - name="fillbiome", - description="设置区域生物群系", - usage="fillbiome <生物群系>", - permission="command.fillbiome", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/forceload.py b/commands/vanilla/forceload.py deleted file mode 100755 index 06632cb..0000000 --- a/commands/vanilla/forceload.py +++ /dev/null @@ -1,91 +0,0 @@ -# ============================================================ -# PyMC - /forceload Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE - - -# Force-loaded chunks -_forceloaded_chunks: set[tuple[int, int]] = {} # Will be set reference per-world - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: forceload [ ]") - return FAILURE - - action = args[0].lower() - - if action == "add": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: forceload add <区块X> <区块Z> [到区块X] [到区块Z]") - return FAILURE - try: - cx = int(args[1]) - cz = int(args[2]) - except ValueError: - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - - if len(args) >= 5: - try: - cx2 = int(args[3]) - cz2 = int(args[4]) - except ValueError: - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - # Add range - count = 0 - for x in range(min(cx, cx2), max(cx, cx2) + 1): - for z in range(min(cz, cz2), max(cz, cz2) + 1): - _forceloaded_chunks.add((x, z)) - count += 1 - await ctx.reply(f"[PyMC] 已强制加载 {count} 个区块") - else: - _forceloaded_chunks.add((cx, cz)) - await ctx.reply(f"[PyMC] 已强制加载区块 ({cx}, {cz})") - return SUCCESS - - if action == "remove": - if len(args) < 3: - if len(args) >= 2 and args[1].lower() == "all": - count = len(_forceloaded_chunks) - _forceloaded_chunks.clear() - await ctx.reply(f"[PyMC] 已移除所有强制加载区块 ({count} 个)") - return SUCCESS - await ctx.reply("[PyMC] 用法: forceload remove <区块X> <区块Z> | forceload remove all") - return FAILURE - try: - cx = int(args[1]) - cz = int(args[2]) - except ValueError: - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - _forceloaded_chunks.discard((cx, cz)) - await ctx.reply(f"[PyMC] 已移除区块 ({cx}, {cz}) 的强制加载") - return SUCCESS - - if action == "query": - if _forceloaded_chunks: - chunks = ", ".join(f"({x},{z})" for x, z in sorted(_forceloaded_chunks)[:20]) - more = f" ... 还有 {len(_forceloaded_chunks) - 20} 个" if len(_forceloaded_chunks) > 20 else "" - await ctx.reply(f"[PyMC] 强制加载区块: {chunks}{more}") - else: - await ctx.reply("[PyMC] 没有强制加载的区块") - return SUCCESS - - await ctx.reply("[PyMC] 用法: forceload ...") - return FAILURE - - cmd = Command( - name="forceload", - description="强制加载区块", - usage="forceload [<区块X> <区块Z>]", - permission="command.forceload", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/function.py b/commands/vanilla/function.py deleted file mode 100755 index 49a3753..0000000 --- a/commands/vanilla/function.py +++ /dev/null @@ -1,97 +0,0 @@ -# ============================================================ -# PyMC - /function Command -# Simple .mcfunction file support -# ============================================================ - -import os -import logging - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE - -logger = logging.getLogger("PyMC.函数") - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: function <函数名>") - return FAILURE - - function_name = args[0].replace(":", "/") - - # Look for .mcfunction files - # Standard datapack structure: world/datapacks//data//functions/.mcfunction - search_paths = [ - os.path.join("world", "datapacks"), - os.path.join("datapacks"), - "functions", - ] - - function_path = None - for base in search_paths: - # Try direct path - candidate = os.path.join(base, f"{function_name}.mcfunction") - if os.path.isfile(candidate): - function_path = candidate - break - - # Try within data directory - candidate = os.path.join(base, "data", f"{function_name}.mcfunction") - if os.path.isfile(candidate): - function_path = candidate - break - - # Search recursively - if os.path.isdir(base): - for root, dirs, files in os.walk(base): - for f in files: - if f.endswith(".mcfunction"): - rel = os.path.relpath(os.path.join(root, f), base) - if rel.replace("\\", "/").replace(".mcfunction", "") == function_name: - function_path = os.path.join(root, f) - break - if function_path: - break - - if function_path is None: - await ctx.reply(f"[PyMC] 未找到函数: {args[0]}") - return FAILURE - - # Read and execute each line - try: - with open(function_path, 'r', encoding='utf-8') as f: - lines = f.readlines() - except Exception as e: - await ctx.reply(f"[PyMC] 读取函数文件失败: {e}") - return FAILURE - - executed = 0 - for line_num, line in enumerate(lines, 1): - line = line.strip() - if not line or line.startswith("#"): - continue - - # Remove leading / - if line.startswith("/"): - line = line[1:] - - try: - result = await ctx.server.command_manager.execute(ctx.sender, line) - executed += 1 - except Exception as e: - logger.debug(f"Function {args[0]} line {line_num} error: {e}") - - await ctx.reply(f"[PyMC] 已执行函数 {args[0]} ({executed} 条命令)") - return SUCCESS - - cmd = Command( - name="function", - description="执行 .mcfunction 函数文件", - usage="function <函数名>", - permission="command.function", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/gamemode.py b/commands/vanilla/gamemode.py deleted file mode 100755 index ff1ba86..0000000 --- a/commands/vanilla/gamemode.py +++ /dev/null @@ -1,63 +0,0 @@ -# ============================================================ -# PyMC - /gamemode Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.arguments import parse_gamemode, GAMEMODE_NAMES - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - from handlers.play.join import _send_game_event - from handlers.play.chat import send_system_message - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - if ctx.sender is not None: - await ctx.reply(f"[PyMC] 当前游戏模式: {ctx.sender.gamemode}") - else: - await ctx.reply("[PyMC] 用法: gamemode <模式> [玩家]") - return SUCCESS - - mode_name = args[0].lower() - target = ctx.sender - - try: - mode, normalized = parse_gamemode(mode_name) - except ValueError: - await ctx.reply("[PyMC] 无效模式,可用值: survival, creative, adventure, spectator (或 s, c, a, sp)") - return FAILURE - - # Check for target player - if len(args) >= 2: - target = ctx.server.find_player(args[1]) - if target is None: - await ctx.reply(f"[PyMC] 未找到玩家: {args[1]}") - return FAILURE - elif ctx.sender is None: - await ctx.reply("[PyMC] 用法: gamemode <模式> <玩家>") - return FAILURE - - mode_names_cn = {0: "生存", 1: "创造", 2: "冒险", 3: "旁观"} - target.gamemode = normalized - await _send_game_event(target, 3, float(mode)) - await send_system_message(target, f"[PyMC] 游戏模式已切换为 {mode_names_cn.get(mode, '未知')}") - if ctx.sender is not target: - await ctx.reply(f"[PyMC] 已将 {target.username} 的游戏模式切换为 {mode_names_cn.get(mode, '未知')}") - return SUCCESS - - def _suggest(ctx: CommandContext) -> list[str]: - return ["survival", "creative", "adventure", "spectator"] - - cmd = Command( - name="gamemode", - description="切换游戏模式", - usage="gamemode [玩家]", - aliases=["gm"], - permission="command.gamemode", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) diff --git a/commands/vanilla/gamerule.py b/commands/vanilla/gamerule.py deleted file mode 100755 index 3e73bf9..0000000 --- a/commands/vanilla/gamerule.py +++ /dev/null @@ -1,64 +0,0 @@ -# ============================================================ -# PyMC - /gamerule Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - rules = getattr(ctx.server, "gamerules", {}) - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - # List all gamerules - summary = ", ".join( - f"{name}={str(value).lower()}" - for name, value in sorted(rules.items()) - ) - await ctx.reply(f"[PyMC] 游戏规则: {summary}") - return SUCCESS - - rule_name = args[0] - if rule_name not in rules: - known = ", ".join(sorted(rules.keys())) - await ctx.reply(f"[PyMC] 未知游戏规则: {rule_name},当前支持: {known}") - return FAILURE - - if len(args) == 1: - await ctx.reply(f"[PyMC] {rule_name} = {str(rules[rule_name]).lower()}") - return SUCCESS - - raw_value = args[1].lower() - current = rules[rule_name] - if isinstance(current, bool): - if raw_value not in {"true", "false"}: - await ctx.reply(f"[PyMC] {rule_name} 需要 true/false 值") - return FAILURE - value = raw_value == "true" - elif isinstance(current, int): - try: - value = int(raw_value) - except ValueError: - await ctx.reply(f"[PyMC] {rule_name} 需要整数值") - return FAILURE - if value < 0: - await ctx.reply(f"[PyMC] {rule_name} 不能为负数") - return FAILURE - else: - await ctx.reply(f"[PyMC] 不支持的游戏规则类型: {rule_name}") - return FAILURE - rules[rule_name] = value - await ctx.reply(f"[PyMC] 游戏规则 {rule_name} 已设置为 {str(value).lower()}") - return SUCCESS - - cmd = Command( - name="gamerule", - description="设置或查询游戏规则", - usage="gamerule [规则名] [值]", - permission="command.gamerule", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/give.py b/commands/vanilla/give.py index bfdd164..7a76ff8 100755 --- a/commands/vanilla/give.py +++ b/commands/vanilla/give.py @@ -94,7 +94,6 @@ async def _execute(ctx: CommandContext) -> int: target.inventory_state_id += 1 if slot is not None: # Send slot update - from handlers.play.join import _send_set_experience await ctx.reply(f"[PyMC] 已给予 {target.username} {item_name} x{count}") return SUCCESS except Exception as e: diff --git a/commands/vanilla/help.py b/commands/vanilla/help.py deleted file mode 100755 index 4953282..0000000 --- a/commands/vanilla/help.py +++ /dev/null @@ -1,43 +0,0 @@ -# ============================================================ -# PyMC - /help Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - cmd_name = ctx.arguments.get("command") - if cmd_name: - cmd = manager.get_command(cmd_name) - if cmd: - await ctx.reply(f"[PyMC] /{cmd.name}: {cmd.description}") - if cmd.usage: - await ctx.reply(f"[PyMC] 用法: {cmd.usage}") - return SUCCESS - await ctx.reply(f"[PyMC] 未知命令: /{cmd_name}") - return SUCCESS - - # Show available commands - available = manager.get_commands_for_sender(ctx.sender) - if ctx.sender is not None: - level = ctx.server.permissions.get_permission_level(ctx.sender.username) - await ctx.reply(f"[PyMC] 你的权限组: {level}") - - cmd_list = ", ".join(f"/{cmd.name}" for cmd in sorted(available, key=lambda c: c.name)) - await ctx.reply(f"[PyMC] 可用命令: {cmd_list}") - return SUCCESS - - def _suggest(ctx: CommandContext) -> list[str]: - return [f"/{cmd.name}" for cmd in manager.get_commands_for_sender(ctx.sender)] - - cmd = Command( - name="help", - description="显示可用命令列表", - usage="help [命令名]", - aliases=["?"], - permission="command.help", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) diff --git a/commands/vanilla/kill.py b/commands/vanilla/kill.py deleted file mode 100755 index 0aac97e..0000000 --- a/commands/vanilla/kill.py +++ /dev/null @@ -1,78 +0,0 @@ -# ============================================================ -# PyMC - /kill Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - from handlers.play.entities import broadcast_entity_remove - from network.connection import Connection - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - if ctx.sender is None: - await ctx.reply("[PyMC] 用法: kill <实体>") - return FAILURE - # Kill self - ctx.sender.health = 0.0 - from handlers.play.join import _send_update_health - await _send_update_health(ctx.sender) - await ctx.reply("[PyMC] 你已经死了") - return SUCCESS - - target_spec = args[0] - - # Use selector system - targets = resolve_selector(ctx.server, ctx.sender, target_spec) - if not targets: - # Maybe it's an entity ID - try: - entity_id = int(target_spec) - entity = ctx.server.entity_manager.remove_entity(entity_id) - if entity is not None: - await broadcast_entity_remove(ctx.server, [entity_id]) - await ctx.reply(f"[PyMC] 已移除实体 #{entity_id} ({entity.kind})") - return SUCCESS - await ctx.reply(f"[PyMC] 未找到实体: {entity_id}") - return FAILURE - except ValueError: - await ctx.reply(f"[PyMC] 未找到目标: {target_spec}") - return FAILURE - - # Kill all matched targets - killed_count = 0 - entity_ids = [] - for target in targets: - if isinstance(target, Connection): - target.health = 0.0 - from handlers.play.join import _send_update_health - await _send_update_health(target) - killed_count += 1 - else: - entity_ids.append(target.entity_id) - ctx.server.entity_manager.remove_entity(target.entity_id) - killed_count += 1 - - if entity_ids: - await broadcast_entity_remove(ctx.server, entity_ids) - - await ctx.reply(f"[PyMC] 已击杀 {killed_count} 个目标") - return SUCCESS - - def _suggest(ctx: CommandContext) -> list[str]: - return ["@a", "@p", "@e", "@s", "@r"] - - cmd = Command( - name="kill", - description="击杀实体", - usage="kill <目标>", - permission="command.kill", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) diff --git a/commands/vanilla/list.py b/commands/vanilla/list.py deleted file mode 100755 index d0907b8..0000000 --- a/commands/vanilla/list.py +++ /dev/null @@ -1,22 +0,0 @@ -# ============================================================ -# PyMC - /list Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - players = ctx.server.get_online_players() - names = ", ".join(p.username for p in players) if players else "无" - await ctx.reply(f"[PyMC] 在线玩家 ({len(players)}/{ctx.server.max_players}): {names}") - return SUCCESS - - cmd = Command( - name="list", - description="显示在线玩家列表", - usage="list", - permission="command.list", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/locate.py b/commands/vanilla/locate.py deleted file mode 100755 index 7bc9f8e..0000000 --- a/commands/vanilla/locate.py +++ /dev/null @@ -1,89 +0,0 @@ -# ============================================================ -# PyMC - /locate Command -# ============================================================ - -import math -import random - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.arguments import parse_locate_target - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: locate structure <类型> 或 locate biome <类型>") - return FAILURE - - # Parse: locate structure or locate biome - if len(args) >= 2 and args[0].lower() in ("structure", "biome"): - target_type = args[0].lower() - target_name = args[1].lower() - else: - # Auto-detect - target_type, target_name = parse_locate_target(args[0]) - if target_type == "structure" and len(args) >= 2: - target_name = args[1].lower() - target_type = args[0].lower() - - # Get base position - if ctx.sender and hasattr(ctx.sender, 'x'): - base_x, base_z = int(ctx.sender.x), int(ctx.sender.z) - else: - base_x, base_z = 0, 0 - - # Generate a plausible location - # In a full implementation, this would search world data for actual structures/biomes - # For now, we generate a deterministic but varied position - rng = random.Random(hash(target_name) ^ 0x5F3759DF) - - if target_type == "structure": - # Find a position with the structure - # Simplified: place at a random chunk within view distance - angle = rng.random() * math.tau - distance = rng.randint(100, 2000) - found_x = int(base_x + math.cos(angle) * distance) - found_z = int(base_z + math.sin(angle) * distance) - - # Snap to chunk boundary - found_x = (found_x >> 4) << 4 - found_z = (found_z >> 4) << 4 - - actual_distance = math.sqrt((found_x - base_x) ** 2 + (found_z - base_z) ** 2) - await ctx.reply(f"[PyMC] 最近的 {target_name} 位于 ({found_x}, ?, {found_z}) (距离 {actual_distance:.0f} 方块)") - else: - # Locate biome - angle = rng.random() * math.tau - distance = rng.randint(50, 1500) - found_x = int(base_x + math.cos(angle) * distance) - found_z = int(base_z + math.sin(angle) * distance) - - actual_distance = math.sqrt((found_x - base_x) ** 2 + (found_z - base_z) ** 2) - await ctx.reply(f"[PyMC] 最近的 {target_name} 生物群系位于 ({found_x}, ?, {found_z}) (距离 {actual_distance:.0f} 方块)") - - return SUCCESS - - def _suggest(ctx: CommandContext) -> list[str]: - from commands.arguments import STRUCTURE_TYPES, BIOME_NAMES - tokens = ctx.input_string.split() - if len(tokens) == 2: - return ["structure", "biome"] - if len(tokens) == 3: - if tokens[1].lower() == "structure": - return list(STRUCTURE_TYPES) - if tokens[1].lower() == "biome": - return list(BIOME_NAMES) - return [] - - cmd = Command( - name="locate", - description="定位最近的结构或生物群系", - usage="locate <名称>", - permission="command.locate", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) diff --git a/commands/vanilla/particle.py b/commands/vanilla/particle.py index b1a222c..7460235 100755 --- a/commands/vanilla/particle.py +++ b/commands/vanilla/particle.py @@ -4,7 +4,6 @@ from commands.framework import Command, CommandContext, SUCCESS, FAILURE from commands.arguments import parse_particle_name -from network.connection import Connection def register(manager): diff --git a/commands/vanilla/place.py b/commands/vanilla/place.py deleted file mode 100755 index 1733146..0000000 --- a/commands/vanilla/place.py +++ /dev/null @@ -1,82 +0,0 @@ -# ============================================================ -# PyMC - /place Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.arguments import parse_coordinate, resolve_coordinate - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: place <名称> [x] [y] [z]") - return FAILURE - - place_type = args[0].lower() - - if place_type == "structure": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: place structure <结构名> [x] [y] [z]") - return FAILURE - struct_name = args[1] - - bx, by, bz = 0.0, 100.0, 0.0 - if ctx.sender and hasattr(ctx.sender, 'x'): - bx, by, bz = ctx.sender.x, ctx.sender.y, ctx.sender.z - - x, y, z = bx, by, bz - if len(args) >= 5: - try: - x = resolve_coordinate(parse_coordinate(args[2]), bx) - y = resolve_coordinate(parse_coordinate(args[3]), by) - z = resolve_coordinate(parse_coordinate(args[4]), bz) - except ValueError: - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - - await ctx.reply(f"[PyMC] 已在 ({x:.0f}, {y:.0f}, {z:.0f}) 放置结构 {struct_name} (结构放置暂未完全实现)") - return SUCCESS - - if place_type == "feature": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: place feature <特性名> [x] [y] [z]") - return FAILURE - feature_name = args[1] - await ctx.reply(f"[PyMC] 已放置特性 {feature_name} (特性放置暂未完全实现)") - return SUCCESS - - if place_type == "jigsaw": - if len(args) < 5: - await ctx.reply("[PyMC] 用法: place jigsaw <池> <目标> <最大深度> [x] [y] [z]") - return FAILURE - await ctx.reply("[PyMC] jigsaw 放置暂未完全实现") - return SUCCESS - - if place_type == "template": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: place template <模板名> [x] [y] [z] [旋转] [镜像]") - return FAILURE - await ctx.reply("[PyMC] 模板放置暂未完全实现") - return SUCCESS - - await ctx.reply(f"[PyMC] 未知放置类型: {place_type}") - return FAILURE - - def _suggest(ctx: CommandContext) -> list[str]: - tokens = ctx.input_string.split() - if len(tokens) == 2: - return ["structure", "feature", "jigsaw", "template"] - return [] - - cmd = Command( - name="place", - description="放置结构、特性或模板", - usage="place <名称> [位置]", - permission="command.place", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) diff --git a/commands/vanilla/player.py b/commands/vanilla/player.py index c5e50f9..5ce1c5c 100755 --- a/commands/vanilla/player.py +++ b/commands/vanilla/player.py @@ -11,505 +11,11 @@ def register(manager): """Register all player-related commands.""" # --- /tp --- - async def _tp(ctx: CommandContext) -> int: - from handlers.play.join import _send_synchronize_position - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: /tp <目标> 或 /tp 或 /tp <玩家> 或 /tp <玩家> <目标玩家>") - return FAILURE - - sender = ctx.sender - target = sender - dest = None - - # Try to parse as: /tp (self teleport) - if len(args) >= 3: - first = args[0] - is_coord = first.startswith("~") or first.startswith("^") or _is_number(first) - - if is_coord and sender is not None: - # /tp - try: - from commands.arguments import parse_coordinate, resolve_coordinate - bx, by, bz = sender.x, sender.y, sender.z - x = resolve_coordinate(parse_coordinate(args[0]), bx) - y = resolve_coordinate(parse_coordinate(args[1]), by) - z = resolve_coordinate(parse_coordinate(args[2]), bz) - except (ValueError, IndexError): - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - - yaw = sender.yaw - pitch = sender.pitch - if len(args) >= 5: - try: - yaw = float(args[3]) - pitch = float(args[4]) - except ValueError: - pass - - target.x, target.y, target.z = x, y, z - target.yaw, target.pitch = yaw, pitch - await _send_synchronize_position(target) - await ctx.reply(f"[PyMC] 已传送到 ({x:.1f}, {y:.1f}, {z:.1f})") - return SUCCESS - - # Not a coordinate - first arg is a player/selector - targets = resolve_selector(ctx.server, sender, first) - if not targets: - await ctx.reply(f"[PyMC] 未找到目标: {first}") - return FAILURE - target = targets[0] - - # Check if remaining args are a destination player or coordinates - if len(args) >= 4: - second = args[1] - if _is_selector_or_player(second) and len(args) < 5: - dest_targets = resolve_selector(ctx.server, sender, second) - if not dest_targets: - await ctx.reply(f"[PyMC] 未找到目标: {second}") - return FAILURE - dest = dest_targets[0] - target.x, target.y, target.z = dest.x, dest.y, dest.z - target.yaw, target.pitch = dest.yaw, dest.pitch - else: - try: - from commands.arguments import parse_coordinate, resolve_coordinate - bx, by, bz = target.x, target.y, target.z - x = resolve_coordinate(parse_coordinate(args[1]), bx) - y = resolve_coordinate(parse_coordinate(args[2]), by) - z = resolve_coordinate(parse_coordinate(args[3]), bz) - except (ValueError, IndexError): - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - target.x, target.y, target.z = x, y, z - - yaw = target.yaw - pitch = target.pitch - if len(args) >= 6: - try: - yaw = float(args[4]) - pitch = float(args[5]) - except ValueError: - pass - target.yaw, target.pitch = yaw, pitch - - await _send_synchronize_position(target) - from network.connection import Connection - target_name = target.username if isinstance(target, Connection) else f"实体#{getattr(target, 'entity_id', '?')}" - await ctx.reply(f"[PyMC] 已将 {target_name} 传送到 ({target.x:.1f}, {target.y:.1f}, {target.z:.1f})") - return SUCCESS - - elif len(args) == 1: - if sender is None: - await ctx.reply("[PyMC] 控制台用法: tp <玩家> ") - return FAILURE - targets = resolve_selector(ctx.server, sender, args[0]) - if not targets: - await ctx.reply(f"[PyMC] 未找到目标: {args[0]}") - return FAILURE - dest = targets[0] - sender.x, sender.y, sender.z = dest.x, dest.y, dest.z - sender.yaw, sender.pitch = dest.yaw, dest.pitch - await _send_synchronize_position(sender) - from network.connection import Connection - dest_name = dest.username if isinstance(dest, Connection) else f"实体#{getattr(dest, 'entity_id', '?')}" - await ctx.reply(f"[PyMC] 已传送到 {dest_name}") - return SUCCESS - - elif len(args) == 2: - src_targets = resolve_selector(ctx.server, sender, args[0]) - if not src_targets: - await ctx.reply(f"[PyMC] 未找到源目标: {args[0]}") - return FAILURE - dest_targets = resolve_selector(ctx.server, sender, args[1]) - if not dest_targets: - await ctx.reply(f"[PyMC] 未找到目标: {args[1]}") - return FAILURE - target = src_targets[0] - dest = dest_targets[0] - target.x, target.y, target.z = dest.x, dest.y, dest.z - target.yaw, target.pitch = dest.yaw, dest.pitch - await _send_synchronize_position(target) - await ctx.reply(f"[PyMC] 已传送实体到目标位置") - return SUCCESS - - await ctx.reply("[PyMC] 用法: /tp <目标> 或 /tp ") - return FAILURE - - def _tp_suggest(ctx: CommandContext) -> list[str]: - from network.connection import Connection - players = ctx.server.get_online_players() - names = [p.username for p in players] - return names + ["@a", "@p", "@s", "@r"] - - cmd_tp = Command( - name="tp", - description="传送实体到指定位置或目标", - usage="tp | tp <目标> | tp <实体> <目标>", - aliases=["teleport"], - permission="command.tp", - category="player", - ) - cmd_tp._execute_func = _tp - cmd_tp._suggest_func = _tp_suggest - manager.register(cmd_tp) - # --- /gamemode --- - async def _gamemode(ctx: CommandContext) -> int: - from handlers.play.join import _send_game_event - from handlers.play.chat import send_system_message - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - if ctx.sender is not None: - await ctx.reply(f"[PyMC] 当前游戏模式: {ctx.sender.gamemode}") - else: - await ctx.reply("[PyMC] 用法: gamemode <模式> [玩家]") - return SUCCESS - - mode_name = args[0].lower() - target = ctx.sender - - try: - from commands.arguments import parse_gamemode - mode, normalized = parse_gamemode(mode_name) - except ValueError: - await ctx.reply("[PyMC] 无效模式,可用值: survival, creative, adventure, spectator (或 s, c, a, sp)") - return FAILURE - - if len(args) >= 2: - target = ctx.server.find_player(args[1]) - if target is None: - await ctx.reply(f"[PyMC] 未找到玩家: {args[1]}") - return FAILURE - elif ctx.sender is None: - await ctx.reply("[PyMC] 用法: gamemode <模式> <玩家>") - return FAILURE - - mode_names_cn = {0: "生存", 1: "创造", 2: "冒险", 3: "旁观"} - target.gamemode = normalized - await _send_game_event(target, 3, float(mode)) - await send_system_message(target, f"[PyMC] 游戏模式已切换为 {mode_names_cn.get(mode, '未知')}") - if ctx.sender is not target: - await ctx.reply(f"[PyMC] 已将 {target.username} 的游戏模式切换为 {mode_names_cn.get(mode, '未知')}") - return SUCCESS - - def _gamemode_suggest(ctx: CommandContext) -> list[str]: - return ["survival", "creative", "adventure", "spectator"] - - cmd_gamemode = Command( - name="gamemode", - description="切换游戏模式", - usage="gamemode [玩家]", - aliases=[], - permission="command.gamemode", - category="player", - ) - cmd_gamemode._execute_func = _gamemode - cmd_gamemode._suggest_func = _gamemode_suggest - manager.register(cmd_gamemode) - # --- /give --- - async def _give(ctx: CommandContext) -> int: - from network.connection import Connection - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: give <玩家> <物品> [数量]") - return FAILURE - - target = ctx.sender - target_spec = args[0] - if ctx.sender is None or target_spec != ctx.sender.username: - targets = resolve_selector(ctx.server, ctx.sender, target_spec) - if targets: - for t in targets: - if isinstance(t, Connection): - target = t - break - if target is None and ctx.sender is None: - await ctx.reply(f"[PyMC] 未找到玩家: {target_spec}") - return FAILURE - - if len(args) < 2: - await ctx.reply("[PyMC] 用法: give <玩家> <物品> [数量]") - return FAILURE - - item_name = args[1].lower() - if ":" not in item_name: - item_name = f"minecraft:{item_name}" - - count = 1 - if len(args) >= 3: - try: - count = int(args[2]) - count = max(1, min(64, count)) - except ValueError: - await ctx.reply("[PyMC] 数量格式无效") - return FAILURE - - if target is None: - await ctx.reply("[PyMC] 未找到目标玩家") - return FAILURE - - if hasattr(target, 'inventory_obj') and target.inventory_obj is not None: - try: - slot = target.inventory_obj.add_item(item_name, count) - target.inventory_state_id += 1 - if slot is not None: - await ctx.reply(f"[PyMC] 已给予 {target.username} {item_name} x{count}") - return SUCCESS - except Exception: - await ctx.reply(f"[PyMC] 已给予 {target.username} {item_name} x{count} (物品栏暂未完全同步)") - return SUCCESS - - await ctx.reply(f"[PyMC] 已给予 {target.username} {item_name} x{count}") - return SUCCESS - - def _give_suggest(ctx: CommandContext) -> list[str]: - from commands.vanilla.give import KNOWN_ITEMS - tokens = ctx.input_string.split() - if len(tokens) <= 2: - partial = tokens[1] if len(tokens) > 1 else "" - return [i for i in KNOWN_ITEMS if i.startswith(partial)] - return [] - - cmd_give = Command( - name="give", - description="给予玩家物品", - usage="give <玩家> <物品> [数量]", - permission="command.give", - category="player", - ) - cmd_give._execute_func = _give - cmd_give._suggest_func = _give_suggest - manager.register(cmd_give) - # --- /clear --- - async def _clear(ctx: CommandContext) -> int: - from network.connection import Connection - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - target = ctx.sender - item_filter = None - max_count = -1 - - if args: - targets = resolve_selector(ctx.server, ctx.sender, args[0]) - players = [t for t in targets if isinstance(t, Connection)] - if players: - target = players[0] - elif ctx.sender is None: - await ctx.reply(f"[PyMC] 未找到玩家: {args[0]}") - return FAILURE - - if len(args) >= 2: - item_filter = args[1].lower() - if ":" not in item_filter: - item_filter = f"minecraft:{item_filter}" - - if len(args) >= 3: - try: - max_count = int(args[2]) - except ValueError: - await ctx.reply("[PyMC] 数量格式无效") - return FAILURE - - if target is None: - await ctx.reply("[PyMC] 未指定目标玩家") - return FAILURE - - cleared = 0 - if hasattr(target, 'inventory_obj') and target.inventory_obj is not None: - cleared = target.inventory_obj.clear_items(item_filter=item_filter, max_count=max_count) - target.inventory_state_id += 1 - - if item_filter: - await ctx.reply(f"[PyMC] 已清除 {target.username} 的 {item_filter} x{cleared}") - else: - await ctx.reply(f"[PyMC] 已清除 {target.username} 的物品栏 (共 {cleared} 个物品)") - return SUCCESS - - cmd_clear = Command( - name="clear", - description="清除玩家物品栏", - usage="clear [玩家] [物品] [最大数量]", - permission="command.clear", - category="player", - ) - cmd_clear._execute_func = _clear - manager.register(cmd_clear) - # --- /kill --- - async def _kill(ctx: CommandContext) -> int: - from handlers.play.entities import broadcast_entity_remove - from network.connection import Connection - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - if ctx.sender is None: - await ctx.reply("[PyMC] 用法: kill <实体>") - return FAILURE - ctx.sender.health = 0.0 - from handlers.play.join import _send_update_health - await _send_update_health(ctx.sender) - await ctx.reply("[PyMC] 你已经死了") - return SUCCESS - - target_spec = args[0] - targets = resolve_selector(ctx.server, ctx.sender, target_spec) - if not targets: - try: - entity_id = int(target_spec) - entity = ctx.server.entity_manager.remove_entity(entity_id) - if entity is not None: - await broadcast_entity_remove(ctx.server, [entity_id]) - await ctx.reply(f"[PyMC] 已移除实体 #{entity_id} ({entity.kind})") - return SUCCESS - await ctx.reply(f"[PyMC] 未找到实体: {entity_id}") - return FAILURE - except ValueError: - await ctx.reply(f"[PyMC] 未找到目标: {target_spec}") - return FAILURE - - killed_count = 0 - entity_ids = [] - for target in targets: - if isinstance(target, Connection): - target.health = 0.0 - from handlers.play.join import _send_update_health - await _send_update_health(target) - killed_count += 1 - else: - entity_ids.append(target.entity_id) - ctx.server.entity_manager.remove_entity(target.entity_id) - killed_count += 1 - - if entity_ids: - await broadcast_entity_remove(ctx.server, entity_ids) - - await ctx.reply(f"[PyMC] 已击杀 {killed_count} 个目标") - return SUCCESS - - def _kill_suggest(ctx: CommandContext) -> list[str]: - return ["@a", "@p", "@e", "@s", "@r"] - - cmd_kill = Command( - name="kill", - description="击杀实体", - usage="kill <目标>", - permission="command.kill", - category="player", - ) - cmd_kill._execute_func = _kill - cmd_kill._suggest_func = _kill_suggest - manager.register(cmd_kill) - # --- /xp --- - async def _xp(ctx: CommandContext) -> int: - from handlers.play.join import _add_player_experience - from network.connection import Connection - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: xp <数量> [玩家] 或 xp set <玩家> <数量> [levels|points]") - return FAILURE - - sub = args[0].lower() - - if sub in ("set", "add"): - if len(args) < 3: - await ctx.reply(f"[PyMC] 用法: xp {sub} <玩家> <数量> [levels|points]") - return FAILURE - - targets = resolve_selector(ctx.server, ctx.sender, args[1]) - players = [t for t in targets if isinstance(t, Connection)] - if not players: - await ctx.reply(f"[PyMC] 未找到玩家: {args[1]}") - return FAILURE - - try: - amount = int(args[2]) - except ValueError: - await ctx.reply("[PyMC] 经验数量格式无效") - return FAILURE - - unit = "points" - if len(args) >= 4: - unit = args[3].lower() - - for player in players: - if unit == "levels": - if sub == "set": - player.experience_level = max(0, amount) - player.experience_progress = 0.0 - else: - player.experience_level = max(0, player.experience_level + amount) - else: - if sub == "add": - await _add_player_experience(player, amount) - elif sub == "set": - player.experience_total = max(0, amount) - - names = ", ".join(p.username for p in players) - action = "设置为" if sub == "set" else "添加了" - unit_cn = "级" if unit == "levels" else "点" - await ctx.reply(f"[PyMC] 已{action} {names} {abs(amount)} {unit_cn}经验") - return SUCCESS - - try: - amount = int(args[0]) - except ValueError: - await ctx.reply("[PyMC] 经验数量格式无效") - return FAILURE - - target = ctx.sender - if len(args) >= 2: - targets = resolve_selector(ctx.server, ctx.sender, args[1]) - players = [t for t in targets if isinstance(t, Connection)] - if players: - target = players[0] - elif ctx.sender is None: - await ctx.reply(f"[PyMC] 未找到玩家: {args[1]}") - return FAILURE - - if target is None: - await ctx.reply("[PyMC] 未指定目标") - return FAILURE - - if amount < 0: - await ctx.reply("[PyMC] 暂不支持扣除经验") - return FAILURE - - await _add_player_experience(target, amount) - await ctx.reply(f"[PyMC] 获得 {amount} 点经验") - return SUCCESS - - cmd_xp = Command( - name="xp", - description="设置或添加经验", - usage="xp <数量> [玩家] | xp <玩家> <数量> [levels|points]", - aliases=["experience"], - permission="command.xp", - category="player", - ) - cmd_xp._execute_func = _xp - manager.register(cmd_xp) - # --- /effect --- from commands.arguments import parse_effect_name, EFFECT_NAMES @@ -729,60 +235,6 @@ def _enchant_suggest(ctx: CommandContext) -> list[str]: # --- /damage --- - from commands.arguments import parse_damage_type - - async def _damage(ctx: CommandContext) -> int: - from handlers.play.join import _damage_player - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: damage <目标> <伤害值> [伤害类型]") - return FAILURE - - targets = resolve_selector(ctx.server, ctx.sender, args[0]) - players = [t for t in targets if isinstance(t, Connection)] - if not players: - if ctx.sender is None: - await ctx.reply(f"[PyMC] 未找到目标: {args[0]}") - return FAILURE - players = [ctx.sender] if isinstance(ctx.sender, Connection) else [] - - if len(args) < 2: - await ctx.reply("[PyMC] 用法: damage <目标> <伤害值> [伤害类型]") - return FAILURE - - try: - amount = float(args[1]) - except ValueError: - await ctx.reply("[PyMC] 伤害值格式无效") - return FAILURE - - damage_type = "generic" - if len(args) >= 3: - try: - damage_type = parse_damage_type(args[2]) - except ValueError: - damage_type = args[2] - - for player in players: - await _damage_player(player, max(0.0, amount), damage_type, ctx.server) - - names = ", ".join(p.username for p in players) - await ctx.reply(f"[PyMC] 已对 {names} 造成 {amount:.1f} 点{damage_type}伤害") - return SUCCESS - - cmd_damage = Command( - name="damage", - description="对实体造成伤害", - usage="damage <目标> <伤害值> [伤害类型]", - permission="command.damage", - category="player", - ) - cmd_damage._execute_func = _damage - manager.register(cmd_damage) - def _is_number(s: str) -> bool: try: @@ -792,5 +244,3 @@ def _is_number(s: str) -> bool: return False -def _is_selector_or_player(s: str) -> bool: - return s.startswith("@") or not _is_number(s) diff --git a/commands/vanilla/recipe.py b/commands/vanilla/recipe.py deleted file mode 100755 index fab7c1a..0000000 --- a/commands/vanilla/recipe.py +++ /dev/null @@ -1,48 +0,0 @@ -# ============================================================ -# PyMC - /recipe Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector -from network.connection import Connection - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if len(args) < 2: - await ctx.reply("[PyMC] 用法: recipe <目标> [配方名|*]") - return FAILURE - - action = args[0].lower() - if action not in ("give", "take"): - await ctx.reply(f"[PyMC] 未知操作: {action}") - return FAILURE - - targets = resolve_selector(ctx.server, ctx.sender, args[1]) - players = [t for t in targets if isinstance(t, Connection)] - if not players: - await ctx.reply(f"[PyMC] 未找到目标: {args[1]}") - return FAILURE - - recipe_name = args[2] if len(args) >= 3 else "*" - action_cn = "给予" if action == "give" else "移除" - - # Recipe system not fully implemented, acknowledge command - if recipe_name == "*": - await ctx.reply(f"[PyMC] 已{action_cn} {len(players)} 个玩家的所有配方") - else: - await ctx.reply(f"[PyMC] 已{action_cn} {len(players)} 个玩家配方: {recipe_name}") - - return SUCCESS - - cmd = Command( - name="recipe", - description="给予或移除配方", - usage="recipe <目标> [配方名|*]", - permission="command.recipe", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/ride.py b/commands/vanilla/ride.py deleted file mode 100755 index 558319c..0000000 --- a/commands/vanilla/ride.py +++ /dev/null @@ -1,76 +0,0 @@ -# ============================================================ -# PyMC - /ride Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if len(args) < 2: - await ctx.reply("[PyMC] 用法: ride <骑乘者> [坐骑]") - return FAILURE - - rider_targets = resolve_selector(ctx.server, ctx.sender, args[0]) - if not rider_targets: - await ctx.reply(f"[PyMC] 未找到骑乘者: {args[0]}") - return FAILURE - rider = rider_targets[0] - - action = args[1].lower() - - if action == "mount": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: ride <骑乘者> mount <坐骑>") - return FAILURE - mount_targets = resolve_selector(ctx.server, ctx.sender, args[2]) - if not mount_targets: - await ctx.reply(f"[PyMC] 未找到坐骑: {args[2]}") - return FAILURE - mount = mount_targets[0] - - # Store mount relationship in metadata - if hasattr(rider, 'metadata'): - rider.metadata["riding"] = mount.entity_id if hasattr(mount, 'entity_id') else id(mount) - if hasattr(mount, 'metadata'): - riders = mount.metadata.get("riders", []) - rider_id = rider.entity_id if hasattr(rider, 'entity_id') else id(rider) - if rider_id not in riders: - riders.append(rider_id) - mount.metadata["riders"] = riders - - # Position rider on top of mount - if hasattr(rider, 'x') and hasattr(mount, 'x'): - rider.x = mount.x - rider.y = mount.y + 1.0 - rider.z = mount.z - - from network.connection import Connection - from handlers.play.join import _send_synchronize_position - if isinstance(rider, Connection): - await _send_synchronize_position(rider) - - await ctx.reply("[PyMC] 已将实体骑乘到目标上") - return SUCCESS - - if action == "dismount": - if hasattr(rider, 'metadata'): - rider.metadata.pop("riding", None) - await ctx.reply("[PyMC] 已让实体下骑") - return SUCCESS - - await ctx.reply(f"[PyMC] 未知操作: {action}") - return FAILURE - - cmd = Command( - name="ride", - description="让实体骑乘或下骑", - usage="ride <骑乘者> [坐骑]", - permission="command.ride", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/schedule.py b/commands/vanilla/schedule.py deleted file mode 100755 index 6e5c139..0000000 --- a/commands/vanilla/schedule.py +++ /dev/null @@ -1,103 +0,0 @@ -# ============================================================ -# PyMC - /schedule Command -# Delayed and repeated command execution -# ============================================================ - -import asyncio -import logging -import time - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE - -logger = logging.getLogger("PyMC.调度") - - -# Active scheduled tasks -_scheduled_tasks: dict[str, asyncio.Task] = {} -_task_counter = 0 - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - global _task_counter - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: schedule function <函数> <时间> [append|replace]") - return FAILURE - - action = args[0].lower() - - if action == "function": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: schedule function <函数|命令> <时间> [append|replace]") - return FAILURE - - target = args[1] - time_str = args[2].lower() - replace_mode = True - if len(args) >= 4: - replace_mode = args[3].lower() != "append" - - # Parse time - try: - from commands.arguments import parse_time_value - delay_ticks = parse_time_value(time_str) - except ValueError: - await ctx.reply(f"[PyMC] 无效时间: {time_str}") - return FAILURE - - delay_seconds = delay_ticks / 20.0 # Convert ticks to seconds - - # Schedule the execution - _task_counter += 1 - task_id = f"schedule_{_task_counter}" - - async def _run_scheduled(): - await asyncio.sleep(delay_seconds) - try: - # Check if it's a function name or a direct command - if "." not in target and " " not in target: - # Assume function - await ctx.server.command_manager.execute(ctx.sender, f"function {target}") - else: - await ctx.server.command_manager.execute(ctx.sender, target) - except Exception as e: - logger.debug(f"Scheduled task error: {e}") - finally: - _scheduled_tasks.pop(task_id, None) - - task = asyncio.create_task(_run_scheduled()) - _scheduled_tasks[task_id] = task - - await ctx.reply(f"[PyMC] 已安排 {target} 在 {delay_ticks} tick 后执行") - return SUCCESS - - if action == "clear": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: schedule clear <函数|ID>") - return FAILURE - target = args[1] - # Cancel matching tasks - cancelled = 0 - for tid, task in list(_scheduled_tasks.items()): - if not task.done(): - task.cancel() - cancelled += 1 - _scheduled_tasks.clear() - await ctx.reply(f"[PyMC] 已取消 {cancelled} 个计划任务") - return SUCCESS - - await ctx.reply("[PyMC] 用法: schedule ...") - return FAILURE - - cmd = Command( - name="schedule", - description="延迟或重复执行命令", - usage="schedule function <命令> <时间> | schedule clear ", - permission="command.schedule", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/scoreboard.py b/commands/vanilla/scoreboard.py deleted file mode 100755 index 4bdd7bd..0000000 --- a/commands/vanilla/scoreboard.py +++ /dev/null @@ -1,477 +0,0 @@ -# ============================================================ -# PyMC - /scoreboard Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.arguments import parse_display_slot, parse_criteria - - -class ScoreboardManager: - """Manages scoreboard objectives and scores.""" - - def __init__(self): - self.objectives: dict[str, dict] = {} # name -> {criteria, display_name, display_slot} - self.scores: dict[str, dict[str, int]] = {} # objective_name -> {player_name -> score} - self.teams: dict[str, dict] = {} # team_name -> {display_name, color, prefix, suffix, friendly_fire, see_friendly, members} - self.display_slots: dict[str, str | None] = {} # slot -> objective_name - - def create_objective(self, name: str, criteria: str = "dummy", display_name: str = ""): - if name in self.objectives: - raise ValueError(f"Objective '{name}' already exists") - self.objectives[name] = { - "criteria": criteria, - "display_name": display_name or name, - } - self.scores[name] = {} - - def remove_objective(self, name: str): - if name not in self.objectives: - raise ValueError(f"Objective '{name}' does not exist") - del self.objectives[name] - self.scores.pop(name, None) - # Remove from display slots - for slot, obj in list(self.display_slots.items()): - if obj == name: - self.display_slots[slot] = None - - def set_score(self, objective: str, player: str, score: int): - if objective not in self.objectives: - raise ValueError(f"Objective '{objective}' does not exist") - self.scores[objective][player] = score - - def get_score(self, objective: str, player: str) -> int: - if objective not in self.objectives: - return 0 - return self.scores.get(objective, {}).get(player, 0) - - def add_score(self, objective: str, player: str, amount: int) -> int: - current = self.get_score(objective, player) - new_score = current + amount - self.set_score(objective, player, new_score) - return new_score - - def remove_score(self, objective: str, player: str) -> bool: - if objective not in self.scores: - return False - return self.scores[objective].pop(player, None) is not None - - def set_display(self, slot: str, objective: str | None): - if objective is not None and objective not in self.objectives: - raise ValueError(f"Objective '{objective}' does not exist") - self.display_slots[slot] = objective - - def list_objectives(self) -> list[tuple[str, str, str]]: - return [(name, obj["criteria"], obj["display_name"]) for name, obj in self.objectives.items()] - - def create_team(self, name: str, display_name: str = ""): - if name in self.teams: - raise ValueError(f"Team '{name}' already exists") - self.teams[name] = { - "display_name": display_name or name, - "color": "white", - "prefix": "", - "suffix": "", - "friendly_fire": True, - "see_friendly_invisibles": False, - "members": set(), - } - - def remove_team(self, name: str): - if name not in self.teams: - raise ValueError(f"Team '{name}' does not exist") - del self.teams[name] - - def join_team(self, team_name: str, member: str): - if team_name not in self.teams: - raise ValueError(f"Team '{team_name}' does not exist") - self.teams[team_name]["members"].add(member) - - def leave_team(self, team_name: str, member: str): - if team_name not in self.teams: - raise ValueError(f"Team '{team_name}' does not exist") - self.teams[team_name]["members"].discard(member) - - -# Global scoreboard instance -_scoreboard_manager = ScoreboardManager() - - -def get_scoreboard_manager() -> ScoreboardManager: - return _scoreboard_manager - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: scoreboard ...") - return FAILURE - - sb = _scoreboard_manager - category = args[0].lower() - - # === OBJECTIVES === - if category == "objectives": - if len(args) < 2: - # List objectives - objs = sb.list_objectives() - if not objs: - await ctx.reply("[PyMC] 没有记分板目标") - else: - for name, criteria, display in objs: - scores = sb.scores.get(name, {}) - await ctx.reply(f"[PyMC] {name}: {criteria} (显示名: {display}, {len(scores)} 个分数)") - return SUCCESS - - action = args[1].lower() - - if action == "add": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: scoreboard objectives add <名称> <条件> [显示名]") - return FAILURE - obj_name = args[2] - criteria = args[3].lower() if len(args) >= 4 else "dummy" - display_name = " ".join(args[4:]) if len(args) >= 5 else obj_name - try: - criteria = parse_criteria(criteria) - sb.create_objective(obj_name, criteria, display_name) - await ctx.reply(f"[PyMC] 已创建新记分板目标: {obj_name}") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "remove": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: scoreboard objectives remove <名称>") - return FAILURE - try: - sb.remove_objective(args[2]) - await ctx.reply(f"[PyMC] 已移除记分板目标: {args[2]}") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "setdisplay": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: scoreboard objectives setdisplay <位置> [目标]") - return FAILURE - try: - slot = parse_display_slot(args[2]) - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - obj_name = args[3] if len(args) >= 4 else None - try: - sb.set_display(slot, obj_name) - if obj_name: - await ctx.reply(f"[PyMC] 已将目标 {obj_name} 显示在 {slot}") - else: - await ctx.reply(f"[PyMC] 已清除 {slot} 的显示目标") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "list": - objs = sb.list_objectives() - if not objs: - await ctx.reply("[PyMC] 没有记分板目标") - else: - for name, criteria, display in objs: - await ctx.reply(f"[PyMC] - {name}: {criteria} ({display})") - return SUCCESS - - # === PLAYERS === - elif category == "players": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: scoreboard players ...") - return FAILURE - - action = args[1].lower() - - if action == "set": - if len(args) < 5: - await ctx.reply("[PyMC] 用法: scoreboard players set <目标> <目标名> <分数>") - return FAILURE - player = args[2] - obj_name = args[3] - try: - score = int(args[4]) - except ValueError: - await ctx.reply("[PyMC] 分数格式无效") - return FAILURE - try: - sb.set_score(obj_name, player, score) - await ctx.reply(f"[PyMC] 已将 {player} 的 {obj_name} 分数设置为 {score}") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "add": - if len(args) < 5: - await ctx.reply("[PyMC] 用法: scoreboard players add <目标> <目标名> <分数>") - return FAILURE - player = args[2] - obj_name = args[3] - try: - amount = int(args[4]) - except ValueError: - await ctx.reply("[PyMC] 分数格式无效") - return FAILURE - try: - new_score = sb.add_score(obj_name, player, amount) - await ctx.reply(f"[PyMC] {player} 的 {obj_name} 分数现在是 {new_score}") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "remove": - if len(args) < 5: - await ctx.reply("[PyMC] 用法: scoreboard players remove <目标> <目标名> <分数>") - return FAILURE - player = args[2] - obj_name = args[3] - try: - amount = int(args[4]) - except ValueError: - await ctx.reply("[PyMC] 分数格式无效") - return FAILURE - try: - new_score = sb.add_score(obj_name, player, -amount) - await ctx.reply(f"[PyMC] {player} 的 {obj_name} 分数现在是 {new_score}") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "get": - if len(args) < 4: - await ctx.reply("[PyMC] 用法: scoreboard players get <目标> <目标名>") - return FAILURE - player = args[2] - obj_name = args[3] - score = sb.get_score(obj_name, player) - await ctx.reply(f"[PyMC] {player} 的 {obj_name} 分数: {score}") - return SUCCESS - - if action == "reset": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: scoreboard players reset <目标> [目标名]") - return FAILURE - player = args[2] - if len(args) >= 4: - obj_name = args[3] - sb.remove_score(obj_name, player) - await ctx.reply(f"[PyMC] 已重置 {player} 的 {obj_name} 分数") - else: - for obj_name in list(sb.scores.keys()): - sb.remove_score(obj_name, player) - await ctx.reply(f"[PyMC] 已重置 {player} 的所有分数") - return SUCCESS - - if action == "list": - player = args[2] if len(args) >= 3 else None - if player: - found = [] - for obj_name, scores in sb.scores.items(): - if player in scores: - found.append(f"{obj_name}={scores[player]}") - if found: - await ctx.reply(f"[PyMC] {player} 的分数: {', '.join(found)}") - else: - await ctx.reply(f"[PyMC] {player} 没有任何分数") - else: - all_players = set() - for scores in sb.scores.values(): - all_players.update(scores.keys()) - if all_players: - await ctx.reply(f"[PyMC] 跟踪的实体: {', '.join(sorted(all_players))}") - else: - await ctx.reply("[PyMC] 没有被跟踪的实体") - return SUCCESS - - if action == "operation": - if len(args) < 6: - await ctx.reply("[PyMC] 用法: scoreboard players operation <目标> <目标名> <操作> <源> <源目标名>") - return FAILURE - target_player = args[2] - target_obj = args[3] - op = args[4] - source_player = args[5] - source_obj = args[6] if len(args) >= 7 else target_obj - - source_val = sb.get_score(source_obj, source_player) - target_val = sb.get_score(target_obj, target_player) - - if op == "+=": - result = target_val + source_val - elif op == "-=": - result = target_val - source_val - elif op == "*=": - result = target_val * source_val - elif op == "/=": - result = target_val // source_val if source_val != 0 else 0 - elif op == "%=": - result = target_val % source_val if source_val != 0 else 0 - elif op == "=": - result = source_val - elif op == "<": - result = min(target_val, source_val) - elif op == ">": - result = max(target_val, source_val) - elif op == "><": - # Swap - sb.set_score(target_obj, target_player, source_val) - sb.set_score(source_obj, source_player, target_val) - await ctx.reply(f"[PyMC] 已交换分数") - return SUCCESS - else: - await ctx.reply(f"[PyMC] 未知操作: {op}") - return FAILURE - - sb.set_score(target_obj, target_player, result) - await ctx.reply(f"[PyMC] {target_player} 的 {target_obj} = {result}") - return SUCCESS - - await ctx.reply(f"[PyMC] 未知子命令: scoreboard players {action}") - return FAILURE - - # === TEAMS === - elif category == "teams": - if len(args) < 2: - # List teams - if not sb.teams: - await ctx.reply("[PyMC] 没有队伍") - else: - for name, team in sb.teams.items(): - members = ", ".join(team["members"]) or "无" - await ctx.reply(f"[PyMC] {name} ({team['display_name']}): {members}") - return SUCCESS - - action = args[1].lower() - - if action == "add": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: scoreboard teams add <名称> [显示名]") - return FAILURE - team_name = args[2] - display_name = " ".join(args[3:]) if len(args) >= 4 else team_name - try: - sb.create_team(team_name, display_name) - await ctx.reply(f"[PyMC] 已创建队伍: {team_name}") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "remove": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: scoreboard teams remove <名称>") - return FAILURE - try: - sb.remove_team(args[2]) - await ctx.reply(f"[PyMC] 已移除队伍: {args[2]}") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "join": - if len(args) < 4: - await ctx.reply("[PyMC] 用法: scoreboard teams join <队伍> <成员>") - return FAILURE - try: - sb.join_team(args[2], args[3]) - await ctx.reply(f"[PyMC] 已将 {args[3]} 加入队伍 {args[2]}") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "leave": - if len(args) < 4: - await ctx.reply("[PyMC] 用法: scoreboard teams leave <队伍> <成员>") - return FAILURE - try: - sb.leave_team(args[2], args[3]) - await ctx.reply(f"[PyMC] 已将 {args[3]} 移出队伍 {args[2]}") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "list": - if len(args) >= 3: - team_name = args[2] - if team_name not in sb.teams: - await ctx.reply(f"[PyMC] 队伍不存在: {team_name}") - return FAILURE - members = ", ".join(sb.teams[team_name]["members"]) or "无" - await ctx.reply(f"[PyMC] 队伍 {team_name} 成员: {members}") - else: - for name, team in sb.teams.items(): - members = ", ".join(team["members"]) or "无" - await ctx.reply(f"[PyMC] {name} ({team['display_name']}): {members}") - return SUCCESS - - if action == "modify": - if len(args) < 5: - await ctx.reply("[PyMC] 用法: scoreboard teams modify <队伍> <属性> <值>") - return FAILURE - team_name = args[2] - if team_name not in sb.teams: - await ctx.reply(f"[PyMC] 队伍不存在: {team_name}") - return FAILURE - prop = args[3].lower() - value = args[4] - if prop == "color": - sb.teams[team_name]["color"] = value.lower() - elif prop == "displayname": - sb.teams[team_name]["display_name"] = value - elif prop == "prefix": - sb.teams[team_name]["prefix"] = value - elif prop == "suffix": - sb.teams[team_name]["suffix"] = value - elif prop == "friendlyfire": - sb.teams[team_name]["friendly_fire"] = value.lower() in ("true", "1") - else: - await ctx.reply(f"[PyMC] 未知队伍属性: {prop}") - return FAILURE - await ctx.reply(f"[PyMC] 已修改队伍 {team_name} 的 {prop}") - return SUCCESS - - await ctx.reply(f"[PyMC] 未知子命令: scoreboard teams {action}") - return FAILURE - - await ctx.reply(f"[PyMC] 用法: scoreboard ...") - return FAILURE - - def _suggest(ctx: CommandContext) -> list[str]: - tokens = ctx.input_string.split() - if len(tokens) == 2: - return ["objectives", "players", "teams"] - if len(tokens) == 3: - category = tokens[1].lower() - if category == "objectives": - return ["add", "remove", "setdisplay", "list"] - if category == "players": - return ["set", "add", "remove", "get", "reset", "list", "operation"] - if category == "teams": - return ["add", "remove", "join", "leave", "list", "modify"] - return [] - - cmd = Command( - name="scoreboard", - description="管理记分板", - usage="scoreboard ...", - permission="command.scoreboard", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) diff --git a/commands/vanilla/seed.py b/commands/vanilla/seed.py deleted file mode 100755 index c30110b..0000000 --- a/commands/vanilla/seed.py +++ /dev/null @@ -1,22 +0,0 @@ -# ============================================================ -# PyMC - /seed Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - seed = ctx.server.config.get("level-seed", "") - text = f"[PyMC] 世界种子: {seed if seed != '' else 0}" - await ctx.reply(text) - return SUCCESS - - cmd = Command( - name="seed", - description="显示世界种子", - usage="seed", - permission="command.seed", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/server.py b/commands/vanilla/server.py deleted file mode 100755 index f6d08c9..0000000 --- a/commands/vanilla/server.py +++ /dev/null @@ -1,310 +0,0 @@ -# ============================================================ -# PyMC - Server Administration Commands -# kick, ban, ban-ip, pardon, pardon-ip, op, deop, whitelist, -# say, me, msg -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector -from network.connection import Connection - - -def register(manager): - """Register all server administration commands.""" - - # --- /say --- - async def _say(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: say <消息>") - return FAILURE - message = ' '.join(tokens[1:]) - full_text = f"[Server] {message}" - ctx.server.broadcast_system_message(full_text) - return SUCCESS - - cmd_say = Command( - name="say", - description="广播服务器消息", - usage="say <消息>", - permission="command.say", - category="server", - ) - cmd_say._execute_func = _say - manager.register(cmd_say) - - # --- /me --- - async def _me(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: /me <动作>") - return FAILURE - action = ' '.join(tokens[1:]) - ctx.server.broadcast_system_message(f"* {ctx.source_name} {action}") - return SUCCESS - - cmd_me = Command( - name="me", - description="发送动作消息", - usage="me <动作>", - permission="command.me", - category="server", - ) - cmd_me._execute_func = _me - manager.register(cmd_me) - - # --- /msg --- - async def _msg(ctx: CommandContext) -> int: - from handlers.play.chat import send_system_message - - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 3: - await ctx.reply("[PyMC] 用法: /msg <玩家> <消息>") - return FAILURE - - target = ctx.server.find_player(tokens[1]) - if target is None: - await ctx.reply(f"[PyMC] 未找到玩家: {tokens[1]}") - return FAILURE - - message = ' '.join(tokens[2:]) - await send_system_message(target, f"[私聊] {ctx.source_name}: {message}") - if ctx.sender is not None and target != ctx.sender: - await send_system_message(ctx.sender, f"[私聊 -> {target.username}] {message}") - return SUCCESS - - cmd_msg = Command( - name="msg", - description="发送私聊消息", - usage="msg <玩家> <消息>", - aliases=["tell", "w"], - permission="command.msg", - category="server", - ) - cmd_msg._execute_func = _msg - manager.register(cmd_msg) - - # --- /kick --- - async def _kick(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: kick <玩家> [原因]") - return FAILURE - - target = ctx.server.find_player(tokens[1]) - if target is None: - await ctx.reply(f"[PyMC] 未找到玩家: {tokens[1]}") - return FAILURE - - reason = ' '.join(tokens[2:]) if len(tokens) >= 3 else "已被管理员移出服务器" - await target.disconnect(reason) - await ctx.reply(f"[PyMC] 已踢出 {target.username}: {reason}") - return SUCCESS - - cmd_kick = Command( - name="kick", - description="踢出玩家", - usage="kick <玩家> [原因]", - permission="command.kick", - category="server", - ) - cmd_kick._execute_func = _kick - manager.register(cmd_kick) - - # --- /ban --- - async def _ban(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: ban <玩家> [原因]") - return FAILURE - - reason = ' '.join(tokens[2:]) if len(tokens) >= 3 else "" - ctx.server.permissions.ban_player(tokens[1], reason) - target = ctx.server.find_player(tokens[1]) - if target is not None: - await target.disconnect(reason or "你已被封禁") - await ctx.reply(f"[PyMC] 已封禁玩家: {tokens[1]}") - return SUCCESS - - cmd_ban = Command( - name="ban", - description="封禁玩家", - usage="ban <玩家> [原因]", - permission="command.ban", - category="server", - ) - cmd_ban._execute_func = _ban - manager.register(cmd_ban) - - # --- /pardon --- - async def _pardon(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: pardon <玩家>") - return FAILURE - ctx.server.permissions.pardon_player(tokens[1]) - await ctx.reply(f"[PyMC] 已解除封禁: {tokens[1]}") - return SUCCESS - - cmd_pardon = Command( - name="pardon", - description="解除封禁", - usage="pardon <玩家>", - permission="command.ban", - category="server", - ) - cmd_pardon._execute_func = _pardon - manager.register(cmd_pardon) - - # --- /ban-ip --- - async def _ban_ip(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: ban-ip [原因]") - return FAILURE - - reason = ' '.join(tokens[2:]) if len(tokens) >= 3 else "" - ctx.server.permissions.ban_ip(tokens[1], reason) - for player in ctx.server.get_online_players(): - address = player.address.split(":")[0] - if address == tokens[1]: - await player.disconnect(reason or "你的 IP 已被封禁") - await ctx.reply(f"[PyMC] 已封禁 IP: {tokens[1]}") - return SUCCESS - - cmd_banip = Command( - name="ban-ip", - description="封禁 IP", - usage="ban-ip [原因]", - permission="command.ban", - category="server", - ) - cmd_banip._execute_func = _ban_ip - manager.register(cmd_banip) - - # --- /pardon-ip --- - async def _pardon_ip(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: pardon-ip ") - return FAILURE - ctx.server.permissions.pardon_ip(tokens[1]) - await ctx.reply(f"[PyMC] 已解除 IP 封禁: {tokens[1]}") - return SUCCESS - - cmd_pardonip = Command( - name="pardon-ip", - description="解除 IP 封禁", - usage="pardon-ip ", - permission="command.ban", - category="server", - ) - cmd_pardonip._execute_func = _pardon_ip - manager.register(cmd_pardonip) - - # --- /banlist --- - async def _banlist(ctx: CommandContext) -> int: - banlist = ctx.server.permissions.get_banlist() - players = ", ".join(sorted(entry["name"] for entry in banlist["players"].values())) or "无" - ips = ", ".join(sorted(banlist["ips"].keys())) or "无" - await ctx.reply(f"[PyMC] 玩家封禁: {players}") - await ctx.reply(f"[PyMC] IP 封禁: {ips}") - return SUCCESS - - cmd_banlist = Command( - name="banlist", - description="查看封禁列表", - usage="banlist", - permission="command.ban", - category="server", - ) - cmd_banlist._execute_func = _banlist - manager.register(cmd_banlist) - - # --- /op --- - async def _op(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: op <玩家>") - return FAILURE - ctx.server.permissions.op(tokens[1]) - ctx.server.permissions.set_user_group(tokens[1], "admin") - await ctx.reply(f"[PyMC] 已授予 OP: {tokens[1]}") - return SUCCESS - - cmd_op = Command( - name="op", - description="授予 OP 权限", - usage="op <玩家>", - permission="command.op", - category="server", - ) - cmd_op._execute_func = _op - manager.register(cmd_op) - - # --- /deop --- - async def _deop(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - await ctx.reply("[PyMC] 用法: deop <玩家>") - return FAILURE - ctx.server.permissions.deop(tokens[1]) - ctx.server.permissions.set_user_group(tokens[1], "default") - await ctx.reply(f"[PyMC] 已移除 OP: {tokens[1]}") - return SUCCESS - - cmd_deop = Command( - name="deop", - description="移除 OP 权限", - usage="deop <玩家>", - permission="command.op", - category="server", - ) - cmd_deop._execute_func = _deop - manager.register(cmd_deop) - - # --- /whitelist --- - async def _whitelist(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) < 2: - whitelist = ctx.server.permissions.get_whitelist() - status = "开启" if whitelist["enabled"] else "关闭" - players = ", ".join(whitelist["players"]) or "无" - await ctx.reply(f"[PyMC] 白名单状态: {status}") - await ctx.reply(f"[PyMC] 白名单玩家: {players}") - return SUCCESS - - action = tokens[1].lower() - if action == "on": - ctx.server.permissions.set_whitelist_enabled(True) - await ctx.reply("[PyMC] 白名单已开启") - elif action == "off": - ctx.server.permissions.set_whitelist_enabled(False) - await ctx.reply("[PyMC] 白名单已关闭") - elif action == "list": - whitelist = ctx.server.permissions.get_whitelist() - players = ", ".join(whitelist["players"]) or "无" - await ctx.reply(f"[PyMC] 白名单玩家: {players}") - elif action == "add" and len(tokens) >= 3: - ctx.server.permissions.add_whitelist(tokens[2]) - await ctx.reply(f"[PyMC] 已加入白名单: {tokens[2]}") - elif action == "remove" and len(tokens) >= 3: - ctx.server.permissions.remove_whitelist(tokens[2]) - await ctx.reply(f"[PyMC] 已移除白名单: {tokens[2]}") - elif action == "reload": - ctx.server.permissions.load() - await ctx.reply("[PyMC] 白名单与权限文件已重载") - else: - await ctx.reply("[PyMC] 用法: whitelist ") - return FAILURE - return SUCCESS - - cmd_whitelist = Command( - name="whitelist", - description="管理白名单", - usage="whitelist ", - permission="command.whitelist", - category="server", - ) - cmd_whitelist._execute_func = _whitelist - manager.register(cmd_whitelist) diff --git a/commands/vanilla/setblock.py b/commands/vanilla/setblock.py deleted file mode 100755 index e683734..0000000 --- a/commands/vanilla/setblock.py +++ /dev/null @@ -1,54 +0,0 @@ -# ============================================================ -# PyMC - /setblock Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.arguments import parse_coordinate, resolve_coordinate - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - from world.editing import resolve_block_state, set_world_block - from handlers.play.blocks import _broadcast_block_change - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if len(args) < 4: - await ctx.reply("[PyMC] 用法: setblock <方块>") - return FAILURE - - bx, by, bz = 0.0, 100.0, 0.0 - if ctx.sender and hasattr(ctx.sender, 'x'): - bx, by, bz = ctx.sender.x, ctx.sender.y, ctx.sender.z - - try: - x = int(resolve_coordinate(parse_coordinate(args[0]), bx)) - y = int(resolve_coordinate(parse_coordinate(args[1]), by)) - z = int(resolve_coordinate(parse_coordinate(args[2]), bz)) - except (ValueError, IndexError): - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - - block_state = resolve_block_state(args[3]) - if block_state is None: - await ctx.reply(f"[PyMC] 未知方块: {args[3]}") - return FAILURE - - changed_chunks = set_world_block(ctx.server, x, y, z, block_state) - if not changed_chunks: - await ctx.reply("[PyMC] 方块位置超出世界范围") - return FAILURE - - await _broadcast_block_change(ctx.server, x, y, z, block_state) - await ctx.reply(f"[PyMC] 已设置方块 ({x}, {y}, {z}) -> {args[3]}") - return SUCCESS - - cmd = Command( - name="setblock", - description="设置单个方块", - usage="setblock <方块>", - permission="command.setblock", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/spreadplayers.py b/commands/vanilla/spreadplayers.py deleted file mode 100755 index f07991c..0000000 --- a/commands/vanilla/spreadplayers.py +++ /dev/null @@ -1,75 +0,0 @@ -# ============================================================ -# PyMC - /spreadplayers Command -# ============================================================ - -import math -import random - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector -from network.connection import Connection - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if len(args) < 4: - await ctx.reply("[PyMC] 用法: spreadplayers <最大距离> <是否尊重团队> <目标>") - return FAILURE - - try: - center_x = float(args[0]) - center_z = float(args[1]) - max_distance = float(args[2]) - respect_teams = args[3].lower() in ("true", "1", "yes") - except (ValueError, IndexError): - await ctx.reply("[PyMC] 参数格式无效") - return FAILURE - - if len(args) < 5: - await ctx.reply("[PyMC] 用法: spreadplayers <最大距离> <是否尊重团队> <目标>") - return FAILURE - - targets = resolve_selector(ctx.server, ctx.sender, args[4]) - players = [t for t in targets if isinstance(t, Connection)] - - if not players: - await ctx.reply(f"[PyMC] 未找到目标: {args[4]}") - return FAILURE - - from handlers.play.join import _send_synchronize_position - - spread_count = 0 - for player in players: - angle = random.random() * math.tau - radius = random.random() * max_distance - new_x = center_x + math.cos(angle) * radius - new_z = center_z + math.sin(angle) * radius - - # Find safe Y - terrain = getattr(ctx.server, 'terrain_generator', None) - if terrain: - try: - new_y = terrain.get_terrain_height(int(new_x), int(new_z)) + 2 - except Exception: - new_y = 100 - else: - new_y = 100 - - player.x, player.y, player.z = new_x, float(new_y), new_z - await _send_synchronize_position(player) - spread_count += 1 - - await ctx.reply(f"[PyMC] 已将 {spread_count} 个玩家分散在 ({center_x}, {center_z}) 附近") - return SUCCESS - - cmd = Command( - name="spreadplayers", - description="将玩家分散到区域中", - usage="spreadplayers <最大距离> <尊重团队> <目标>", - permission="command.spreadplayers", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/summon.py b/commands/vanilla/summon.py deleted file mode 100755 index a7ead59..0000000 --- a/commands/vanilla/summon.py +++ /dev/null @@ -1,86 +0,0 @@ -# ============================================================ -# PyMC - /summon Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.arguments import parse_coordinate, resolve_coordinate - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - from handlers.play.entities import broadcast_entity_spawn - from network.connection import Connection - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: summon <实体类型> [x] [y] [z] [NBT]") - return FAILURE - - entity_type = args[0].lower() - if ":" in entity_type: - entity_type = entity_type.split(":", 1)[1] - - # Parse coordinates - bx, by, bz = 0.0, 100.0, 0.0 - if ctx.sender and hasattr(ctx.sender, 'x'): - bx, by, bz = ctx.sender.x, ctx.sender.y, ctx.sender.z - - if len(args) >= 4: - try: - x = resolve_coordinate(parse_coordinate(args[1]), bx) - y = resolve_coordinate(parse_coordinate(args[2]), by) - z = resolve_coordinate(parse_coordinate(args[3]), bz) - except (ValueError, IndexError): - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - else: - x, y, z = bx, by, bz - - # Create entity based on type - entity = None - if entity_type == "experience_orb" or entity_type == "orb": - count = 1 - if len(args) >= 5: - try: - count = max(1, int(args[4])) - except ValueError: - pass - entity = ctx.server.entity_manager.create_experience_orb(x, y, z, count=count) - await broadcast_entity_spawn(ctx.server, entity) - await ctx.reply(f"[PyMC] 已生成经验球实体 #{entity.entity_id} x{count}") - elif entity_type == "item": - item_name = "minecraft:stone" - count = 1 - if len(args) >= 5: - item_name = args[4] - if ":" not in item_name: - item_name = f"minecraft:{item_name}" - if len(args) >= 6: - try: - count = max(1, int(args[5])) - except ValueError: - pass - entity = ctx.server.entity_manager.create_item(x, y, z, item_name=item_name, count=count) - await ctx.reply(f"[PyMC] 已生成 item 实体 #{entity.entity_id}: {item_name} x{count}") - elif entity_type in ("pig", "cow", "sheep", "zombie", "skeleton", "creeper", "spider"): - entity = ctx.server.entity_manager.create_mob(x, y, z, mob_type=entity_type) - await broadcast_entity_spawn(ctx.server, entity) - await ctx.reply(f"[PyMC] 已生成 {entity_type} 实体 #{entity.entity_id}") - else: - # Try to create a generic mob - entity = ctx.server.entity_manager.create_mob(x, y, z, mob_type=entity_type) - await broadcast_entity_spawn(ctx.server, entity) - await ctx.reply(f"[PyMC] 已生成 {entity_type} 实体 #{entity.entity_id}") - - return SUCCESS - - cmd = Command( - name="summon", - description="生成实体", - usage="summon <实体类型> [x] [y] [z] [NBT]", - permission="command.summon", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/tag.py b/commands/vanilla/tag.py deleted file mode 100755 index 3a011d7..0000000 --- a/commands/vanilla/tag.py +++ /dev/null @@ -1,81 +0,0 @@ -# ============================================================ -# PyMC - /tag Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector - - -# Tag storage: entity_id -> set of tags -_entity_tags: dict[int, set[str]] = {} - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if len(args) < 3: - await ctx.reply("[PyMC] 用法: tag <目标> <标签名>") - return FAILURE - - targets = resolve_selector(ctx.server, ctx.sender, args[0]) - if not targets: - await ctx.reply(f"[PyMC] 未找到目标: {args[0]}") - return FAILURE - - action = args[1].lower() - tag_name = args[2] if len(args) >= 3 else None - - if action == "add": - if not tag_name: - await ctx.reply("[PyMC] 用法: tag <目标> add <标签名>") - return FAILURE - for target in targets: - eid = getattr(target, 'entity_id', id(target)) - if eid not in _entity_tags: - _entity_tags[eid] = set() - # Also attach _tags attribute to the entity - _entity_tags[eid].add(tag_name) - if hasattr(target, '_tags'): - target._tags.add(tag_name) - else: - target._tags = {tag_name} - await ctx.reply(f"[PyMC] 已添加标签 '{tag_name}' 到 {len(targets)} 个实体") - return SUCCESS - - if action == "remove": - if not tag_name: - await ctx.reply("[PyMC] 用法: tag <目标> remove <标签名>") - return FAILURE - for target in targets: - eid = getattr(target, 'entity_id', id(target)) - if eid in _entity_tags: - _entity_tags[eid].discard(tag_name) - if hasattr(target, '_tags'): - target._tags.discard(tag_name) - await ctx.reply(f"[PyMC] 已移除标签 '{tag_name}' 从 {len(targets)} 个实体") - return SUCCESS - - if action == "list": - for target in targets: - eid = getattr(target, 'entity_id', id(target)) - tags = _entity_tags.get(eid, set()) - if hasattr(target, '_tags'): - tags = tags | target._tags - name = getattr(target, 'username', f"实体#{eid}") - tag_list = ", ".join(sorted(tags)) if tags else "无" - await ctx.reply(f"[PyMC] {name} 的标签: {tag_list}") - return SUCCESS - - await ctx.reply(f"[PyMC] 未知操作: {action}") - return FAILURE - - cmd = Command( - name="tag", - description="管理实体标签", - usage="tag <目标> <标签名>", - permission="command.tag", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/team.py b/commands/vanilla/team.py deleted file mode 100755 index 89b44de..0000000 --- a/commands/vanilla/team.py +++ /dev/null @@ -1,143 +0,0 @@ -# ============================================================ -# PyMC - /team Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.vanilla.scoreboard import get_scoreboard_manager - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - # Delegate to scoreboard teams - sb = get_scoreboard_manager() - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - # List teams - if not sb.teams: - await ctx.reply("[PyMC] 没有队伍") - else: - for name, team in sb.teams.items(): - members = ", ".join(team["members"]) or "无" - await ctx.reply(f"[PyMC] {name} ({team['display_name']}): {members}") - return SUCCESS - - action = args[0].lower() - - if action == "add": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: team add <名称> [显示名]") - return FAILURE - team_name = args[1] - display_name = " ".join(args[2:]) if len(args) >= 3 else team_name - try: - sb.create_team(team_name, display_name) - await ctx.reply(f"[PyMC] 已创建队伍: {team_name}") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "remove": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: team remove <名称>") - return FAILURE - try: - sb.remove_team(args[1]) - await ctx.reply(f"[PyMC] 已移除队伍: {args[1]}") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "join": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: team join <队伍> <成员>") - return FAILURE - try: - sb.join_team(args[1], args[2]) - await ctx.reply(f"[PyMC] 已将 {args[2]} 加入队伍 {args[1]}") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "leave": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: team leave <队伍> <成员>") - return FAILURE - try: - sb.leave_team(args[1], args[2]) - await ctx.reply(f"[PyMC] 已将 {args[2]} 移出队伍 {args[1]}") - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - return SUCCESS - - if action == "list": - if len(args) >= 2: - team_name = args[1] - if team_name not in sb.teams: - await ctx.reply(f"[PyMC] 队伍不存在: {team_name}") - return FAILURE - members = ", ".join(sb.teams[team_name]["members"]) or "无" - await ctx.reply(f"[PyMC] 队伍 {team_name} 成员: {members}") - else: - for name, team in sb.teams.items(): - members = ", ".join(team["members"]) or "无" - await ctx.reply(f"[PyMC] {name}: {members}") - return SUCCESS - - if action == "modify": - if len(args) < 4: - await ctx.reply("[PyMC] 用法: team modify <队伍> <属性> <值>") - return FAILURE - team_name = args[1] - if team_name not in sb.teams: - await ctx.reply(f"[PyMC] 队伍不存在: {team_name}") - return FAILURE - prop = args[2].lower() - value = args[3] - if prop == "color": - sb.teams[team_name]["color"] = value.lower() - elif prop == "displayname": - sb.teams[team_name]["display_name"] = value - elif prop == "prefix": - sb.teams[team_name]["prefix"] = value - elif prop == "suffix": - sb.teams[team_name]["suffix"] = value - elif prop == "friendlyfire": - sb.teams[team_name]["friendly_fire"] = value.lower() in ("true", "1") - elif prop == "seeFriendlyInvisibles": - sb.teams[team_name]["see_friendly_invisibles"] = value.lower() in ("true", "1") - else: - await ctx.reply(f"[PyMC] 未知属性: {prop}") - return FAILURE - await ctx.reply(f"[PyMC] 已修改队伍 {team_name} 的 {prop}") - return SUCCESS - - if action == "empty": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: team empty <队伍>") - return FAILURE - if args[1] not in sb.teams: - await ctx.reply(f"[PyMC] 队伍不存在: {args[1]}") - return FAILURE - count = len(sb.teams[args[1]]["members"]) - sb.teams[args[1]]["members"] = set() - await ctx.reply(f"[PyMC] 已清空队伍 {args[1]} ({count} 个成员)") - return SUCCESS - - await ctx.reply(f"[PyMC] 未知操作: {action}") - return FAILURE - - cmd = Command( - name="team", - description="管理队伍", - usage="team ...", - permission="command.team", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/tellraw.py b/commands/vanilla/tellraw.py deleted file mode 100755 index 3dc0496..0000000 --- a/commands/vanilla/tellraw.py +++ /dev/null @@ -1,62 +0,0 @@ -# ============================================================ -# PyMC - /tellraw Command -# Send JSON text components to players -# ============================================================ - -import json - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector -from commands.arguments import parse_text_component - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - from handlers.play.chat import send_system_message - from network.connection import Connection - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if len(args) < 2: - await ctx.reply("[PyMC] 用法: tellraw <目标> ") - return FAILURE - - target_spec = args[0] - message_str = ' '.join(args[1:]) - - # Parse the message component - try: - component = parse_text_component(message_str) - except Exception: - component = {"text": message_str} - - # Resolve targets - targets = resolve_selector(ctx.server, ctx.sender, target_spec) - players = [t for t in targets if isinstance(t, Connection)] - - if not players: - # Maybe it's a player name - player = ctx.server.find_player(target_spec) - if player: - players = [player] - - if not players: - await ctx.reply(f"[PyMC] 未找到目标: {target_spec}") - return FAILURE - - # Send the component as a system message - component_str = json.dumps(component, ensure_ascii=False) - for player in players: - await send_system_message(player, component_str) - - return SUCCESS - - cmd = Command( - name="tellraw", - description="发送 JSON 文本消息", - usage="tellraw <目标> ", - permission="command.tellraw", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/time_cmd.py b/commands/vanilla/time_cmd.py deleted file mode 100755 index df84889..0000000 --- a/commands/vanilla/time_cmd.py +++ /dev/null @@ -1,80 +0,0 @@ -# ============================================================ -# PyMC - /time Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.arguments import parse_time_value, TIME_PRESETS - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply(f"[PyMC] 当前时间: {ctx.server.world_time}") - return SUCCESS - - action = args[0].lower() - - if action == "set" and len(args) >= 2: - try: - value = parse_time_value(args[1]) - except ValueError: - await ctx.reply(f"[PyMC] 无效时间值: {args[1]}") - return FAILURE - ctx.server.world_time = value - ctx.server._time_manager.time = value - # Sync to all players - from handlers.play.join import _send_time_update - for player in ctx.server.get_online_players(): - await _send_time_update(player, ctx.server) - await ctx.reply(f"[PyMC] 世界时间已设置为 {value}") - return SUCCESS - - if action == "add" and len(args) >= 2: - try: - value = parse_time_value(args[1]) - except ValueError: - await ctx.reply(f"[PyMC] 无效时间值: {args[1]}") - return FAILURE - ctx.server.world_time += value - ctx.server._time_manager.time = ctx.server.world_time - # Sync to all players - from handlers.play.join import _send_time_update - for player in ctx.server.get_online_players(): - await _send_time_update(player, ctx.server) - await ctx.reply(f"[PyMC] 世界时间已变更为 {ctx.server.world_time}") - return SUCCESS - - if action == "query": - if len(args) >= 2 and args[1].lower() == "daytime": - await ctx.reply(f"[PyMC] 白天时间: {ctx.server.world_time % 24000}") - elif len(args) >= 2 and args[1].lower() == "day": - await ctx.reply(f"[PyMC] 天数: {ctx.server.world_time // 24000}") - else: - await ctx.reply(f"[PyMC] 世界时间: {ctx.server.world_time}") - return SUCCESS - - await ctx.reply("[PyMC] 用法: time <值>") - return FAILURE - - def _suggest(ctx: CommandContext) -> list[str]: - tokens = ctx.input_string.split() - if len(tokens) == 2: - return ["set", "add", "query"] - if len(tokens) == 3 and tokens[1] == "set": - return list(TIME_PRESETS.keys()) - if len(tokens) == 3 and tokens[1] == "query": - return ["daytime", "day", "gametime"] - return [] - - cmd = Command( - name="time", - description="设置或查询世界时间", - usage="time <值>", - permission="command.time", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) diff --git a/commands/vanilla/title.py b/commands/vanilla/title.py deleted file mode 100755 index cacdd12..0000000 --- a/commands/vanilla/title.py +++ /dev/null @@ -1,144 +0,0 @@ -# ============================================================ -# PyMC - /title Command -# Display titles, subtitles, and action bars -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector -from network.connection import Connection - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if len(args) < 2: - await ctx.reply("[PyMC] 用法: title <目标> <内容>") - return FAILURE - - target_spec = args[0] - action = args[1].lower() - - # Resolve targets - targets = resolve_selector(ctx.server, ctx.sender, target_spec) - players = [t for t in targets if isinstance(t, Connection)] - - if not players: - player = ctx.server.find_player(target_spec) - if player: - players = [player] - - if not players and action not in ("clear", "reset"): - await ctx.reply(f"[PyMC] 未找到目标: {target_spec}") - return FAILURE - - # Handle different title actions - if action == "clear": - for player in players: - await _send_title_clear(player, reset=False) - return SUCCESS - - if action == "reset": - for player in players: - await _send_title_clear(player, reset=True) - await _send_title_times(player, 10, 70, 20) - return SUCCESS - - if action == "times": - if len(args) < 5: - await ctx.reply("[PyMC] 用法: title <目标> times <淡入> <停留> <淡出>") - return FAILURE - try: - fade_in = int(args[2]) - stay = int(args[3]) - fade_out = int(args[4]) - except ValueError: - await ctx.reply("[PyMC] 时间格式无效(单位:tick)") - return FAILURE - for player in players: - await _send_title_times(player, fade_in, stay, fade_out) - return SUCCESS - - if action in ("title", "subtitle", "actionbar"): - if len(args) < 3: - await ctx.reply(f"[PyMC] 用法: title <目标> {action} <文本>") - return FAILURE - - from commands.arguments import parse_text_component - message_str = ' '.join(args[2:]) - try: - component = parse_text_component(message_str) - except Exception: - component = {"text": message_str} - - for player in players: - if action == "title": - await _send_title_text(player, component) - elif action == "subtitle": - await _send_title_subtitle(player, component) - elif action == "actionbar": - await _send_action_bar(player, component) - - return SUCCESS - - await ctx.reply(f"[PyMC] 未知操作: {action}. 可用: title, subtitle, actionbar, clear, reset, times") - return FAILURE - - def _suggest(ctx: CommandContext) -> list[str]: - tokens = ctx.input_string.split() - if len(tokens) == 3: - return ["title", "subtitle", "actionbar", "clear", "reset", "times"] - return [] - - cmd = Command( - name="title", - description="显示标题、副标题或动作栏文本", - usage="title <目标> <内容>", - permission="command.title", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) - - -async def _send_title_text(conn: Connection, component: dict): - """Send set_title_text packet (0x65 in 1.21.1).""" - from protocol.nbt import encode_nbt - payload = bytearray() - payload.extend(encode_nbt(component, with_type=True)) - await conn.send_packet(0x65, bytes(payload)) - - -async def _send_title_subtitle(conn: Connection, component: dict): - """Send set_title_subtitle packet (0x63 in 1.21.1).""" - from protocol.nbt import encode_nbt - payload = bytearray() - payload.extend(encode_nbt(component, with_type=True)) - await conn.send_packet(0x63, bytes(payload)) - - -async def _send_action_bar(conn: Connection, component: dict): - """Send action_bar packet (0x4C in 1.21.1).""" - from protocol.nbt import encode_nbt - payload = bytearray() - payload.extend(encode_nbt(component, with_type=True)) - await conn.send_packet(0x4C, bytes(payload)) - - -async def _send_title_clear(conn: Connection, reset: bool = False): - """Send clear_titles packet (0x0F in 1.21.1).""" - from protocol.data_types import write_boolean - payload = bytearray() - payload.extend(write_boolean(reset)) - await conn.send_packet(0x0F, bytes(payload)) - - -async def _send_title_times(conn: Connection, fade_in: int, stay: int, fade_out: int): - """Send set_title_time packet (0x66 in 1.21.1).""" - from protocol.data_types import write_int - payload = bytearray() - payload.extend(write_int(fade_in)) - payload.extend(write_int(stay)) - payload.extend(write_int(fade_out)) - await conn.send_packet(0x66, bytes(payload)) diff --git a/commands/vanilla/tp.py b/commands/vanilla/tp.py deleted file mode 100755 index 7837123..0000000 --- a/commands/vanilla/tp.py +++ /dev/null @@ -1,176 +0,0 @@ -# ============================================================ -# PyMC - /tp Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - from handlers.play.join import _send_synchronize_position - - tokens = ctx.arguments.get("_raw_tokens", []) - # Remove command name - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: /tp <目标> 或 /tp 或 /tp <玩家> 或 /tp <玩家> <目标玩家>") - return FAILURE - - sender = ctx.sender - - # Determine the target and destination - target = sender # Who to teleport - dest = None # Where to teleport to - - # Try to parse as: /tp (self teleport) - if len(args) >= 3: - # Check if first arg is a coordinate or selector - first = args[0] - is_coord = first.startswith("~") or first.startswith("^") or _is_number(first) - - if is_coord and sender is not None: - # /tp - try: - from commands.arguments import parse_coordinate, resolve_coordinate - bx, by, bz = sender.x, sender.y, sender.z - x = resolve_coordinate(parse_coordinate(args[0]), bx) - y = resolve_coordinate(parse_coordinate(args[1]), by) - z = resolve_coordinate(parse_coordinate(args[2]), bz) - except (ValueError, IndexError): - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - - # Check for rotation - yaw = sender.yaw - pitch = sender.pitch - if len(args) >= 5: - try: - yaw = float(args[3]) - pitch = float(args[4]) - except ValueError: - pass - - target.x, target.y, target.z = x, y, z - target.yaw, target.pitch = yaw, pitch - await _send_synchronize_position(target) - await ctx.reply(f"[PyMC] 已传送到 ({x:.1f}, {y:.1f}, {z:.1f})") - return SUCCESS - - # Not a coordinate - first arg is a player/selector - targets = resolve_selector(ctx.server, sender, first) - if not targets: - await ctx.reply(f"[PyMC] 未找到目标: {first}") - return FAILURE - target = targets[0] - - # Check if remaining args are a destination player or coordinates - if len(args) >= 4: - # Could be /tp or /tp - second = args[1] - if _is_selector_or_player(second) and len(args) < 5: - # /tp - dest_targets = resolve_selector(ctx.server, sender, second) - if not dest_targets: - await ctx.reply(f"[PyMC] 未找到目标: {second}") - return FAILURE - dest = dest_targets[0] - target.x, target.y, target.z = dest.x, dest.y, dest.z - target.yaw, target.pitch = dest.yaw, dest.pitch - else: - # /tp - try: - from commands.arguments import parse_coordinate, resolve_coordinate - bx, by, bz = target.x, target.y, target.z - x = resolve_coordinate(parse_coordinate(args[1]), bx) - y = resolve_coordinate(parse_coordinate(args[2]), by) - z = resolve_coordinate(parse_coordinate(args[3]), bz) - except (ValueError, IndexError): - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - target.x, target.y, target.z = x, y, z - - yaw = target.yaw - pitch = target.pitch - if len(args) >= 6: - try: - yaw = float(args[4]) - pitch = float(args[5]) - except ValueError: - pass - target.yaw, target.pitch = yaw, pitch - - await _send_synchronize_position(target) - from network.connection import Connection - target_name = target.username if isinstance(target, Connection) else f"实体#{getattr(target, 'entity_id', '?')}" - await ctx.reply(f"[PyMC] 已将 {target_name} 传送到 ({target.x:.1f}, {target.y:.1f}, {target.z:.1f})") - return SUCCESS - - elif len(args) == 1: - # /tp - teleport self to target - if sender is None: - await ctx.reply("[PyMC] 控制台用法: tp <玩家> ") - return FAILURE - targets = resolve_selector(ctx.server, sender, args[0]) - if not targets: - await ctx.reply(f"[PyMC] 未找到目标: {args[0]}") - return FAILURE - dest = targets[0] - sender.x, sender.y, sender.z = dest.x, dest.y, dest.z - sender.yaw, sender.pitch = dest.yaw, dest.pitch - await _send_synchronize_position(sender) - from network.connection import Connection - dest_name = dest.username if isinstance(dest, Connection) else f"实体#{getattr(dest, 'entity_id', '?')}" - await ctx.reply(f"[PyMC] 已传送到 {dest_name}") - return SUCCESS - - elif len(args) == 2: - # /tp - src_targets = resolve_selector(ctx.server, sender, args[0]) - if not src_targets: - await ctx.reply(f"[PyMC] 未找到源目标: {args[0]}") - return FAILURE - dest_targets = resolve_selector(ctx.server, sender, args[1]) - if not dest_targets: - await ctx.reply(f"[PyMC] 未找到目标: {args[1]}") - return FAILURE - target = src_targets[0] - dest = dest_targets[0] - target.x, target.y, target.z = dest.x, dest.y, dest.z - target.yaw, target.pitch = dest.yaw, dest.pitch - await _send_synchronize_position(target) - await ctx.reply(f"[PyMC] 已传送实体到目标位置") - return SUCCESS - - await ctx.reply("[PyMC] 用法: /tp <目标> 或 /tp ") - return FAILURE - - def _suggest(ctx: CommandContext) -> list[str]: - from network.connection import Connection - players = ctx.server.get_online_players() - names = [p.username for p in players] - return names + ["@a", "@p", "@s", "@r"] - - cmd = Command( - name="tp", - description="传送实体到指定位置或目标", - usage="tp | tp <目标> | tp <实体> <目标>", - aliases=["teleport"], - permission="command.tp", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) - - -def _is_number(s: str) -> bool: - try: - float(s) - return True - except ValueError: - return False - - -def _is_selector_or_player(s: str) -> bool: - return s.startswith("@") or not _is_number(s) diff --git a/commands/vanilla/trigger.py b/commands/vanilla/trigger.py deleted file mode 100755 index b49e425..0000000 --- a/commands/vanilla/trigger.py +++ /dev/null @@ -1,69 +0,0 @@ -# ============================================================ -# PyMC - /trigger Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.vanilla.scoreboard import get_scoreboard_manager - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - sb = get_scoreboard_manager() - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: trigger <目标> [add|set] <值>") - return FAILURE - - objective = args[0] - - if objective not in sb.objectives: - await ctx.reply(f"[PyMC] 目标 '{objective}' 不存在或不是 trigger 类型") - return FAILURE - - # Get player name - if ctx.sender is None: - await ctx.reply("[PyMC] 控制台无法使用 trigger 命令") - return FAILURE - player = ctx.sender.username - - action = "add" - value = 1 - - if len(args) >= 2: - action = args[1].lower() - if action in ("add", "set"): - if len(args) >= 3: - try: - value = int(args[2]) - except ValueError: - await ctx.reply("[PyMC] 值格式无效") - return FAILURE - else: - # First arg after objective is the value (implicit add) - try: - value = int(args[1]) - action = "add" - except ValueError: - await ctx.reply("[PyMC] 用法: trigger <目标> [add|set] <值>") - return FAILURE - - if action == "add": - new_score = sb.add_score(objective, player, value) - else: - new_score = value - sb.set_score(objective, player, value) - - await ctx.reply(f"[PyMC] {objective} for {player}: {new_score}") - return SUCCESS - - cmd = Command( - name="trigger", - description="修改 trigger 类型记分板目标", - usage="trigger <目标> [add|set] <值>", - permission="command.trigger", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/weather.py b/commands/vanilla/weather.py deleted file mode 100755 index 7bfac83..0000000 --- a/commands/vanilla/weather.py +++ /dev/null @@ -1,48 +0,0 @@ -# ============================================================ -# PyMC - /weather Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.arguments import parse_weather - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply(f"[PyMC] 当前天气: {ctx.server.weather}") - return SUCCESS - - try: - weather = parse_weather(args[0]) - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - - duration = 6000 - if len(args) >= 2: - try: - duration = int(args[1]) * 20 # Convert seconds to ticks - except ValueError: - pass - - # 走统一入口: 更新 TimeManager 持续时间并立即广播到客户端 - await ctx.server.set_weather(weather, duration) - - await ctx.reply(f"[PyMC] 天气已设置为 {weather}") - return SUCCESS - - def _suggest(ctx: CommandContext) -> list[str]: - return ["clear", "rain", "thunder"] - - cmd = Command( - name="weather", - description="设置天气", - usage="weather [持续时间(秒)]", - permission="command.weather", - ) - cmd._execute_func = _execute - cmd._suggest_func = _suggest - manager.register(cmd) diff --git a/commands/vanilla/world.py b/commands/vanilla/world.py index c43f068..9dfc030 100755 --- a/commands/vanilla/world.py +++ b/commands/vanilla/world.py @@ -6,9 +6,7 @@ from commands.framework import Command, CommandContext, SUCCESS, FAILURE from commands.arguments import ( - parse_time_value, TIME_PRESETS, parse_weather, parse_difficulty, - parse_coordinate, resolve_coordinate, parse_fill_mode, - parse_mask_mode, parse_clone_mode, + parse_coordinate, resolve_coordinate, parse_fill_mode, parse_clone_mode, ) @@ -16,159 +14,9 @@ def register(manager): """Register all world-related commands.""" # --- /time --- - async def _time(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply(f"[PyMC] 当前时间: {ctx.server.world_time}") - return SUCCESS - - action = args[0].lower() - - if action == "set" and len(args) >= 2: - try: - value = parse_time_value(args[1]) - except ValueError: - await ctx.reply(f"[PyMC] 无效时间值: {args[1]}") - return FAILURE - ctx.server.world_time = value - await ctx.reply(f"[PyMC] 世界时间已设置为 {value}") - return SUCCESS - - if action == "add" and len(args) >= 2: - try: - value = parse_time_value(args[1]) - except ValueError: - await ctx.reply(f"[PyMC] 无效时间值: {args[1]}") - return FAILURE - ctx.server.world_time += value - await ctx.reply(f"[PyMC] 世界时间已变更为 {ctx.server.world_time}") - return SUCCESS - - if action == "query": - if len(args) >= 2 and args[1].lower() == "daytime": - await ctx.reply(f"[PyMC] 白天时间: {ctx.server.world_time % 24000}") - elif len(args) >= 2 and args[1].lower() == "day": - await ctx.reply(f"[PyMC] 天数: {ctx.server.world_time // 24000}") - else: - await ctx.reply(f"[PyMC] 世界时间: {ctx.server.world_time}") - return SUCCESS - - await ctx.reply("[PyMC] 用法: time <值>") - return FAILURE - - def _time_suggest(ctx: CommandContext) -> list[str]: - tokens = ctx.input_string.split() - if len(tokens) == 2: - return ["set", "add", "query"] - if len(tokens) == 3 and tokens[1] == "set": - return list(TIME_PRESETS.keys()) - if len(tokens) == 3 and tokens[1] == "query": - return ["daytime", "day", "gametime"] - return [] - - cmd_time = Command( - name="time", - description="设置或查询世界时间", - usage="time <值>", - permission="command.time", - category="world", - ) - cmd_time._execute_func = _time - cmd_time._suggest_func = _time_suggest - manager.register(cmd_time) - # --- /weather --- - async def _weather(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply(f"[PyMC] 当前天气: {ctx.server.weather}") - return SUCCESS - - try: - weather = parse_weather(args[0]) - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - - ctx.server.weather = weather - duration = 6000 - if len(args) >= 2: - try: - duration = int(args[1]) * 20 - except ValueError: - pass - - await ctx.reply(f"[PyMC] 天气已设置为 {weather}") - return SUCCESS - - def _weather_suggest(ctx: CommandContext) -> list[str]: - return ["clear", "rain", "thunder"] - - cmd_weather = Command( - name="weather", - description="设置天气", - usage="weather [持续时间(秒)]", - permission="command.weather", - category="world", - ) - cmd_weather._execute_func = _weather - cmd_weather._suggest_func = _weather_suggest - manager.register(cmd_weather) - # --- /difficulty --- - async def _difficulty(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply(f"[PyMC] 当前难度: {ctx.server.config.get('difficulty', 'normal')}") - return SUCCESS - - try: - diff_int, diff_name = parse_difficulty(args[0]) - except ValueError as e: - await ctx.reply(f"[PyMC] {e}") - return FAILURE - - ctx.server.config["difficulty"] = diff_name - ctx.server.save_runtime_config() - await ctx.reply(f"[PyMC] 难度已设置为 {diff_name}") - return SUCCESS - - def _difficulty_suggest(ctx: CommandContext) -> list[str]: - return ["peaceful", "easy", "normal", "hard"] - - cmd_difficulty = Command( - name="difficulty", - description="设置游戏难度", - usage="difficulty ", - permission="command.difficulty", - category="world", - ) - cmd_difficulty._execute_func = _difficulty - cmd_difficulty._suggest_func = _difficulty_suggest - manager.register(cmd_difficulty) - # --- /seed --- - async def _seed(ctx: CommandContext) -> int: - seed = ctx.server.config.get("level-seed", "") - await ctx.reply(f"[PyMC] 世界种子: {seed if seed != '' else 0}") - return SUCCESS - - cmd_seed = Command( - name="seed", - description="显示世界种子", - usage="seed", - permission="command.seed", - category="world", - ) - cmd_seed._execute_func = _seed - manager.register(cmd_seed) - # --- /setblock --- async def _setblock(ctx: CommandContext) -> int: from world.editing import resolve_block_state, set_world_block @@ -373,86 +221,7 @@ async def _clone(ctx: CommandContext) -> int: manager.register(cmd_clone) # --- /setworldspawn --- - async def _setworldspawn(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - if len(tokens) >= 4: - try: - x = int(float(tokens[1])) - y = int(float(tokens[2])) - z = int(float(tokens[3])) - except ValueError: - await ctx.reply("[PyMC] 用法: setworldspawn ") - return FAILURE - else: - x = int(ctx.server.spawn_position[0]) - y = int(ctx.server.spawn_position[1]) - z = int(ctx.server.spawn_position[2]) - ctx.server.spawn_position = (x, y, z) - ctx.server.save_runtime_config() - await ctx.reply(f"[PyMC] 世界出生点已设置为 ({x}, {y}, {z})") - return SUCCESS - - cmd_sws = Command( - name="setworldspawn", - description="设置世界出生点", - usage="setworldspawn [x y z]", - permission="command.op", - category="world", - ) - cmd_sws._execute_func = _setworldspawn - manager.register(cmd_sws) - # --- /spawnpoint --- - async def _spawnpoint(ctx: CommandContext) -> int: - import math - tokens = ctx.arguments.get("_raw_tokens", []) - target = ctx.sender - coord_index = 1 - - if len(tokens) >= 2 and ctx.sender is None: - target = ctx.server.find_player(tokens[1]) - coord_index = 2 - if target is None: - await ctx.reply(f"[PyMC] 未找到玩家: {tokens[1]}") - return FAILURE - elif len(tokens) >= 2 and ctx.sender is not None: - maybe_target = ctx.server.find_player(tokens[1]) - if maybe_target is not None: - target = maybe_target - coord_index = 2 - - if target is None: - await ctx.reply("[PyMC] 用法: spawnpoint [玩家] [x y z]") - return FAILURE - - if len(tokens) >= coord_index + 3: - try: - spawn_x = int(float(tokens[coord_index])) - spawn_y = int(float(tokens[coord_index + 1])) - spawn_z = int(float(tokens[coord_index + 2])) - except ValueError: - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - else: - spawn_x = math.floor(target.x) - spawn_y = math.floor(target.y) - spawn_z = math.floor(target.z) - - target.personal_spawn = (spawn_x, spawn_y, spawn_z) - ctx.server.save_player_state(target) - await ctx.reply(f"[PyMC] 已将 {target.username or '玩家'} 的个人出生点设置为 ({spawn_x}, {spawn_y}, {spawn_z})") - return SUCCESS - - cmd_sp = Command( - name="spawnpoint", - description="设置个人出生点", - usage="spawnpoint [玩家] [x y z]", - permission="command.op", - category="world", - ) - cmd_sp._execute_func = _spawnpoint - manager.register(cmd_sp) - # --- /fillbiome --- async def _fillbiome(ctx: CommandContext) -> int: tokens = ctx.arguments.get("_raw_tokens", []) diff --git a/commands/vanilla/world_mgmt.py b/commands/vanilla/world_mgmt.py index 7595614..0193414 100755 --- a/commands/vanilla/world_mgmt.py +++ b/commands/vanilla/world_mgmt.py @@ -12,7 +12,6 @@ import math import os import random -from typing import Any from commands.framework import Command, CommandContext, SUCCESS, FAILURE from commands.selector import resolve_selector @@ -42,10 +41,6 @@ } -def get_world_border() -> dict: - return _world_border - - # ============================================================ # Force-loaded Chunks # ============================================================ @@ -68,12 +63,6 @@ def get_world_border() -> dict: _task_counter = 0 -# ============================================================ -# Advancement Tracking -# ============================================================ - -_advancements: dict[str, dict] = {} -_player_advancements: dict[str, dict[str, bool]] = {} # username -> {adv_name -> done} # ============================================================ @@ -722,11 +711,12 @@ async def _datapack(ctx: CommandContext) -> int: # /advancement # ======================================== async def _advancement(ctx: CommandContext) -> int: + from world.advancements import apply as apply_advancements, BY_KEY tokens = ctx.arguments.get("_raw_tokens", []) args = tokens[1:] if len(tokens) > 1 else [] if len(args) < 3: - await ctx.reply("[PyMC] 用法: advancement <目标> [进度名]") + await ctx.reply("[PyMC] 用法: advancement <目标> [进度名] [条件名]") return FAILURE action = args[0].lower() @@ -741,42 +731,24 @@ async def _advancement(ctx: CommandContext) -> int: return FAILURE mode = args[2].lower() + target = args[3] if len(args) >= 4 else None + criterion = args[4] if len(args) >= 5 else None + if mode != "everything" and target is None: + await ctx.reply(f"[PyMC] 用法: advancement {action} <目标> {mode} <进度名>") + return FAILURE + if target is not None and target.removeprefix("minecraft:") not in BY_KEY: + await ctx.reply(f"[PyMC] 未知进度: {target}") + return FAILURE - if mode == "everything": - count = 0 - for player in players: - if player.username not in _player_advancements: - _player_advancements[player.username] = {} - if action == "grant": - for adv_name in _advancements: - if not _player_advancements[player.username].get(adv_name): - _player_advancements[player.username][adv_name] = True - count += 1 - else: - count = len(_player_advancements[player.username]) - _player_advancements[player.username] = {} - action_cn = "授予" if action == "grant" else "撤销" - await ctx.reply(f"[PyMC] 已{action_cn} {len(players)} 个玩家的所有进度 ({count} 个)") - return SUCCESS - - if mode == "only": - if len(args) < 4: - await ctx.reply("[PyMC] 用法: advancement <目标> only <进度名>") + total = 0 + for player in players: + try: + total += await apply_advancements(ctx.server, player, action, mode, target, criterion) + except ValueError as e: + await ctx.reply(f"[PyMC] {e}") return FAILURE - adv_name = args[3] - count = 0 - for player in players: - if player.username not in _player_advancements: - _player_advancements[player.username] = {} - _player_advancements[player.username][adv_name] = (action == "grant") - count += 1 - action_cn = "授予" if action == "grant" else "撤销" - await ctx.reply(f"[PyMC] 已{action_cn} {len(players)} 个玩家进度: {adv_name}") - return SUCCESS - - adv_name = args[3] if len(args) >= 4 else "unknown" action_cn = "授予" if action == "grant" else "撤销" - await ctx.reply(f"[PyMC] 已{action_cn}进度: {adv_name} (from/through/until 模式暂简化处理)") + await ctx.reply(f"[PyMC] 已{action_cn} {len(players)} 个玩家的进度 ({total} 项变化)") return SUCCESS cmd_advancement = Command( diff --git a/commands/vanilla/worldborder.py b/commands/vanilla/worldborder.py deleted file mode 100755 index 3cd71f1..0000000 --- a/commands/vanilla/worldborder.py +++ /dev/null @@ -1,126 +0,0 @@ -# ============================================================ -# PyMC - /worldborder Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE - - -# Global world border state -_world_border = { - "center_x": 0.0, - "center_z": 0.0, - "size": 60000000.0, - "target_size": 60000000.0, - "speed": 0.0, - "damage_per_block": 0.2, - "damage_safe_zone": 5.0, - "warning_blocks": 5, - "warning_time": 15, -} - - -def get_world_border() -> dict: - return _world_border - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply(f"[PyMC] 世界边界大小: {_world_border['size']:.0f}") - return SUCCESS - - action = args[0].lower() - - if action == "set": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: worldborder set <大小> [时间(秒)]") - return FAILURE - try: - size = float(args[1]) - except ValueError: - await ctx.reply("[PyMC] 大小格式无效") - return FAILURE - _world_border["size"] = size - _world_border["target_size"] = size - await ctx.reply(f"[PyMC] 世界边界已设置为 {size}") - return SUCCESS - - if action == "center": - if len(args) < 3: - await ctx.reply("[PyMC] 用法: worldborder center ") - return FAILURE - try: - _world_border["center_x"] = float(args[1]) - _world_border["center_z"] = float(args[2]) - except ValueError: - await ctx.reply("[PyMC] 坐标格式无效") - return FAILURE - await ctx.reply(f"[PyMC] 世界边界中心已设置为 ({_world_border['center_x']}, {_world_border['center_z']})") - return SUCCESS - - if action == "damage": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: worldborder damage <值>") - return FAILURE - sub = args[1].lower() - if sub == "amount" and len(args) >= 3: - try: - _world_border["damage_per_block"] = float(args[2]) - except ValueError: - await ctx.reply("[PyMC] 伤害值格式无效") - return FAILURE - await ctx.reply(f"[PyMC] 边界伤害已设置为 {_world_border['damage_per_block']}") - elif sub == "buffer" and len(args) >= 3: - try: - _world_border["damage_safe_zone"] = float(args[2]) - except ValueError: - await ctx.reply("[PyMC] 缓冲区大小格式无效") - return FAILURE - await ctx.reply(f"[PyMC] 伤害缓冲区已设置为 {_world_border['damage_safe_zone']}") - else: - await ctx.reply("[PyMC] 用法: worldborder damage <值>") - return FAILURE - return SUCCESS - - if action == "warning": - if len(args) < 2: - await ctx.reply("[PyMC] 用法: worldborder warning <值>") - return FAILURE - sub = args[1].lower() - if sub == "time" and len(args) >= 3: - try: - _world_border["warning_time"] = int(args[2]) - except ValueError: - await ctx.reply("[PyMC] 时间格式无效") - return FAILURE - await ctx.reply(f"[PyMC] 警告时间已设置为 {_world_border['warning_time']} 秒") - elif sub == "distance" and len(args) >= 3: - try: - _world_border["warning_blocks"] = int(args[2]) - except ValueError: - await ctx.reply("[PyMC] 距离格式无效") - return FAILURE - await ctx.reply(f"[PyMC] 警告距离已设置为 {_world_border['warning_blocks']} 方块") - else: - await ctx.reply("[PyMC] 用法: worldborder warning <值>") - return FAILURE - return SUCCESS - - if action == "get": - await ctx.reply(f"[PyMC] 世界边界: 大小={_world_border['size']}, 中心=({_world_border['center_x']}, {_world_border['center_z']})") - return SUCCESS - - await ctx.reply("[PyMC] 用法: worldborder ...") - return FAILURE - - cmd = Command( - name="worldborder", - description="管理世界边界", - usage="worldborder ...", - permission="command.worldborder", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/commands/vanilla/xp.py b/commands/vanilla/xp.py deleted file mode 100755 index 2b85591..0000000 --- a/commands/vanilla/xp.py +++ /dev/null @@ -1,104 +0,0 @@ -# ============================================================ -# PyMC - /xp Command -# ============================================================ - -from commands.framework import Command, CommandContext, SUCCESS, FAILURE -from commands.selector import resolve_selector - - -def register(manager): - async def _execute(ctx: CommandContext) -> int: - from handlers.play.join import _add_player_experience - from network.connection import Connection - - tokens = ctx.arguments.get("_raw_tokens", []) - args = tokens[1:] if len(tokens) > 1 else [] - - if not args: - await ctx.reply("[PyMC] 用法: xp <数量> [玩家] 或 xp set <玩家> <数量> [levels|points]") - return FAILURE - - # Simple mode: /xp [player] - # Or: /xp set [levels|points] - # Or: /xp add [levels|points] - - sub = args[0].lower() - - if sub in ("set", "add"): - if len(args) < 3: - await ctx.reply(f"[PyMC] 用法: xp {sub} <玩家> <数量> [levels|points]") - return FAILURE - - targets = resolve_selector(ctx.server, ctx.sender, args[1]) - players = [t for t in targets if isinstance(t, Connection)] - if not players: - await ctx.reply(f"[PyMC] 未找到玩家: {args[1]}") - return FAILURE - - try: - amount = int(args[2]) - except ValueError: - await ctx.reply("[PyMC] 经验数量格式无效") - return FAILURE - - unit = "points" - if len(args) >= 4: - unit = args[3].lower() - - for player in players: - if unit == "levels": - if sub == "set": - player.experience_level = max(0, amount) - player.experience_progress = 0.0 - else: - player.experience_level = max(0, player.experience_level + amount) - else: # points - if sub == "add": - await _add_player_experience(player, amount) - elif sub == "set": - player.experience_total = max(0, amount) - - names = ", ".join(p.username for p in players) - action = "设置为" if sub == "set" else "添加了" - unit_cn = "级" if unit == "levels" else "点" - await ctx.reply(f"[PyMC] 已{action} {names} {abs(amount)} {unit_cn}经验") - return SUCCESS - - # Simple mode: /xp [player] - try: - amount = int(args[0]) - except ValueError: - await ctx.reply("[PyMC] 经验数量格式无效") - return FAILURE - - target = ctx.sender - if len(args) >= 2: - targets = resolve_selector(ctx.server, ctx.sender, args[1]) - players = [t for t in targets if isinstance(t, Connection)] - if players: - target = players[0] - elif ctx.sender is None: - await ctx.reply(f"[PyMC] 未找到玩家: {args[1]}") - return FAILURE - - if target is None: - await ctx.reply("[PyMC] 未指定目标") - return FAILURE - - if amount < 0: - await ctx.reply("[PyMC] 暂不支持扣除经验") - return FAILURE - - await _add_player_experience(target, amount) - await ctx.reply(f"[PyMC] 获得 {amount} 点经验") - return SUCCESS - - cmd = Command( - name="xp", - description="设置或添加经验", - usage="xp <数量> [玩家] | xp <玩家> <数量> [levels|points]", - aliases=["experience"], - permission="command.xp", - ) - cmd._execute_func = _execute - manager.register(cmd) diff --git a/config.py b/config.py index 40dd289..9ffb443 100755 --- a/config.py +++ b/config.py @@ -50,10 +50,9 @@ # ---- PyMC 扩展 ---- "debug": False, # 输出 DEBUG 级别日志 - "web-admin-enabled": True, - "web-admin-host": "127.0.0.1", - "web-admin-port": 25568, - "web-admin-allow-remote": False, + "chunk-decode-cache": 64, # 解码后的区块缓存数量 (每个约 1.2 MB) + "redstone-chunk-cache": 256, # 原生红石引擎保留在内存中的区块数 (每个约 196 KB) + "anvil-too-expensive-limit": True, # 铁砧费用达到 40 级时不能取 (原版); 关闭后不限制费用 "permissions-file": "permissions.json", "chunk-generation-multithreading": False, "chunk-generation-workers": 0, diff --git a/handlers/configuration.py b/handlers/configuration.py index d2f3a71..f04978f 100755 --- a/handlers/configuration.py +++ b/handlers/configuration.py @@ -8,12 +8,8 @@ from protocol.data_types import ( write_string, write_varint, write_boolean, write_identifier ) -from protocol.nbt import ( - encode_nbt, NbtByte, NbtFloat, NbtLong, NbtDouble -) from protocol.versions import has_configuration_phase from network.connection import Connection, ConnectionState -from world.biomes import build_biome_registry_entries logger = logging.getLogger("PyMC.配置") @@ -211,24 +207,6 @@ async def _send_tags(conn: Connection): await conn.send_packet(0x0D, _TAGS_PAYLOAD_CACHE) -async def _send_single_registry(conn: Connection, registry_id: str, - entries: dict): - """ - 发送单个注册表的 Registry Data 数据包 (0x07),条目为 Python dict。 - 供插件/Mod 追加自定义注册表条目使用。 - """ - payload = bytearray() - payload.extend(write_identifier(registry_id)) - payload.extend(write_varint(len(entries))) - - for entry_id, entry_data in entries.items(): - payload.extend(write_identifier(entry_id)) - payload.extend(write_boolean(True)) # 有数据 - payload.extend(encode_nbt(entry_data, with_type=True)) - - await conn.send_packet(0x07, bytes(payload)) - - async def _send_finish_configuration(conn: Connection): """发送 Finish Configuration 数据包 (0x03)。""" await conn.send_packet(0x03, b'') diff --git a/handlers/handshake.py b/handlers/handshake.py index 72867eb..f60142d 100755 --- a/handlers/handshake.py +++ b/handlers/handshake.py @@ -7,8 +7,7 @@ import logging from protocol.data_types import read_varint, read_string, read_ushort from protocol.versions import ( - is_supported, get_version_name, get_handler_version, - has_configuration_phase, NATIVE_PROTOCOL_VERSION + is_supported, get_version_name ) from network.connection import Connection, ConnectionState diff --git a/handlers/play/__init__.py b/handlers/play/__init__.py index 26f4c1f..d6802fc 100755 --- a/handlers/play/__init__.py +++ b/handlers/play/__init__.py @@ -296,6 +296,9 @@ async def handle_play(conn: Connection, packet_id: int, payload: bytes, await _handle_interact(conn, payload, server) elif name == "steer_vehicle": await _handle_steer_vehicle(conn, payload, server) + elif name == "enchant_item": + from world.enchanting_window import handle_enchant_button + await handle_enchant_button(conn, payload, server) elif name == "set_creative_mode_slot": await _handle_creative_inventory_action(conn, payload, server) from handlers.play.players import broadcast_player_equipment @@ -460,6 +463,10 @@ async def _handle_close_container(conn: Connection, payload: bytes, server=None) for part in getattr(view, "positions", (pos,)): container_manager.remove_viewer(*part, conn.entity_id) + from world.enchanting_window import return_inputs + from world.inventory_interactions import _drop_stack + for stack in return_inputs(conn, window_id): + await _drop_stack(conn, server, stack, stack.count) conn._open_entity_container = None conn._open_window_id = None conn._open_container_pos = None diff --git a/handlers/play/blocks.py b/handlers/play/blocks.py index 20e3d09..0632f20 100755 --- a/handlers/play/blocks.py +++ b/handlers/play/blocks.py @@ -29,8 +29,7 @@ GLASS, SAND, OAK_LOG, TORCH, ) from world.editing import ( - get_world_block, set_world_block, fill_box_detailed, - clone_box_detailed, resolve_block_state, + get_world_block, set_world_block, ) logger = logging.getLogger("PyMC.方块") @@ -140,10 +139,6 @@ def _load_chunk_for_edit(server, chunk_x: int, chunk_z: int): return _load_chunk_for_edit_impl(server, chunk_x, chunk_z) -def _set_world_block(server, x: int, y: int, z: int, block_state: int) -> bool: - return bool(set_world_block(server, x, y, z, block_state)) - - async def _refresh_chunks_for_players(server, chunk_coords: list[tuple[int, int]]): """将受影响区块重新编码并发给已加载这些区块的玩家。""" if not chunk_coords: @@ -193,7 +188,6 @@ def _get_held_item_for_placement(conn: Connection) -> tuple[int, str | None]: Get the block state ID the player is trying to place based on held item. Returns (block_state_id, item_name) or (0, None) if nothing to place. """ - from world.inventory import ItemStack from world.chunk_io import BLOCK_NAME_TO_DEFAULT_STATE inv = getattr(conn, 'inventory_obj', None) @@ -230,10 +224,8 @@ async def _handle_block_dig(conn: Connection, payload: bytes, server): """处理挖方块。集成物品栏和方块行为系统。""" from handlers.play.entities import broadcast_entity_spawn from world.block_behavior import ( - get_block_drops, get_block_name_from_state, get_block_hardness, - can_harvest_block, calculate_break_time, container_manager, + get_block_drops, get_block_hardness, container_manager, ) - from world.inventory import ItemStack from world.chunk_io import STATE_ID_TO_BLOCK offset = 0 @@ -478,32 +470,6 @@ async def _do_drop(): asyncio.create_task(_do_drop()) -def _get_tool_max_damage(item_id: str) -> int: - """Get the max damage (durability) for a tool.""" - _DURABILITY = { - "wooden_pickaxe": 59, "wooden_axe": 59, "wooden_shovel": 59, - "wooden_sword": 59, "wooden_hoe": 59, - "stone_pickaxe": 131, "stone_axe": 131, "stone_shovel": 131, - "stone_sword": 131, "stone_hoe": 131, - "iron_pickaxe": 250, "iron_axe": 250, "iron_shovel": 250, - "iron_sword": 250, "iron_hoe": 250, - "golden_pickaxe": 32, "golden_axe": 32, "golden_shovel": 32, - "golden_sword": 32, "golden_hoe": 32, - "diamond_pickaxe": 1561, "diamond_axe": 1561, "diamond_shovel": 1561, - "diamond_sword": 1561, "diamond_hoe": 1561, - "netherite_pickaxe": 2031, "netherite_axe": 2031, "netherite_shovel": 2031, - "netherite_sword": 2031, "netherite_hoe": 2031, - "leather_helmet": 55, "leather_chestplate": 80, "leather_leggings": 75, "leather_boots": 65, - "iron_helmet": 165, "iron_chestplate": 240, "iron_leggings": 225, "iron_boots": 195, - "golden_helmet": 77, "golden_chestplate": 112, "golden_leggings": 105, "golden_boots": 91, - "diamond_helmet": 363, "diamond_chestplate": 528, "diamond_leggings": 495, "diamond_boots": 429, - "netherite_helmet": 407, "netherite_chestplate": 592, "netherite_leggings": 555, "netherite_boots": 481, - "bow": 384, "crossbow": 326, "trident": 250, "shield": 336, - "shears": 238, "flint_and_steel": 64, "fishing_rod": 64, - } - return _DURABILITY.get(item_id, 0) - - def _is_replaceable(block_state: int) -> bool: """空气、流体和花草等可被直接替换的方块。""" if block_state == AIR: @@ -549,11 +515,6 @@ def _collides_with_player(server, x: int, y: int, z: int, block_state: int) -> b async def _handle_block_place(conn: Connection, payload: bytes, server): """处理方块放置和方块交互。集成物品栏和方块行为系统。""" - from world.block_behavior import ( - get_block_behavior, get_block_name_from_state, container_manager, - ) - from world.inventory import ItemStack - from world.chunk_io import STATE_ID_TO_BLOCK offset = 0 hand, offset = read_varint(payload, offset) @@ -579,7 +540,7 @@ async def _use_item_on(conn: Connection, server, hand: int, cursor: tuple[float, float, float] = (0.5, 0.5, 0.5)): """Use Item On 的实际逻辑: 方块交互优先, 其次放置手持方块。""" from world.block_behavior import ( - get_block_behavior, get_block_name_from_state, container_manager, + get_block_behavior, container_manager, ) from world.chunk_io import STATE_ID_TO_BLOCK @@ -739,6 +700,10 @@ async def _reject(): container_manager.get_or_create(place_x, place_y, place_z, "hopper") elif placed_name == "minecraft:brewing_stand": container_manager.get_or_create(place_x, place_y, place_z, "brewing_stand") + elif placed_name == "minecraft:enchanting_table": + container_manager.get_or_create(place_x, place_y, place_z, "enchanting_table") + elif placed_name.endswith("anvil"): + container_manager.get_or_create(place_x, place_y, place_z, "anvil") elif placed_name in ("minecraft:dropper", "minecraft:dispenser"): container_manager.get_or_create(place_x, place_y, place_z, placed_name.split(":")[1]) diff --git a/handlers/play/chat.py b/handlers/play/chat.py index 078acf3..5823490 100755 --- a/handlers/play/chat.py +++ b/handlers/play/chat.py @@ -15,16 +15,12 @@ - build_player_info_update / build_player_info_remove """ -import asyncio -import json import logging -import math from protocol.data_types import ( write_varint, write_string, write_boolean, write_uuid, ) -from protocol.nbt import encode_nbt from network.connection import Connection logger = logging.getLogger("PyMC.聊天") @@ -86,11 +82,6 @@ async def send_system_message(conn: Connection, text, overlay: bool = False): pid, build_system_message_payload(text, overlay, conn.protocol_version)) -async def send_action_bar(conn: Connection, text): - """在动作栏 (物品栏上方) 显示一条消息。""" - await send_system_message(conn, text, overlay=True) - - MAX_CHAT_LENGTH = 256 diff --git a/handlers/play/chunks.py b/handlers/play/chunks.py index 68e1cf1..b7fb8ab 100755 --- a/handlers/play/chunks.py +++ b/handlers/play/chunks.py @@ -33,7 +33,6 @@ build_flat_chunk_column, build_heightmap_data, ) from world.terrain import TerrainGenerator -from world.blocks import AIR, WATER logger = logging.getLogger("PyMC.区块") @@ -58,7 +57,6 @@ async def _send_chunk_data(conn: Connection, chunk_x: int, chunk_z: int): 发送 Chunk Data and Update Light 数据包 (0x27)。 (平坦世界版本) """ - from protocol.data_types import write_varint as _wv payload = bytearray() # Chunk X, Z (Int) diff --git a/handlers/play/combat.py b/handlers/play/combat.py index b1c0c94..900cdba 100644 --- a/handlers/play/combat.py +++ b/handlers/play/combat.py @@ -256,6 +256,9 @@ def damage_mob(server, entity, amount: float, source=None) -> bool: from world.loot import LootContext, loot_tables table = "entities/" + str(getattr(entity, "mob_type", "")).split(":")[-1] killer = source if source is not None and hasattr(source, "inventory_obj") else None + if killer is not None: + from world.advancements import on_mob_killed + on_mob_killed(killer, entity) if loot_tables.has(table): tool = None if killer is not None: diff --git a/handlers/play/entities.py b/handlers/play/entities.py index 42c1022..41065a6 100755 --- a/handlers/play/entities.py +++ b/handlers/play/entities.py @@ -22,7 +22,7 @@ from protocol.data_types import ( write_varint, write_double, write_short, - write_uuid, write_angle, write_boolean, write_ubyte, write_string, + write_uuid, write_angle, write_boolean, write_ubyte, ) from network.connection import Connection diff --git a/handlers/play/join.py b/handlers/play/join.py index 5e06772..f3c91f7 100755 --- a/handlers/play/join.py +++ b/handlers/play/join.py @@ -28,20 +28,13 @@ import math from protocol.data_types import ( - write_varint, write_string, write_boolean, write_int, write_long, - write_byte, write_ubyte, write_float, write_double, write_short, - write_uuid, write_identifier, write_position, write_angle, + write_varint, write_boolean, write_int, write_long, write_byte, + write_ubyte, write_float, write_double, write_identifier, write_position, ) -from protocol.nbt import encode_nbt, NbtLongArray from network.connection import Connection from world.blocks import ( - AIR, WATER, LAVA, GRASS_BLOCK, DIRT, COARSE_DIRT, PODZOL, - MOSS_BLOCK, SAND, RED_SAND, GRAVEL, SNOW_BLOCK, CLAY, STONE, - FIRE, SOUL_FIRE, CACTUS, WATER_CAULDRON, LAVA_CAULDRON, - MAGMA_BLOCK, CAMPFIRE, SOUL_CAMPFIRE, SWEET_BERRY_BUSH, - POWDER_SNOW, POWDER_SNOW_CAULDRON, SNOW, - SHORT_GRASS, TALL_GRASS, FERN, LARGE_FERN, DEAD_BUSH, - SEAGRASS, TALL_SEAGRASS, KELP, KELP_PLANT, SUGAR_CANE, BAMBOO, + WATER, LAVA, FIRE, SOUL_FIRE, CACTUS, WATER_CAULDRON, LAVA_CAULDRON, + MAGMA_BLOCK, CAMPFIRE, SOUL_CAMPFIRE, SWEET_BERRY_BUSH, POWDER_SNOW, POWDER_SNOW_CAULDRON, ) from world.editing import get_world_block @@ -49,17 +42,13 @@ _sorted_chunk_coords, _send_chunk_batch, _send_deferred_chunks, ) from handlers.play.spawn import ( - _resolve_initial_player_location, _resolve_player_respawn_location, - _is_suffocating_block, PASSABLE_BLOCKS, + _resolve_initial_player_location, _is_suffocating_block, ) from handlers.play.entities import ( - _send_visible_entities_to_player, _entity_within_tracking_range, - _send_experience_orb_spawn, _send_generic_entity_spawn, - broadcast_entity_spawn, broadcast_entity_remove, + _send_visible_entities_to_player, ) from handlers.play.chat import ( - build_system_message_payload, send_system_message, - build_player_info_update, build_player_info_remove, + build_player_info_update, ) logger = logging.getLogger("PyMC.游戏") @@ -156,6 +145,13 @@ async def send_join_game(conn: Connection, server): from commands.brigadier import send_commands await send_commands(conn, server) + # --- 1b. 进度 (1.12+ advancements): the tree and this player's progress --- + from world.advancements import on_join as send_advancements + try: + await send_advancements(server, conn) + except Exception: + logger.exception(f"发送 {conn.username} 的进度失败") + # --- 2. 解析出生位置 (存档位置不安全时回退到安全出生点) --- target_x, target_y, target_z = _resolve_initial_player_location( server, player_state diff --git a/handlers/play/spawn.py b/handlers/play/spawn.py index 32536be..5244853 100755 --- a/handlers/play/spawn.py +++ b/handlers/play/spawn.py @@ -18,17 +18,15 @@ from network.connection import Connection from world.blocks import ( - AIR, WATER, LAVA, GRASS_BLOCK, DIRT, COARSE_DIRT, PODZOL, - MOSS_BLOCK, SAND, RED_SAND, GRAVEL, SNOW_BLOCK, CLAY, STONE, - FIRE, SOUL_FIRE, CACTUS, WATER_CAULDRON, LAVA_CAULDRON, - MAGMA_BLOCK, CAMPFIRE, SOUL_CAMPFIRE, SWEET_BERRY_BUSH, - POWDER_SNOW, POWDER_SNOW_CAULDRON, SNOW, - SHORT_GRASS, TALL_GRASS, FERN, LARGE_FERN, DEAD_BUSH, - SEAGRASS, TALL_SEAGRASS, KELP, KELP_PLANT, SUGAR_CANE, BAMBOO, - OAK_LEAVES, SPRUCE_LEAVES, BIRCH_LEAVES, JUNGLE_LEAVES, - ACACIA_LEAVES, CHERRY_LEAVES, DARK_OAK_LEAVES, MANGROVE_LEAVES, - OAK_LOG, SPRUCE_LOG, BIRCH_LOG, JUNGLE_LOG, ACACIA_LOG, - CHERRY_LOG, DARK_OAK_LOG, MANGROVE_LOG, + AIR, WATER, LAVA, FIRE, SOUL_FIRE, CACTUS, WATER_CAULDRON, + LAVA_CAULDRON, MAGMA_BLOCK, CAMPFIRE, SOUL_CAMPFIRE, SWEET_BERRY_BUSH, POWDER_SNOW, POWDER_SNOW_CAULDRON, + SNOW, SHORT_GRASS, TALL_GRASS, FERN, LARGE_FERN, + DEAD_BUSH, SEAGRASS, TALL_SEAGRASS, KELP, + KELP_PLANT, SUGAR_CANE, BAMBOO, + OAK_LEAVES, SPRUCE_LEAVES, BIRCH_LEAVES, JUNGLE_LEAVES, ACACIA_LEAVES, + CHERRY_LEAVES, DARK_OAK_LEAVES, MANGROVE_LEAVES, OAK_LOG, SPRUCE_LOG, BIRCH_LOG, + JUNGLE_LOG, ACACIA_LOG, CHERRY_LOG, DARK_OAK_LOG, + MANGROVE_LOG, ) logger = logging.getLogger("PyMC.出生点") @@ -120,23 +118,6 @@ def _is_spawn_ground_block(block_id: int | None) -> bool: ) -def _spawn_candidate_from_column(chunk_blocks, local_x: int, local_z: int): - for y_index in range(len(chunk_blocks) - 3, 0, -1): - ground = chunk_blocks[y_index][local_z][local_x] - foot = chunk_blocks[y_index + 1][local_z][local_x] - head = chunk_blocks[y_index + 2][local_z][local_x] - if not _is_spawn_ground_block(ground): - continue - if not _is_spawn_clear_block(foot) or not _is_spawn_clear_block(head): - continue - return { - "block_id": ground, - "world_y": y_index - 64, - "spawn_y": y_index + 1 - 64, - } - return None - - def _resolve_spawn_location(server, block_x: int, block_z: int) -> tuple[int, int, int]: """ The nearest column around (x, z) where a player can stand safely diff --git a/handlers/play/state.py b/handlers/play/state.py index 704e756..20d407b 100644 --- a/handlers/play/state.py +++ b/handlers/play/state.py @@ -112,10 +112,6 @@ async def send_game_event(conn, event: int, value: float = 0.0): await _send(conn, "game_event", write_ubyte(event) + write_float(value)) -async def send_simulation_distance(conn, distance: int): - await _send(conn, "simulation_distance", write_varint(distance)) - - async def set_player_gamemode(server, conn, mode: str) -> bool: """ 切换玩家游戏模式并同步: diff --git a/handlers/player.py b/handlers/player.py index acf29eb..197dc66 100755 --- a/handlers/player.py +++ b/handlers/player.py @@ -20,9 +20,6 @@ import logging from typing import Optional -from protocol.data_types import ( - write_varint, write_boolean, write_short, write_byte, -) logger = logging.getLogger("PyMC.玩家状态") @@ -30,12 +27,8 @@ from world.inventory import ( ItemStack, PlayerInventory as NewPlayerInventory, - encode_slot_entry, build_set_container_content_payload as new_build_container_payload, build_set_slot_payload as new_build_slot_payload, - build_open_screen_payload, - item_name_to_protocol_id, - protocol_id_to_item_name, send_inventory_sync as new_send_inventory_sync, send_slot_update as new_send_slot_update, send_hotbar_update as new_send_hotbar_update, @@ -177,10 +170,6 @@ def get_item_in_slot(self, slot: int) -> dict | None: return {"item": item.item_id, "count": item.count} return None - def clear_slot(self, slot: int): - """清除指定槽位。""" - self._inv.set_slot(slot, None) - def add_item(self, item_name: str, count: int = 1) -> int: """ 尝试添加物品到物品栏,返回无法添加的数量。 @@ -232,38 +221,8 @@ def deserialize(cls, data: dict) -> 'PlayerInventory': # --- New API access --- - def get_new_inventory(self) -> NewPlayerInventory: - """Get the underlying new ItemStack-based inventory.""" - return self._inv - - def get_held_item_stack(self) -> ItemStack | None: - """Get the currently held item as an ItemStack.""" - return self._inv.get_held_item_from_slot(self._selected_slot) - - # --- Legacy encoding functions (kept for backward compat) --- -def _encode_slot_entry(item: Optional[tuple[str, int]]) -> bytes: - """ - 编码单个物品栏槽位 (legacy tuple format). - 新代码应使用 world.inventory.encode_slot_entry - """ - if item is None: - return write_boolean(False) - - item_name, count = item - stack = ItemStack(item_name, count) - return encode_slot_entry(stack) - - -def _item_name_to_protocol_id(item_name: str) -> int: - """ - 将物品命名空间 ID 转换为协议数值 ID。 - 新代码应使用 world.inventory.item_name_to_protocol_id - """ - return item_name_to_protocol_id(item_name) - - def build_set_container_content_payload( window_id: int, state_id: int, diff --git a/handlers/status.py b/handlers/status.py index 8c74cc8..616a283 100755 --- a/handlers/status.py +++ b/handlers/status.py @@ -6,7 +6,7 @@ import json import logging -from protocol.data_types import write_string, read_long, write_long +from protocol.data_types import write_string from protocol.versions import get_version_name, NATIVE_PROTOCOL_VERSION from network.connection import Connection diff --git a/handlers/versioned/base.py b/handlers/versioned/base.py index 00e9089..c285dde 100755 --- a/handlers/versioned/base.py +++ b/handlers/versioned/base.py @@ -8,6 +8,7 @@ Subclasses override methods to handle version differences. """ +from protocol.data_types import write_int, write_long, write_varint from protocol.nbt import encode_nbt, NbtLongArray @@ -38,11 +39,6 @@ def __init__(self, protocol_version: int | None = None): if protocol_version is not None: self.PROTOCOL_VERSION = protocol_version - def get_packet_map(self) -> dict: - """Return clientbound packet ID mappings for this version.""" - from protocol.packet_map import get_clientbound_map - return get_clientbound_map(self.PROTOCOL_VERSION) - def get_packet_id(self, packet_name: str) -> int | None: """Get a clientbound packet ID by name for this version.""" from protocol.packet_map import get_clientbound_packet @@ -66,13 +62,6 @@ def build_heightmap_nbt(self, motion_blocking, world_surface): } return encode_nbt(heightmap_nbt, with_type=True) - async def send_keep_alive(self, conn, keep_alive_id): - """Send a Keep Alive packet.""" - from protocol.data_types import write_long - pid = self.get_packet_id("keep_alive") - if pid is not None: - await conn.send_packet(pid, write_long(keep_alive_id)) - async def send_system_chat(self, conn, text, overlay=False): """Send a system chat message in this version's format. @@ -188,16 +177,6 @@ async def send_set_experience(self, conn): payload.extend(write_varint(conn.experience_total)) await conn.send_packet(pid, bytes(payload)) - async def send_spawn_position(self, conn, x, y, z): - """Send Set Default Spawn Position packet.""" - from protocol.data_types import write_position, write_float - pid = self.get_packet_id("spawn_position") - if pid is not None: - payload = bytearray() - payload.extend(write_position(x, y, z)) - payload.extend(write_float(0.0)) - await conn.send_packet(pid, bytes(payload)) - async def send_update_time(self, conn, world_age, day_time=None): """Send Update Time packet (world age + time of day).""" from protocol.data_types import write_long @@ -238,29 +217,49 @@ async def send_remove_entities(self, conn, entity_ids): payload.extend(write_varint(eid)) await conn.send_packet(pid, bytes(payload)) - async def send_player_info_update(self, conn, players, server): - """Send Player Info Update packet (or equivalent for older versions).""" - # This is version-specific and will be overridden - pass - - async def send_player_info_remove(self, conn, uuids, server): - """Send Player Info Remove packet (or equivalent for older versions).""" - # This is version-specific - pass + def build_chunk_packet_full_light(self, chunk_x, chunk_z, chunk_data, heightmap_longs, + chunk_blocks=None, sky_light_arrays=None, + block_light_arrays=None): + """Chunk Data and Update Light packet with full light masks (1.17 and later layout).""" + payload = bytearray() - async def handle_login_success(self, conn, server): - """ - After Login Success is sent, handle the transition. - For 1.20.2+, go to configuration phase. - For older versions, go directly to play phase. - """ - if self.HAS_CONFIGURATION_PHASE: - # Wait for Login Acknowledged from client - pass - else: - # Go directly to play - from network.connection import ConnectionState - conn.state = ConnectionState.PLAY + # Chunk X, Z (Int) + payload.extend(write_int(chunk_x)) + payload.extend(write_int(chunk_z)) + + # Heightmaps (NBT) + payload.extend(self.build_heightmap_nbt(heightmap_longs, heightmap_longs)) + + # Chunk Data + payload.extend(write_varint(len(chunk_data))) + payload.extend(chunk_data) + + # Block Entities (VarInt count = 0) + payload.extend(write_varint(0)) + + # Light data + all_bits = (1 << 26) - 1 + payload.extend(write_varint(1)) + payload.extend(write_long(all_bits)) + payload.extend(write_varint(1)) + payload.extend(write_long(all_bits)) + payload.extend(write_varint(0)) + payload.extend(write_varint(0)) + + sky_light_section = bytes([0xFF] * 2048) + light_section_count = 26 + payload.extend(write_varint(light_section_count)) + for _ in range(light_section_count): + payload.extend(write_varint(2048)) + payload.extend(sky_light_section) + + block_light_section = bytes([0x00] * 2048) + payload.extend(write_varint(light_section_count)) + for _ in range(light_section_count): + payload.extend(write_varint(2048)) + payload.extend(block_light_section) + + return bytes(payload) def build_chunk_data_for_version(self, chunk_blocks, chunk_biomes=None): """ diff --git a/handlers/versioned/v1_12.py b/handlers/versioned/v1_12.py index d34793d..66a9534 100755 --- a/handlers/versioned/v1_12.py +++ b/handlers/versioned/v1_12.py @@ -17,9 +17,7 @@ import struct import math from protocol.data_types import ( - write_varint, write_string, write_boolean, write_int, write_long, - write_byte, write_ubyte, write_float, write_double, - write_uuid, write_identifier, write_position, + write_varint, write_string, write_boolean, write_int, write_ubyte, ) from handlers.versioned.base import VersionHandler diff --git a/handlers/versioned/v1_13.py b/handlers/versioned/v1_13.py index 1d101d5..464c8f8 100755 --- a/handlers/versioned/v1_13.py +++ b/handlers/versioned/v1_13.py @@ -19,11 +19,8 @@ import struct import math from protocol.data_types import ( - write_varint, write_string, write_boolean, write_int, write_long, - write_byte, write_ubyte, write_float, write_double, - write_uuid, write_identifier, write_position, + write_varint, write_string, write_boolean, write_int, write_ubyte, ) -from protocol.nbt import encode_nbt, NbtLong, NbtLongArray from handlers.versioned.base import VersionHandler logger = logging.getLogger("PyMC.版本.1_13") diff --git a/handlers/versioned/v1_14.py b/handlers/versioned/v1_14.py index 3774da8..f9323f4 100755 --- a/handlers/versioned/v1_14.py +++ b/handlers/versioned/v1_14.py @@ -14,14 +14,11 @@ """ import logging -import struct import math from protocol.data_types import ( write_varint, write_string, write_boolean, write_int, write_long, - write_byte, write_ubyte, write_float, write_double, - write_uuid, write_identifier, write_position, + write_byte, write_ubyte, ) -from protocol.nbt import encode_nbt, NbtLong, NbtLongArray from handlers.versioned.base import VersionHandler logger = logging.getLogger("PyMC.版本.1_14") @@ -199,14 +196,6 @@ def build_chunk_packet(self, chunk_x, chunk_z, chunk_data, heightmap_longs, return bytes(payload) - def build_heightmap_nbt(self, motion_blocking, world_surface): - """Build heightmap NBT for 1.14+.""" - heightmap_nbt = { - "MOTION_BLOCKING": NbtLongArray(motion_blocking), - "WORLD_SURFACE": NbtLongArray(world_surface), - } - return encode_nbt(heightmap_nbt, with_type=True) - def conn_protocol_ge_578(): """Helper: check if we're dealing with 1.15+ protocol.""" diff --git a/handlers/versioned/v1_16.py b/handlers/versioned/v1_16.py index 262fec1..60dd02c 100755 --- a/handlers/versioned/v1_16.py +++ b/handlers/versioned/v1_16.py @@ -18,11 +18,10 @@ import struct import math from protocol.data_types import ( - write_varint, write_string, write_boolean, write_int, write_long, - write_byte, write_ubyte, write_float, write_double, - write_uuid, write_identifier, write_position, write_short, + write_varint, write_boolean, write_int, write_long, write_byte, + write_ubyte, write_identifier, ) -from protocol.nbt import encode_nbt, NbtLong, NbtLongArray, NbtByte, NbtDouble, NbtFloat +from protocol.nbt import encode_nbt, NbtLong, NbtByte, NbtDouble, NbtFloat from handlers.versioned.base import VersionHandler logger = logging.getLogger("PyMC.版本.1_16") diff --git a/handlers/versioned/v1_17.py b/handlers/versioned/v1_17.py index 0bd4b2e..53ab1e7 100755 --- a/handlers/versioned/v1_17.py +++ b/handlers/versioned/v1_17.py @@ -15,13 +15,11 @@ """ import logging -import struct from protocol.data_types import ( - write_varint, write_string, write_boolean, write_int, write_long, - write_byte, write_ubyte, write_float, write_double, - write_uuid, write_identifier, write_position, + write_varint, write_boolean, write_int, write_long, write_byte, + write_ubyte, write_identifier, ) -from protocol.nbt import encode_nbt, NbtLong, NbtLongArray, NbtByte, NbtDouble, NbtFloat +from protocol.nbt import encode_nbt, NbtLong, NbtByte, NbtDouble, NbtFloat from handlers.versioned.base import VersionHandler logger = logging.getLogger("PyMC.版本.1_17") @@ -234,46 +232,4 @@ def _build_overworld_dimension(self) -> dict: "monster_spawn_block_light_limit": 0, } - def build_chunk_packet(self, chunk_x, chunk_z, chunk_data, heightmap_longs, - chunk_blocks=None, sky_light_arrays=None, - block_light_arrays=None): - """Build Chunk Data and Update Light packet for 1.17/1.18.""" - payload = bytearray() - - # Chunk X, Z (Int) - payload.extend(write_int(chunk_x)) - payload.extend(write_int(chunk_z)) - - # Heightmaps (NBT) - payload.extend(self.build_heightmap_nbt(heightmap_longs, heightmap_longs)) - - # Chunk Data - payload.extend(write_varint(len(chunk_data))) - payload.extend(chunk_data) - - # Block Entities (VarInt count = 0) - payload.extend(write_varint(0)) - - # Light data - all_bits = (1 << 26) - 1 - payload.extend(write_varint(1)) - payload.extend(write_long(all_bits)) - payload.extend(write_varint(1)) - payload.extend(write_long(all_bits)) - payload.extend(write_varint(0)) - payload.extend(write_varint(0)) - - sky_light_section = bytes([0xFF] * 2048) - light_section_count = 26 - payload.extend(write_varint(light_section_count)) - for _ in range(light_section_count): - payload.extend(write_varint(2048)) - payload.extend(sky_light_section) - - block_light_section = bytes([0x00] * 2048) - payload.extend(write_varint(light_section_count)) - for _ in range(light_section_count): - payload.extend(write_varint(2048)) - payload.extend(block_light_section) - - return bytes(payload) + build_chunk_packet = VersionHandler.build_chunk_packet_full_light diff --git a/handlers/versioned/v1_19.py b/handlers/versioned/v1_19.py index b8efd27..d4fea11 100755 --- a/handlers/versioned/v1_19.py +++ b/handlers/versioned/v1_19.py @@ -16,13 +16,10 @@ """ import logging -import struct from protocol.data_types import ( - write_varint, write_string, write_boolean, write_int, write_long, - write_byte, write_ubyte, write_float, write_double, - write_uuid, write_identifier, write_position, + write_varint, write_boolean, write_int, write_long, write_byte, + write_ubyte, write_identifier, ) -from protocol.nbt import encode_nbt, NbtLong, NbtLongArray from handlers.versioned.base import VersionHandler logger = logging.getLogger("PyMC.版本.1_19") @@ -112,46 +109,4 @@ async def send_join_game(self, conn, server): await conn.send_packet(pid, bytes(payload)) - def build_chunk_packet(self, chunk_x, chunk_z, chunk_data, heightmap_longs, - chunk_blocks=None, sky_light_arrays=None, - block_light_arrays=None): - """Build Chunk Data and Update Light packet for 1.19.x.""" - payload = bytearray() - - # Chunk X, Z (Int) - payload.extend(write_int(chunk_x)) - payload.extend(write_int(chunk_z)) - - # Heightmaps (NBT) - payload.extend(self.build_heightmap_nbt(heightmap_longs, heightmap_longs)) - - # Chunk Data - payload.extend(write_varint(len(chunk_data))) - payload.extend(chunk_data) - - # Block Entities (VarInt count = 0) - payload.extend(write_varint(0)) - - # Light data - all_bits = (1 << 26) - 1 - payload.extend(write_varint(1)) - payload.extend(write_long(all_bits)) - payload.extend(write_varint(1)) - payload.extend(write_long(all_bits)) - payload.extend(write_varint(0)) - payload.extend(write_varint(0)) - - sky_light_section = bytes([0xFF] * 2048) - light_section_count = 26 - payload.extend(write_varint(light_section_count)) - for _ in range(light_section_count): - payload.extend(write_varint(2048)) - payload.extend(sky_light_section) - - block_light_section = bytes([0x00] * 2048) - payload.extend(write_varint(light_section_count)) - for _ in range(light_section_count): - payload.extend(write_varint(2048)) - payload.extend(block_light_section) - - return bytes(payload) + build_chunk_packet = VersionHandler.build_chunk_packet_full_light diff --git a/handlers/versioned/v1_20.py b/handlers/versioned/v1_20.py index dd528d0..9b65794 100755 --- a/handlers/versioned/v1_20.py +++ b/handlers/versioned/v1_20.py @@ -11,13 +11,10 @@ """ import logging -import struct from protocol.data_types import ( - write_varint, write_string, write_boolean, write_int, write_long, - write_byte, write_ubyte, write_float, write_double, - write_uuid, write_identifier, write_position, write_angle, + write_varint, write_boolean, write_int, write_long, write_byte, + write_ubyte, write_identifier, ) -from protocol.nbt import encode_nbt, NbtLong, NbtLongArray from handlers.versioned.base import VersionHandler logger = logging.getLogger("PyMC.版本.1_20") @@ -114,46 +111,4 @@ async def send_join_game(self, conn, server): await conn.send_packet(pid, bytes(payload)) - def build_chunk_packet(self, chunk_x, chunk_z, chunk_data, heightmap_longs, - chunk_blocks=None, sky_light_arrays=None, - block_light_arrays=None): - """Build Chunk Data and Update Light packet for 1.20.1.""" - payload = bytearray() - - # Chunk X, Z (Int) - payload.extend(write_int(chunk_x)) - payload.extend(write_int(chunk_z)) - - # Heightmaps (NBT) - payload.extend(self.build_heightmap_nbt(heightmap_longs, heightmap_longs)) - - # Chunk Data - payload.extend(write_varint(len(chunk_data))) - payload.extend(chunk_data) - - # Block Entities (VarInt count = 0) - payload.extend(write_varint(0)) - - # Light data - simplified full bright - all_bits = (1 << 26) - 1 - payload.extend(write_varint(1)) - payload.extend(write_long(all_bits)) - payload.extend(write_varint(1)) - payload.extend(write_long(all_bits)) - payload.extend(write_varint(0)) - payload.extend(write_varint(0)) - - sky_light_section = bytes([0xFF] * 2048) - light_section_count = 26 - payload.extend(write_varint(light_section_count)) - for _ in range(light_section_count): - payload.extend(write_varint(2048)) - payload.extend(sky_light_section) - - block_light_section = bytes([0x00] * 2048) - payload.extend(write_varint(light_section_count)) - for _ in range(light_section_count): - payload.extend(write_varint(2048)) - payload.extend(block_light_section) - - return bytes(payload) + build_chunk_packet = VersionHandler.build_chunk_packet_full_light diff --git a/handlers/versioned/v1_21.py b/handlers/versioned/v1_21.py index 4ee63cc..02e507a 100755 --- a/handlers/versioned/v1_21.py +++ b/handlers/versioned/v1_21.py @@ -9,14 +9,10 @@ """ import logging -import struct -import math from protocol.data_types import ( - write_varint, write_string, write_boolean, write_int, write_long, - write_byte, write_ubyte, write_float, write_double, write_short, - write_uuid, write_identifier, write_position, write_angle, + write_varint, write_boolean, write_int, write_long, write_byte, + write_ubyte, write_identifier, ) -from protocol.nbt import encode_nbt, NbtLong, NbtLongArray from handlers.versioned.base import VersionHandler logger = logging.getLogger("PyMC.版本.1_21") diff --git a/handlers/versioned/v1_8.py b/handlers/versioned/v1_8.py index b02d01c..64c16cc 100755 --- a/handlers/versioned/v1_8.py +++ b/handlers/versioned/v1_8.py @@ -25,9 +25,8 @@ import math import json from protocol.data_types import ( - write_varint, write_string, write_boolean, write_int, write_long, - write_byte, write_ubyte, write_float, write_double, - write_uuid, write_identifier, write_position, write_short, + write_varint, write_string, write_boolean, write_int, write_byte, + write_ubyte, ) from handlers.versioned.base import VersionHandler @@ -120,11 +119,9 @@ async def send_system_chat(self, conn, text, overlay=False): async def send_set_center_chunk(self, conn, chunk_x, chunk_z): """1.8 doesn't have Set Center Chunk - no-op.""" - pass async def send_set_chunk_cache_radius(self, conn, view_distance): """1.8 doesn't have Set Chunk Cache Radius - no-op.""" - pass async def send_remove_entities(self, conn, entity_ids): """Send Destroy Entities packet for 1.8.""" diff --git a/mods/__init__.py b/mods/__init__.py index 131537a..67f1ec0 100755 --- a/mods/__init__.py +++ b/mods/__init__.py @@ -121,13 +121,6 @@ class ModInfo: package_path: str = "" # Absolute path to the mod package directory extra: Dict[str, Any] = field(default_factory=dict) - def depends_on(self, mod_id: str) -> bool: - return mod_id in self.dependencies - - def soft_depends_on(self, mod_id: str) -> bool: - return mod_id in self.soft_dependencies - - # =========================================================== # PyMCMod Base Class # =========================================================== @@ -164,10 +157,6 @@ def __init__(self): self._manager: Optional['ModManager'] = None self._event_handlers: List[tuple] = [] # (event_name, handler) - @property - def mod_info(self) -> ModInfo: - return self._mod_info - @property def logger(self) -> logging.Logger: if self._mod_info: @@ -282,10 +271,6 @@ def __init__(self, mods_dir: Optional[str] = None): # --- Discovery --- - def scan_mods_directory(self, mods_dir: str) -> List[ModInfo]: - """Compatibility method: discover mods from a directory.""" - return self.discover_mods(mods_dir) - def discover_mods(self, mods_dir: Optional[str] = None) -> List[ModInfo]: """ Scan a directory for PYMC native mod packages. @@ -482,36 +467,14 @@ def fire_event_simple(self, event_name: str, # --- Query --- - def is_mod_loaded(self, mod_id: str) -> bool: - return mod_id in self._mods and self._mods[mod_id].is_active - def get_mod(self, mod_id: str) -> Optional[PyMCMod]: instance = self._mods.get(mod_id) return instance.mod_obj if instance else None - def get_mod_state(self, mod_id: str) -> Optional[ModState]: - instance = self._mods.get(mod_id) - return instance.state if instance else None - - def get_loaded_mods(self) -> List[str]: - return [mid for mid, inst in self._mods.items() if inst.is_active] - @property def mod_count(self) -> int: return len([i for i in self._mods.values() if i.is_active]) - @property - def registered_blocks(self) -> Dict[str, Dict]: - return dict(self._blocks) - - @property - def registered_items(self) -> Dict[str, Dict]: - return dict(self._items) - - @property - def registered_biomes(self) -> Dict[str, Dict]: - return dict(self._biomes) - # --- Internal: Registration callbacks --- def _register_block(self, block_id: str, properties: Dict): diff --git a/mods/bridge.py b/mods/bridge.py index e8a40ac..e65fcf7 100755 --- a/mods/bridge.py +++ b/mods/bridge.py @@ -20,7 +20,7 @@ import asyncio import logging -from typing import Any, Dict, List, Optional +from typing import Dict, List, Optional from mods import ModEvent, ModEvents, ModManager, PyMCMod diff --git a/native/__init__.py b/native/__init__.py deleted file mode 100755 index e472a58..0000000 --- a/native/__init__.py +++ /dev/null @@ -1,1053 +0,0 @@ -# ============================================================ -# PyMC - C++ Acceleration Layer Python Interface -# -# Provides unified access to the C++ acceleration layer: -# - Shared memory IPC mode (fastest, separate process) -# - Direct in-process mode (via ctypes shared library) -# - Fallback to subprocess mode (existing terrain_gen/mob_ai) -# -# Architecture: -# NativeCore -# ├── NativeRedstoneEngine - Redstone simulation -# ├── NativeLightEngine - Light propagation -# └── NativePhysicsEngine - AABB collision + physics -# ============================================================ - -import ctypes -import logging -import os -import struct -import subprocess -import sys -import time -from pathlib import Path -from typing import Optional -from world._native_binary import is_runnable_native_binary - -logger = logging.getLogger("pymc.native") - -# =========================================================== -# Constants -# =========================================================== - -# Command types (must match pymc_native_server.cpp) -CMD_TICK = 0x01 -CMD_ADD_REDSTONE = 0x02 -CMD_REMOVE_REDSTONE = 0x03 -CMD_SET_POWER = 0x04 -CMD_CALC_LIGHT = 0x05 -CMD_UPDATE_LIGHT = 0x06 -CMD_SET_ENTITY = 0x07 -CMD_REMOVE_ENTITY = 0x08 -CMD_SET_BLOCKS = 0x09 -CMD_TICK_FLUIDS = 0x0A -CMD_PING = 0x0B -CMD_SHUTDOWN = 0xFF - -# Response status -STATUS_OK = 0 -STATUS_ERROR = 1 -STATUS_UNKNOWN_CMD = 2 - -# Engine constants -SECTION_SIZE = 16 -CHUNK_SECTIONS = 24 -LIGHT_SECTIONS = 26 -MIN_Y = -64 - -# Component types -COMPONENT_WIRE = 0 -COMPONENT_TORCH = 1 -COMPONENT_REPEATER = 2 -COMPONENT_COMPARATOR = 3 -COMPONENT_PISTON = 4 -COMPONENT_STICKY_PISTON = 5 -COMPONENT_OBSERVER = 6 -COMPONENT_LEVER = 7 -COMPONENT_BUTTON = 8 -COMPONENT_PRESSURE_PLATE = 9 -COMPONENT_WEIGHTED_PRESSURE_PLATE = 10 - -# Facing directions -FACING_DOWN = 0 -FACING_UP = 1 -FACING_NORTH = 2 -FACING_SOUTH = 3 -FACING_WEST = 4 -FACING_EAST = 5 - - -# =========================================================== -# Binary protocol helpers -# =========================================================== - -def _pack_u8(val: int) -> bytes: - return struct.pack(' bytes: - return struct.pack(' bytes: - return struct.pack(' bytes: - return struct.pack(' bytes: - return struct.pack(' int: - return struct.unpack_from(' int: - return struct.unpack_from(' int: - return struct.unpack_from(' int: - return struct.unpack_from(' float: - return struct.unpack_from(' Optional[str]: - """Find a pymc_native shared library loadable on the current OS.""" - if os.name == "nt": - lib_names = ["pymc_native.dll", "libpymc_native.dll", "libpymc_native.so"] - elif sys.platform == "darwin": - lib_names = ["libpymc_native.dylib", "pymc_native.dylib", "libpymc_native.so"] - else: - lib_names = ["libpymc_native.so", "pymc_native.so", "libpymc_native.dylib"] - - compiled = globals().get("__compiled__") - search_roots = [ - Path(__file__).resolve().parent, - Path(__file__).resolve().parent.parent, - Path.cwd(), - Path(sys.argv[0]).resolve().parent, - Path(sys.executable).resolve().parent, - ] - if compiled is not None and hasattr(compiled, "containing_dir"): - search_roots.append(Path(compiled.containing_dir).resolve()) - - seen: set = set() - for root in search_roots: - if root is None: - continue - for name in lib_names: - for subdir in ( - ".", - "native", - "build/stage/native", - "build/stage", - "build", - "lib", - ): - candidate = (root / subdir / name).resolve() - if candidate in seen: - continue - seen.add(candidate) - if is_runnable_native_binary(candidate): - return str(candidate) - return None - - -def _find_native_server() -> Optional[str]: - """Find a pymc_native_server executable for the current OS.""" - if os.name == "nt": - exe_names = ["pymc_native_server.exe", "pymc_native_server"] - else: - exe_names = ["pymc_native_server", "pymc_native_server.exe"] - - compiled = globals().get("__compiled__") - search_roots = [ - Path(__file__).resolve().parent, - Path(__file__).resolve().parent.parent, - Path.cwd(), - Path(sys.argv[0]).resolve().parent, - ] - if compiled is not None and hasattr(compiled, "containing_dir"): - search_roots.append(Path(compiled.containing_dir).resolve()) - - seen: set = set() - for root in search_roots: - if root is None: - continue - for subdir in ( - "native", - ".", - "build/stage/native", - "build/stage", - "build", - ): - for name in exe_names: - candidate = (root / subdir / name).resolve() - if candidate in seen: - continue - seen.add(candidate) - if is_runnable_native_binary(candidate): - return str(candidate) - return None - - -# IPC-based Native Core (separate process, shared memory) -# =========================================================== - -class NativeIPCConnection: - """ - Communicates with the native C++ server process via shared memory. - - This is the FASTEST mode - zero-copy ring buffer IPC with - no serialization overhead. The C++ process runs continuously - and Python sends commands/responses through shared memory. - """ - - def __init__(self, shm_name: str = "/pymc_native", - cmd_size: int = 16 * 1024 * 1024, - resp_size: int = 16 * 1024 * 1024): - self._shm_name = shm_name - self._cmd_size = cmd_size - self._resp_size = resp_size - self._lib: Optional[ctypes.CDLL] = None - self._channel: Optional[int] = None - self._process: Optional[subprocess.Popen] = None - self._initialized = False - - def _ensure_lib(self) -> bool: - """Load the pymc_native shared library for IPC functions.""" - if self._lib is not None: - return True - - lib_path = _find_native_lib() - if lib_path is None: - logger.debug("pymc_native shared library not found; IPC native mode unavailable") - return False - - try: - self._lib = ctypes.CDLL(lib_path) - # Set up function signatures - self._lib.pymc_ipc_channel_create.restype = ctypes.c_void_p - self._lib.pymc_ipc_channel_create.argtypes = [ - ctypes.c_char_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_int - ] - self._lib.pymc_ipc_channel_destroy.restype = None - self._lib.pymc_ipc_channel_destroy.argtypes = [ctypes.c_void_p] - self._lib.pymc_ipc_send_command.restype = ctypes.c_int - self._lib.pymc_ipc_send_command.argtypes = [ - ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint32 - ] - self._lib.pymc_ipc_recv_response.restype = ctypes.c_uint32 - self._lib.pymc_ipc_recv_response.argtypes = [ - ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint32 - ] - self._lib.pymc_ipc_wait_for_response.restype = ctypes.c_int - self._lib.pymc_ipc_wait_for_response.argtypes = [ - ctypes.c_void_p, ctypes.c_int - ] - self._lib.pymc_ipc_is_valid.restype = ctypes.c_int - self._lib.pymc_ipc_is_valid.argtypes = [ctypes.c_void_p] - return True - except Exception as e: - logger.warning(f"Failed to load pymc_native library: {e}") - self._lib = None - return False - - def start(self) -> bool: - """Start the native server process and establish IPC.""" - server_path = _find_native_server() - if server_path is None: - logger.debug("pymc_native_server not found; IPC native mode unavailable") - return False - - if not self._ensure_lib(): - return False - - try: - # Create the IPC channel (Python is the creator) - self._channel = self._lib.pymc_ipc_channel_create( - self._shm_name.encode('utf-8'), - self._cmd_size, - self._resp_size, - 1 # create=True - ) - if not self._channel: - logger.error("Failed to create IPC channel") - return False - - # Start the native server process - self._process = subprocess.Popen( - [server_path, - "--name", self._shm_name, - "--cmd-size", str(self._cmd_size), - "--resp-size", str(self._resp_size)], - stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, - stderr=subprocess.PIPE, - ) - - time.sleep(0.1) - if self._process.poll() is not None: - stderr = b"" - if self._process.stderr: - try: - stderr = self._process.stderr.read() or b"" - except Exception: - pass - logger.error( - f"Native server exited immediately (code={self._process.returncode}): " - f"{stderr.decode('utf-8', errors='replace').strip()}" - ) - self._channel = None - return False - - # Verify with ping - if self.ping(): - self._initialized = True - logger.info(f"Native IPC connection established (PID: {self._process.pid})") - return True - else: - logger.warning("Native server ping failed") - self.shutdown() - return False - - except Exception as e: - logger.error(f"Failed to start native server: {e}") - self.shutdown() - return False - - def ping(self) -> bool: - """Send a ping command and wait for response.""" - if not self._channel: - return False - try: - cmd = _pack_u8(CMD_PING) - result = self._lib.pymc_ipc_send_command( - self._channel, cmd, len(cmd) - ) - if not result: - return False - - buf = ctypes.create_string_buffer(64) - self._lib.pymc_ipc_wait_for_response(self._channel, 2000) - n = self._lib.pymc_ipc_recv_response(self._channel, buf, 64) - if n < 4: - return False - - status = _unpack_u32(buf.raw[:4]) - return status == STATUS_OK - except Exception: - return False - - def send_command(self, data: bytes) -> Optional[bytes]: - """Send a command and wait for the response.""" - if not self._channel: - return None - try: - result = self._lib.pymc_ipc_send_command( - self._channel, data, len(data) - ) - if not result: - logger.warning("IPC send_command: buffer full") - return None - - buf = ctypes.create_string_buffer(self._resp_size) - self._lib.pymc_ipc_wait_for_response(self._channel, 5000) - n = self._lib.pymc_ipc_recv_response( - self._channel, buf, self._resp_size - ) - if n < 4: - return None - return buf.raw[:n] - except Exception as e: - logger.warning(f"IPC send_command failed: {e}") - return None - - @property - def available(self) -> bool: - return ( - self._initialized - and self._channel is not None - and self._process is not None - and self._process.poll() is None - ) - - def shutdown(self): - """Shut down the native server process.""" - if self._channel: - try: - cmd = _pack_u8(CMD_SHUTDOWN) - self._lib.pymc_ipc_send_command( - self._channel, cmd, len(cmd) - ) - # Wait briefly for response - buf = ctypes.create_string_buffer(64) - self._lib.pymc_ipc_wait_for_response(self._channel, 500) - self._lib.pymc_ipc_recv_response(self._channel, buf, 64) - except Exception: - pass - - if self._process: - try: - self._process.wait(timeout=3) - except Exception: - try: - self._process.kill() - except Exception: - pass - self._process = None - - if self._channel and self._lib: - try: - self._lib.pymc_ipc_channel_destroy(self._channel) - except Exception: - pass - self._channel = None - - self._initialized = False - - -# =========================================================== -# Direct in-process engine access (via ctypes) -# =========================================================== - -class NativeRedstoneEngine: - """Direct in-process redstone engine via ctypes.""" - - def __init__(self, lib: ctypes.CDLL): - self._lib = lib - self._engine = lib.pymc_redstone_create() - if not self._engine: - raise RuntimeError("Failed to create redstone engine") - - def add_component(self, x: int, y: int, z: int, - comp_type: int, facing: int): - self._lib.pymc_redstone_add_component( - self._engine, x, y, z, comp_type, facing - ) - - def remove_component(self, x: int, y: int, z: int): - self._lib.pymc_redstone_remove_component(self._engine, x, y, z) - - def set_power_level(self, x: int, y: int, z: int, level: int): - self._lib.pymc_redstone_set_power(self._engine, x, y, z, level) - - def get_power_level(self, x: int, y: int, z: int) -> int: - return self._lib.pymc_redstone_get_power(self._engine, x, y, z) - - def tick(self) -> list: - """Process one tick. Returns list of (x, y, z, new_state, flags).""" - max_updates = 4096 - buf = (ctypes.c_int32 * (max_updates * 5))() - count = self._lib.pymc_redstone_tick(self._engine, buf, max_updates) - - updates = [] - for i in range(count): - updates.append(( - buf[i * 5], buf[i * 5 + 1], buf[i * 5 + 2], - buf[i * 5 + 3], buf[i * 5 + 4] - )) - return updates - - def clear(self): - self._lib.pymc_redstone_clear(self._engine) - - def destroy(self): - if self._engine: - self._lib.pymc_redstone_destroy(self._engine) - self._engine = None - - def __del__(self): - self.destroy() - - -class NativeLightEngine: - """Direct in-process light engine via ctypes.""" - - def __init__(self, lib: ctypes.CDLL): - self._lib = lib - self._engine = lib.pymc_light_create() - if not self._engine: - raise RuntimeError("Failed to create light engine") - - def calculate_chunk_lighting(self, blocks: list) -> tuple: - """ - Calculate lighting for a chunk. - - Args: - blocks: flat list of 98304 uint16 block state IDs - - Returns: - (sky_light, block_light) as bytes arrays - """ - blocks_array = (ctypes.c_uint16 * len(blocks))(*blocks) - - sky_size = LIGHT_SECTIONS * SECTION_SIZE * SECTION_SIZE * SECTION_SIZE - block_size = sky_size - - sky_light = (ctypes.c_uint8 * sky_size)() - block_light = (ctypes.c_uint8 * block_size)() - - self._lib.pymc_light_calculate_chunk( - self._engine, blocks_array, sky_light, block_light - ) - - return bytes(sky_light), bytes(block_light) - - def update_block_light(self, x: int, y: int, z: int, - old_block: int, new_block: int) -> list: - """Incremental light update.""" - max_updates = 256 - buf = (ctypes.c_int32 * (max_updates * 5))() - count = self._lib.pymc_light_update_block( - self._engine, x, y, z, old_block, new_block, buf, max_updates - ) - - updates = [] - for i in range(count): - updates.append({ - 'x': buf[i * 5], - 'y': buf[i * 5 + 1], - 'z': buf[i * 5 + 2], - 'sky_light': buf[i * 5 + 3], - 'block_light': buf[i * 5 + 4], - }) - return updates - - def set_block_info(self, block_state: int, sky_type: int, - block_type: int, emitted_light: int, filter_level: int): - self._lib.pymc_light_set_block_info( - self._engine, block_state, sky_type, block_type, - emitted_light, filter_level - ) - - def destroy(self): - if self._engine: - self._lib.pymc_light_destroy(self._engine) - self._engine = None - - def __del__(self): - self.destroy() - - -class NativePhysicsEngine: - """Direct in-process physics engine via ctypes.""" - - def __init__(self, lib: ctypes.CDLL): - self._lib = lib - self._engine = lib.pymc_physics_create() - if not self._engine: - raise RuntimeError("Failed to create physics engine") - - def set_entity(self, entity_id: int, x: float, y: float, z: float, - vx: float = 0.0, vy: float = 0.0, vz: float = 0.0, - bb_min: tuple = (-0.3, 0.0, -0.3), - bb_max: tuple = (0.3, 1.8, 0.3), - on_ground: bool = False, has_gravity: bool = True, - is_item: bool = False, is_falling_block: bool = False, - block_state: int = 0): - entity = ( - _pack_i32(entity_id) + - _pack_f64(x) + _pack_f64(y) + _pack_f64(z) + - _pack_f64(vx) + _pack_f64(vy) + _pack_f64(vz) + - _pack_f64(bb_min[0]) + _pack_f64(bb_min[1]) + _pack_f64(bb_min[2]) + - _pack_f64(bb_max[0]) + _pack_f64(bb_max[1]) + _pack_f64(bb_max[2]) + - _pack_u8(int(on_ground)) + _pack_u8(int(has_gravity)) + - _pack_u8(int(is_item)) + _pack_u8(int(is_falling_block)) + - _pack_u16(block_state) - ) - - class PhysicsEntity(ctypes.Structure): - _fields_ = [ - ("entity_id", ctypes.c_int32), - ("x", ctypes.c_double), ("y", ctypes.c_double), ("z", ctypes.c_double), - ("vx", ctypes.c_double), ("vy", ctypes.c_double), ("vz", ctypes.c_double), - ("bb_min_x", ctypes.c_double), ("bb_min_y", ctypes.c_double), ("bb_min_z", ctypes.c_double), - ("bb_max_x", ctypes.c_double), ("bb_max_y", ctypes.c_double), ("bb_max_z", ctypes.c_double), - ("on_ground", ctypes.c_uint8), - ("has_gravity", ctypes.c_uint8), - ("is_item", ctypes.c_uint8), - ("is_falling_block", ctypes.c_uint8), - ("block_state", ctypes.c_uint16), - ] - - e = PhysicsEntity() - e.entity_id = entity_id - e.x, e.y, e.z = x, y, z - e.vx, e.vy, e.vz = vx, vy, vz - e.bb_min_x, e.bb_min_y, e.bb_min_z = bb_min - e.bb_max_x, e.bb_max_y, e.bb_max_z = bb_max - e.on_ground = int(on_ground) - e.has_gravity = int(has_gravity) - e.is_item = int(is_item) - e.is_falling_block = int(is_falling_block) - e.block_state = block_state - - self._lib.pymc_physics_set_entity(self._engine, ctypes.byref(e)) - - def remove_entity(self, entity_id: int): - self._lib.pymc_physics_remove_entity(self._engine, entity_id) - - def set_blocks(self, blocks: list): - """ - Set block data for collision. - - Args: - blocks: list of (x, y, z, block_state) tuples - """ - if not blocks: - return - - count = len(blocks) - xyz_data = (ctypes.c_int32 * (count * 3))() - block_states = (ctypes.c_uint16 * count)() - - for i, (x, y, z, bs) in enumerate(blocks): - xyz_data[i * 3] = x - xyz_data[i * 3 + 1] = y - xyz_data[i * 3 + 2] = z - block_states[i] = bs - - self._lib.pymc_physics_set_blocks( - self._engine, xyz_data, block_states, count - ) - - def tick(self) -> list: - """Process one physics tick. Returns list of update dicts.""" - max_updates = 1024 - - class PhysicsUpdate(ctypes.Structure): - _fields_ = [ - ("entity_id", ctypes.c_int32), - ("new_x", ctypes.c_double), ("new_y", ctypes.c_double), ("new_z", ctypes.c_double), - ("new_vx", ctypes.c_double), ("new_vy", ctypes.c_double), ("new_vz", ctypes.c_double), - ("on_ground", ctypes.c_uint8), - ("landed", ctypes.c_uint8), - ("landed_block_state", ctypes.c_uint16), - ("landed_x", ctypes.c_int32), ("landed_y", ctypes.c_int32), ("landed_z", ctypes.c_int32), - ] - - buf = (PhysicsUpdate * max_updates)() - count = self._lib.pymc_physics_tick(self._engine, buf, max_updates) - - updates = [] - for i in range(count): - u = buf[i] - updates.append({ - 'entity_id': u.entity_id, - 'new_x': u.new_x, 'new_y': u.new_y, 'new_z': u.new_z, - 'new_vx': u.new_vx, 'new_vy': u.new_vy, 'new_vz': u.new_vz, - 'on_ground': bool(u.on_ground), - 'landed': bool(u.landed), - 'landed_block_state': u.landed_block_state, - 'landed_x': u.landed_x, 'landed_y': u.landed_y, 'landed_z': u.landed_z, - }) - return updates - - def clear_blocks(self): - self._lib.pymc_physics_clear_blocks(self._engine) - - def destroy(self): - if self._engine: - self._lib.pymc_physics_destroy(self._engine) - self._engine = None - - def __del__(self): - self.destroy() - - -# =========================================================== -# IPC-based engine wrappers (communicate with server process) -# =========================================================== - -class IPCRedstoneEngine: - """Redstone engine via IPC to the native server process.""" - - def __init__(self, ipc: NativeIPCConnection): - self._ipc = ipc - - def add_component(self, x: int, y: int, z: int, - comp_type: int, facing: int): - cmd = (_pack_u8(CMD_ADD_REDSTONE) + - _pack_i32(x) + _pack_i32(y) + _pack_i32(z) + - _pack_u8(comp_type) + _pack_u8(facing)) - resp = self._ipc.send_command(cmd) - return resp is not None and _unpack_u32(resp) == STATUS_OK - - def remove_component(self, x: int, y: int, z: int): - cmd = (_pack_u8(CMD_REMOVE_REDSTONE) + - _pack_i32(x) + _pack_i32(y) + _pack_i32(z)) - resp = self._ipc.send_command(cmd) - return resp is not None and _unpack_u32(resp) == STATUS_OK - - def set_power_level(self, x: int, y: int, z: int, level: int): - cmd = (_pack_u8(CMD_SET_POWER) + - _pack_i32(x) + _pack_i32(y) + _pack_i32(z) + - _pack_i32(level)) - resp = self._ipc.send_command(cmd) - return resp is not None and _unpack_u32(resp) == STATUS_OK - - def tick(self) -> list: - """Process one tick. Returns list of update dicts.""" - cmd = _pack_u8(CMD_TICK) - resp = self._ipc.send_command(cmd) - if not resp or _unpack_u32(resp) != STATUS_OK: - return [] - - offset = 4 - # Read redstone updates - rs_count = _unpack_u32(resp, offset) - offset += 4 - - updates = [] - for _ in range(rs_count): - x = _unpack_i32(resp, offset); offset += 4 - y = _unpack_i32(resp, offset); offset += 4 - z = _unpack_i32(resp, offset); offset += 4 - new_state = _unpack_i32(resp, offset); offset += 4 - flags = _unpack_i32(resp, offset); offset += 4 - updates.append({ - 'type': 'redstone', - 'x': x, 'y': y, 'z': z, - 'new_block_state': new_state, - 'flags': flags, - }) - - # Read physics updates - phys_count = _unpack_u32(resp, offset) - offset += 4 - - for _ in range(phys_count): - entity_id = _unpack_i32(resp, offset); offset += 4 - new_x = _unpack_f64(resp, offset); offset += 8 - new_y = _unpack_f64(resp, offset); offset += 8 - new_z = _unpack_f64(resp, offset); offset += 8 - new_vx = _unpack_f64(resp, offset); offset += 8 - new_vy = _unpack_f64(resp, offset); offset += 8 - new_vz = _unpack_f64(resp, offset); offset += 8 - on_ground = _unpack_u8(resp, offset); offset += 1 - landed = _unpack_u8(resp, offset); offset += 1 - landed_bs = 0 - landed_x = landed_y = landed_z = 0 - if landed: - landed_bs = _unpack_u16(resp, offset); offset += 2 - landed_x = _unpack_i32(resp, offset); offset += 4 - landed_y = _unpack_i32(resp, offset); offset += 4 - landed_z = _unpack_i32(resp, offset); offset += 4 - - updates.append({ - 'type': 'physics', - 'entity_id': entity_id, - 'new_x': new_x, 'new_y': new_y, 'new_z': new_z, - 'new_vx': new_vx, 'new_vy': new_vy, 'new_vz': new_vz, - 'on_ground': bool(on_ground), - 'landed': bool(landed), - 'landed_block_state': landed_bs, - 'landed_x': landed_x, 'landed_y': landed_y, 'landed_z': landed_z, - }) - - return updates - - -class IPCLightEngine: - """Light engine via IPC to the native server process.""" - - def __init__(self, ipc: NativeIPCConnection): - self._ipc = ipc - - def calculate_chunk_lighting(self, blocks: list) -> tuple: - """ - Calculate lighting for a chunk. - - Args: - blocks: flat list of 98304 uint16 block state IDs - - Returns: - (sky_light, block_light) as bytes - """ - # Pack blocks as little-endian uint16 - blocks_data = b''.join(_pack_u16(b) for b in blocks) - cmd = _pack_u8(CMD_CALC_LIGHT) + blocks_data - resp = self._ipc.send_command(cmd) - - if not resp or _unpack_u32(resp) != STATUS_OK: - return b'', b'' - - offset = 4 - light_size = LIGHT_SECTIONS * SECTION_SIZE * SECTION_SIZE * SECTION_SIZE - sky_light = resp[offset:offset + light_size] - offset += light_size - block_light = resp[offset:offset + light_size] - return sky_light, block_light - - def update_block_light(self, x: int, y: int, z: int, - old_block: int, new_block: int) -> list: - cmd = (_pack_u8(CMD_UPDATE_LIGHT) + - _pack_i32(x) + _pack_i32(y) + _pack_i32(z) + - _pack_u16(old_block) + _pack_u16(new_block)) - resp = self._ipc.send_command(cmd) - if not resp or _unpack_u32(resp) != STATUS_OK: - return [] - - offset = 4 - count = _unpack_u32(resp, offset) - offset += 4 - updates = [] - for _ in range(count): - ux = _unpack_i32(resp, offset); offset += 4 - uy = _unpack_i32(resp, offset); offset += 4 - uz = _unpack_i32(resp, offset); offset += 4 - usl = _unpack_u8(resp, offset); offset += 1 - ubl = _unpack_u8(resp, offset); offset += 1 - updates.append({ - 'x': ux, 'y': uy, 'z': uz, - 'sky_light': usl, 'block_light': ubl, - }) - return updates - - -class IPCPhysicsEngine: - """Physics engine via IPC to the native server process.""" - - def __init__(self, ipc: NativeIPCConnection): - self._ipc = ipc - - def set_entity(self, entity_id: int, x: float, y: float, z: float, - vx: float = 0.0, vy: float = 0.0, vz: float = 0.0, - bb_min: tuple = (-0.3, 0.0, -0.3), - bb_max: tuple = (0.3, 1.8, 0.3), - on_ground: bool = False, has_gravity: bool = True, - is_item: bool = False, is_falling_block: bool = False, - block_state: int = 0): - cmd = (_pack_u8(CMD_SET_ENTITY) + - _pack_i32(entity_id) + - _pack_f64(x) + _pack_f64(y) + _pack_f64(z) + - _pack_f64(vx) + _pack_f64(vy) + _pack_f64(vz) + - _pack_f64(bb_min[0]) + _pack_f64(bb_min[1]) + _pack_f64(bb_min[2]) + - _pack_f64(bb_max[0]) + _pack_f64(bb_max[1]) + _pack_f64(bb_max[2]) + - _pack_u8(int(on_ground)) + _pack_u8(int(has_gravity)) + - _pack_u8(int(is_item)) + _pack_u8(int(is_falling_block)) + - _pack_u16(block_state)) - resp = self._ipc.send_command(cmd) - return resp is not None and _unpack_u32(resp) == STATUS_OK - - def remove_entity(self, entity_id: int): - cmd = _pack_u8(CMD_REMOVE_ENTITY) + _pack_i32(entity_id) - resp = self._ipc.send_command(cmd) - return resp is not None and _unpack_u32(resp) == STATUS_OK - - def set_blocks(self, blocks: list): - """Set block data. blocks: list of (x, y, z, block_state) tuples.""" - payload = _pack_u32(len(blocks)) - for x, y, z, bs in blocks: - payload += _pack_i32(x) + _pack_i32(y) + _pack_i32(z) + _pack_u16(bs) - cmd = _pack_u8(CMD_SET_BLOCKS) + payload - resp = self._ipc.send_command(cmd) - return resp is not None and _unpack_u32(resp) == STATUS_OK - - def tick_fluids(self) -> list: - cmd = _pack_u8(CMD_TICK_FLUIDS) - resp = self._ipc.send_command(cmd) - if not resp or _unpack_u32(resp) != STATUS_OK: - return [] - - offset = 4 - count = _unpack_u32(resp, offset) - offset += 4 - updates = [] - for _ in range(count): - fx = _unpack_i32(resp, offset); offset += 4 - fy = _unpack_i32(resp, offset); offset += 4 - fz = _unpack_i32(resp, offset); offset += 4 - fbs = _unpack_u16(resp, offset); offset += 2 - flv = struct.unpack_from(' bool: - """Check if native acceleration is available.""" - return self._mode != "none" - - @property - def mode(self) -> str: - """Get the current mode: 'ipc', 'direct', or 'none'.""" - return self._mode - - def tick(self): - """Process one native tick (redstone + physics).""" - if self.redstone is not None: - return self.redstone.tick() - return [] - - def shutdown(self): - """Shut down the native acceleration layer.""" - if self._ipc: - self._ipc.shutdown() - self._ipc = None - - # Direct mode engines clean up in their __del__ - if self.redstone and hasattr(self.redstone, 'destroy'): - self.redstone.destroy() - if self.lighting and hasattr(self.lighting, 'destroy'): - self.lighting.destroy() - if self.physics and hasattr(self.physics, 'destroy'): - self.physics.destroy() - - self._mode = "none" - self.redstone = None - self.lighting = None - self.physics = None - - def __del__(self): - self.shutdown() diff --git a/native/bindings/pymc_native_api.cpp b/native/bindings/pymc_native_api.cpp deleted file mode 100755 index 53ae79a..0000000 --- a/native/bindings/pymc_native_api.cpp +++ /dev/null @@ -1,347 +0,0 @@ -// ============================================================ -// PyMC - C API Bridge Implementation -// Implements the C-callable API defined in pymc_native_api.h -// ============================================================ - -#include "pymc_native_api.h" -#include "../core/ipc_shm.h" -#include "../redstone/redstone_engine.h" -#include "../lighting/light_engine.h" -#include "../physics/physics_engine.h" - -#include -#include - -// =========================================================== -// Version Info -// =========================================================== - -static const char kVersion[] = "1.0.0"; -static constexpr uint32_t kApiVersion = 1; - -PYMC_EXPORT const char* pymc_get_version() { return kVersion; } -PYMC_EXPORT uint32_t pymc_get_api_version() { return kApiVersion; } - -// =========================================================== -// Shared Memory IPC Functions -// =========================================================== - -PYMC_EXPORT void* pymc_ipc_channel_create(const char* name, - uint32_t cmd_size, - uint32_t resp_size, - int create) { - try { - auto* channel = new pymc::IPCChannel(name, cmd_size, resp_size, create != 0); - if (!channel->is_valid()) { - delete channel; - return nullptr; - } - return channel; - } catch (...) { - return nullptr; - } -} - -PYMC_EXPORT void pymc_ipc_channel_destroy(void* handle) { - if (handle) { - delete static_cast(handle); - } -} - -PYMC_EXPORT int pymc_ipc_send_command(void* handle, - const uint8_t* data, - uint32_t len) { - auto* channel = static_cast(handle); - return channel && channel->send_command(data, len) ? 1 : 0; -} - -PYMC_EXPORT uint32_t pymc_ipc_recv_response(void* handle, - uint8_t* buffer, - uint32_t max_len) { - auto* channel = static_cast(handle); - if (!channel) return 0; - return static_cast(channel->recv_response(buffer, max_len)); -} - -PYMC_EXPORT uint32_t pymc_ipc_recv_command(void* handle, - uint8_t* buffer, - uint32_t max_len) { - auto* channel = static_cast(handle); - if (!channel) return 0; - return static_cast(channel->recv_command(buffer, max_len)); -} - -PYMC_EXPORT int pymc_ipc_send_response(void* handle, - const uint8_t* data, - uint32_t len) { - auto* channel = static_cast(handle); - return channel && channel->send_response(data, len) ? 1 : 0; -} - -PYMC_EXPORT int pymc_ipc_wait_for_command(void* handle, int timeout_ms) { - auto* channel = static_cast(handle); - return channel && channel->wait_for_command(timeout_ms) ? 1 : 0; -} - -PYMC_EXPORT int pymc_ipc_wait_for_response(void* handle, int timeout_ms) { - auto* channel = static_cast(handle); - return channel && channel->wait_for_response(timeout_ms) ? 1 : 0; -} - -PYMC_EXPORT int pymc_ipc_is_valid(void* handle) { - auto* channel = static_cast(handle); - return channel && channel->is_valid() ? 1 : 0; -} - -// =========================================================== -// Redstone Engine -// =========================================================== - -PYMC_EXPORT void* pymc_redstone_create() { - try { - return new pymc::RedstoneEngine(); - } catch (...) { - return nullptr; - } -} - -PYMC_EXPORT void pymc_redstone_destroy(void* engine) { - if (engine) { - delete static_cast(engine); - } -} - -PYMC_EXPORT void pymc_redstone_add_component(void* engine, - int32_t x, int32_t y, int32_t z, - uint8_t type, uint8_t facing) { - auto* e = static_cast(engine); - if (e) { - e->add_component(x, y, z, - static_cast(type), - static_cast(facing)); - } -} - -PYMC_EXPORT void pymc_redstone_remove_component(void* engine, - int32_t x, int32_t y, int32_t z) { - auto* e = static_cast(engine); - if (e) { - e->remove_component(x, y, z); - } -} - -PYMC_EXPORT void pymc_redstone_set_power(void* engine, - int32_t x, int32_t y, int32_t z, - int32_t level) { - auto* e = static_cast(engine); - if (e) { - e->set_power_level(x, y, z, level); - } -} - -PYMC_EXPORT int32_t pymc_redstone_get_power(void* engine, - int32_t x, int32_t y, int32_t z) { - auto* e = static_cast(engine); - if (e) { - return e->get_power_level(x, y, z); - } - return 0; -} - -PYMC_EXPORT uint32_t pymc_redstone_tick(void* engine, - int32_t* out_updates, - uint32_t max_updates) { - auto* e = static_cast(engine); - if (!e) return 0; - - auto updates = e->tick(); - uint32_t count = std::min(static_cast(updates.size()), max_updates); - - for (uint32_t i = 0; i < count; i++) { - out_updates[i * 5 + 0] = updates[i].x; - out_updates[i * 5 + 1] = updates[i].y; - out_updates[i * 5 + 2] = updates[i].z; - out_updates[i * 5 + 3] = updates[i].new_block_state; - out_updates[i * 5 + 4] = updates[i].flags; - } - - return count; -} - -PYMC_EXPORT void pymc_redstone_clear(void* engine) { - auto* e = static_cast(engine); - if (e) { - e->clear(); - } -} - -// =========================================================== -// Light Engine -// =========================================================== - -PYMC_EXPORT void* pymc_light_create() { - try { - return new pymc::LightEngine(); - } catch (...) { - return nullptr; - } -} - -PYMC_EXPORT void pymc_light_destroy(void* engine) { - if (engine) { - delete static_cast(engine); - } -} - -PYMC_EXPORT void pymc_light_calculate_chunk(void* engine, - const uint16_t* blocks, - uint8_t* sky_light_out, - uint8_t* block_light_out) { - auto* e = static_cast(engine); - if (e) { - e->calculate_chunk_lighting(blocks, sky_light_out, block_light_out); - } -} - -PYMC_EXPORT uint32_t pymc_light_update_block(void* engine, - int32_t x, int32_t y, int32_t z, - uint16_t old_block, uint16_t new_block, - int32_t* out_updates, - uint32_t max_updates) { - auto* e = static_cast(engine); - if (!e) return 0; - - auto updates = e->update_block_light(x, y, z, old_block, new_block); - uint32_t count = std::min(static_cast(updates.size()), max_updates); - - for (uint32_t i = 0; i < count; i++) { - out_updates[i * 5 + 0] = updates[i].x; - out_updates[i * 5 + 1] = updates[i].y; - out_updates[i * 5 + 2] = updates[i].z; - out_updates[i * 5 + 3] = updates[i].new_sky_light; - out_updates[i * 5 + 4] = updates[i].new_block_light; - } - - return count; -} - -PYMC_EXPORT void pymc_light_set_block_info(void* engine, - uint16_t block_state, - uint8_t sky_type, - uint8_t block_type, - uint8_t emitted_light, - uint8_t filter_level) { - auto* e = static_cast(engine); - if (e) { - pymc::BlockLightInfo info; - info.sky_type = static_cast(sky_type); - info.block_type = static_cast(block_type); - info.emitted_light = emitted_light; - info.filter_level = filter_level; - e->set_block_info(block_state, info); - } -} - -// =========================================================== -// Physics Engine -// =========================================================== - -PYMC_EXPORT void* pymc_physics_create() { - try { - return new pymc::PhysicsEngine(); - } catch (...) { - return nullptr; - } -} - -PYMC_EXPORT void pymc_physics_destroy(void* engine) { - if (engine) { - delete static_cast(engine); - } -} - -PYMC_EXPORT void pymc_physics_set_entity(void* engine, - const struct PymcPhysicsEntity* entity) { - auto* e = static_cast(engine); - if (!e || !entity) return; - - pymc::PhysicsEntity pe; - pe.entity_id = entity->entity_id; - pe.x = entity->x; - pe.y = entity->y; - pe.z = entity->z; - pe.vx = entity->vx; - pe.vy = entity->vy; - pe.vz = entity->vz; - pe.bounding_box = { - entity->bb_min_x, entity->bb_min_y, entity->bb_min_z, - entity->bb_max_x, entity->bb_max_y, entity->bb_max_z - }; - pe.on_ground = entity->on_ground != 0; - pe.has_gravity = entity->has_gravity != 0; - pe.is_item = entity->is_item != 0; - pe.is_falling_block = entity->is_falling_block != 0; - pe.block_state = entity->block_state; - - e->set_entity(pe); -} - -PYMC_EXPORT void pymc_physics_remove_entity(void* engine, int32_t entity_id) { - auto* e = static_cast(engine); - if (e) { - e->remove_entity(entity_id); - } -} - -PYMC_EXPORT void pymc_physics_set_blocks(void* engine, - const int32_t* xyz_data, - const uint16_t* block_states, - uint32_t count) { - auto* e = static_cast(engine); - if (!e) return; - - std::vector blocks(count); - for (uint32_t i = 0; i < count; i++) { - blocks[i].x = xyz_data[i * 3]; - blocks[i].y = xyz_data[i * 3 + 1]; - blocks[i].z = xyz_data[i * 3 + 2]; - blocks[i].block_state = block_states[i]; - } - - e->set_blocks(blocks); -} - -PYMC_EXPORT uint32_t pymc_physics_tick(void* engine, - struct PymcPhysicsUpdate* out_updates, - uint32_t max_updates) { - auto* e = static_cast(engine); - if (!e) return 0; - - auto updates = e->tick(); - uint32_t count = std::min(static_cast(updates.size()), max_updates); - - for (uint32_t i = 0; i < count; i++) { - out_updates[i].entity_id = updates[i].entity_id; - out_updates[i].new_x = updates[i].new_x; - out_updates[i].new_y = updates[i].new_y; - out_updates[i].new_z = updates[i].new_z; - out_updates[i].new_vx = updates[i].new_vx; - out_updates[i].new_vy = updates[i].new_vy; - out_updates[i].new_vz = updates[i].new_vz; - out_updates[i].on_ground = updates[i].on_ground ? 1 : 0; - out_updates[i].landed = updates[i].landed ? 1 : 0; - out_updates[i].landed_block_state = updates[i].landed_block_state; - out_updates[i].landed_x = updates[i].landed_x; - out_updates[i].landed_y = updates[i].landed_y; - out_updates[i].landed_z = updates[i].landed_z; - } - - return count; -} - -PYMC_EXPORT void pymc_physics_clear_blocks(void* engine) { - auto* e = static_cast(engine); - if (e) { - e->clear_blocks(); - } -} diff --git a/native/bindings/pymc_native_api.h b/native/bindings/pymc_native_api.h deleted file mode 100755 index 9ea11d9..0000000 --- a/native/bindings/pymc_native_api.h +++ /dev/null @@ -1,227 +0,0 @@ -// ============================================================ -// PyMC - C API Bridge for Python Bindings -// -// This header defines a C-compatible API that can be called -// from Python via ctypes/cffi. It provides both: -// 1. Direct in-process engine access (loaded as shared lib) -// 2. Shared memory IPC functions for out-of-process communication -// -// The shared library can be used in two modes: -// A) Direct: Python loads the .so and calls engine functions directly -// B) IPC: Python starts the native server process and communicates -// via shared memory ring buffers -// ============================================================ - -#ifndef PYMC_NATIVE_API_H -#define PYMC_NATIVE_API_H - -#include -#include - -#ifdef _WIN32 -#define PYMC_EXPORT __declspec(dllexport) -#else -#define PYMC_EXPORT __attribute__((visibility("default"))) -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -// =========================================================== -// Shared Memory IPC Functions -// =========================================================== - -// Create a shared memory IPC channel. -// Returns: opaque handle, or NULL on failure. -// name: unique name for the SHM objects -// cmd_size: size of command buffer in bytes -// resp_size: size of response buffer in bytes -// create: 1 = creator (Python side), 0 = opener (C++ side) -PYMC_EXPORT void* pymc_ipc_channel_create(const char* name, - uint32_t cmd_size, - uint32_t resp_size, - int create); - -// Destroy an IPC channel. -PYMC_EXPORT void pymc_ipc_channel_destroy(void* handle); - -// Send a command (Python -> C++). -// Returns: 1 on success, 0 if buffer full. -PYMC_EXPORT int pymc_ipc_send_command(void* handle, - const uint8_t* data, - uint32_t len); - -// Receive a response (C++ -> Python). -// Returns: number of bytes read, 0 if empty. -PYMC_EXPORT uint32_t pymc_ipc_recv_response(void* handle, - uint8_t* buffer, - uint32_t max_len); - -// Receive a command (C++ side). -// Returns: number of bytes read, 0 if empty. -PYMC_EXPORT uint32_t pymc_ipc_recv_command(void* handle, - uint8_t* buffer, - uint32_t max_len); - -// Send a response (C++ side). -// Returns: 1 on success, 0 if buffer full. -PYMC_EXPORT int pymc_ipc_send_response(void* handle, - const uint8_t* data, - uint32_t len); - -// Wait for data with timeout. -// Returns: 1 if data available, 0 on timeout. -PYMC_EXPORT int pymc_ipc_wait_for_command(void* handle, int timeout_ms); -PYMC_EXPORT int pymc_ipc_wait_for_response(void* handle, int timeout_ms); - -// Check if channel is valid. -PYMC_EXPORT int pymc_ipc_is_valid(void* handle); - -// =========================================================== -// Direct Engine Access (In-Process Mode) -// =========================================================== - -// --- Redstone Engine --- - -// Create/destroy a redstone engine instance. -PYMC_EXPORT void* pymc_redstone_create(); -PYMC_EXPORT void pymc_redstone_destroy(void* engine); - -// Add a redstone component. -// type: 0=wire, 1=torch, 2=repeater, 3=comparator, 4=piston, -// 5=sticky_piston, 6=observer, 7=lever, 8=button, -// 9=pressure_plate, 10=weighted_pressure_plate, -// 11=tripwire_hook, 12=tripwire, 13=daylight_detector, -// 14=redstone_block, 15=target, 16=lectern -// facing: 0=down, 1=up, 2=north, 3=south, 4=west, 5=east -PYMC_EXPORT void pymc_redstone_add_component(void* engine, - int32_t x, int32_t y, int32_t z, - uint8_t type, uint8_t facing); - -// Remove a redstone component. -PYMC_EXPORT void pymc_redstone_remove_component(void* engine, - int32_t x, int32_t y, int32_t z); - -// Set the power level of a component. -PYMC_EXPORT void pymc_redstone_set_power(void* engine, - int32_t x, int32_t y, int32_t z, - int32_t level); - -// Get the power level of a component. -PYMC_EXPORT int32_t pymc_redstone_get_power(void* engine, - int32_t x, int32_t y, int32_t z); - -// Process one redstone tick. -// out_updates: buffer to receive updates (array of int32_t, 5 per update: x,y,z,new_state,flags) -// max_updates: maximum number of updates to return -// Returns: actual number of updates written. -PYMC_EXPORT uint32_t pymc_redstone_tick(void* engine, - int32_t* out_updates, - uint32_t max_updates); - -// Clear all components. -PYMC_EXPORT void pymc_redstone_clear(void* engine); - -// --- Light Engine --- - -// Create/destroy a light engine instance. -PYMC_EXPORT void* pymc_light_create(); -PYMC_EXPORT void pymc_light_destroy(void* engine); - -// Calculate lighting for an entire chunk. -// blocks: flat array of 98304 uint16_t (y*256+z*16+x ordering) -// sky_light_out: output, LIGHT_SECTIONS * 4096 bytes -// block_light_out: output, LIGHT_SECTIONS * 4096 bytes -PYMC_EXPORT void pymc_light_calculate_chunk(void* engine, - const uint16_t* blocks, - uint8_t* sky_light_out, - uint8_t* block_light_out); - -// Incremental update when a block changes. -// out_updates: buffer for LightUpdate structs (5 int32_t each: x,y,z,sky_light,block_light) -// max_updates: max number of updates -// Returns: actual number of updates. -PYMC_EXPORT uint32_t pymc_light_update_block(void* engine, - int32_t x, int32_t y, int32_t z, - uint16_t old_block, uint16_t new_block, - int32_t* out_updates, - uint32_t max_updates); - -// Register custom block light info. -PYMC_EXPORT void pymc_light_set_block_info(void* engine, - uint16_t block_state, - uint8_t sky_type, - uint8_t block_type, - uint8_t emitted_light, - uint8_t filter_level); - -// --- Physics Engine --- - -// Create/destroy a physics engine instance. -PYMC_EXPORT void* pymc_physics_create(); -PYMC_EXPORT void pymc_physics_destroy(void* engine); - -// Entity data for set_entity -struct PymcPhysicsEntity { - int32_t entity_id; - double x, y, z; - double vx, vy, vz; - double bb_min_x, bb_min_y, bb_min_z; - double bb_max_x, bb_max_y, bb_max_z; - uint8_t on_ground; - uint8_t has_gravity; - uint8_t is_item; - uint8_t is_falling_block; - uint16_t block_state; -}; - -// Physics update result -struct PymcPhysicsUpdate { - int32_t entity_id; - double new_x, new_y, new_z; - double new_vx, new_vy, new_vz; - uint8_t on_ground; - uint8_t landed; - uint16_t landed_block_state; - int32_t landed_x, landed_y, landed_z; -}; - -// Set an entity. -PYMC_EXPORT void pymc_physics_set_entity(void* engine, - const struct PymcPhysicsEntity* entity); - -// Remove an entity. -PYMC_EXPORT void pymc_physics_remove_entity(void* engine, int32_t entity_id); - -// Set block data for collision. -// blocks: array of {int32_t x, int32_t y, int32_t z, uint16_t block_state} -// count: number of entries -PYMC_EXPORT void pymc_physics_set_blocks(void* engine, - const int32_t* xyz_data, - const uint16_t* block_states, - uint32_t count); - -// Process one physics tick. -// out_updates: buffer for PymcPhysicsUpdate results -// max_updates: max number of results -// Returns: actual number of updates. -PYMC_EXPORT uint32_t pymc_physics_tick(void* engine, - struct PymcPhysicsUpdate* out_updates, - uint32_t max_updates); - -// Clear all block data. -PYMC_EXPORT void pymc_physics_clear_blocks(void* engine); - -// =========================================================== -// Version Info -// =========================================================== - -PYMC_EXPORT const char* pymc_get_version(); -PYMC_EXPORT uint32_t pymc_get_api_version(); - -#ifdef __cplusplus -} -#endif - -#endif // PYMC_NATIVE_API_H diff --git a/native/core/ipc_shm.cpp b/native/core/ipc_shm.cpp deleted file mode 100755 index 72b46c0..0000000 --- a/native/core/ipc_shm.cpp +++ /dev/null @@ -1,438 +0,0 @@ -// ============================================================ -// PyMC - Shared Memory IPC Implementation -// Lock-free ring buffer over shared memory for zero-copy IPC -// ============================================================ - -#include "ipc_shm.h" - -#include -#include -#include -#include -#include -#include -#include - -namespace pymc { - -// ----------------------------------------------------------- -// Helper: page-aligned size -// ----------------------------------------------------------- -static size_t page_align(size_t sz) { -#ifdef _WIN32 - SYSTEM_INFO si; - GetSystemInfo(&si); - size_t page = si.dwPageSize; -#else - long page = sysconf(_SC_PAGESIZE); - if (page <= 0) page = 4096; -#endif - return ((sz + static_cast(page) - 1) / static_cast(page)) - * static_cast(page); -} - -// ----------------------------------------------------------- -// Helper: next power of 2 -// ----------------------------------------------------------- -static uint32_t next_pow2(uint32_t v) { - v--; - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - v++; - return v; -} - -// =========================================================== -// SharedMemoryIPC implementation -// =========================================================== - -SharedMemoryIPC::SharedMemoryIPC(const char* name, size_t size, bool create) - : name_(name) - , size_(page_align(std::max(size, static_cast(4096)))) - , creator_(create) - , valid_(false) -#ifdef _WIN32 - , shm_handle_(NULL) -#else - , fd_(-1) -#endif - , mapped_(nullptr) - , ring_(nullptr) - , data_(nullptr) -{ -#ifdef _WIN32 - // Windows: CreateFileMapping / OpenFileMapping - if (creator_) { - shm_handle_ = CreateFileMappingA( - INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, - static_cast(size_ >> 32), - static_cast(size_ & 0xFFFFFFFF), - name); - } else { - shm_handle_ = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, name); - } - - if (!shm_handle_) { - fprintf(stderr, "[PYMC IPC] CreateFileMapping/OpenFileMapping failed for '%s': %lu\n", - name, GetLastError()); - return; - } - - mapped_ = MapViewOfFile(shm_handle_, FILE_MAP_ALL_ACCESS, 0, 0, size_); - if (!mapped_) { - fprintf(stderr, "[PYMC IPC] MapViewOfFile failed for '%s': %lu\n", - name, GetLastError()); - CloseHandle(shm_handle_); - shm_handle_ = NULL; - return; - } -#else - // Linux/POSIX: shm_open / mmap - fd_ = shm_open(name, O_RDWR | (create ? O_CREAT : 0), 0666); - if (fd_ < 0) { - fprintf(stderr, "[PYMC IPC] shm_open failed for '%s': %s\n", - name, strerror(errno)); - return; - } - - if (create) { - if (ftruncate(fd_, static_cast(size_)) != 0) { - fprintf(stderr, "[PYMC IPC] ftruncate failed for '%s': %s\n", - name, strerror(errno)); - ::close(fd_); - fd_ = -1; - return; - } - } - - mapped_ = mmap(nullptr, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0); - if (mapped_ == MAP_FAILED) { - fprintf(stderr, "[PYMC IPC] mmap failed for '%s': %s\n", - name, strerror(errno)); - mapped_ = nullptr; - ::close(fd_); - fd_ = -1; - return; - } - - // On Linux we can close fd after mmap; the mapping stays valid. - // But we keep it open for potential resizing later. -#endif - - ring_ = static_cast(mapped_); - data_ = reinterpret_cast(mapped_) + sizeof(RingBufferHeader); - - if (create) { - init_ring_buffer(); - } - - valid_ = true; -} - -SharedMemoryIPC::~SharedMemoryIPC() { - cleanup(); -} - -void SharedMemoryIPC::init_ring_buffer() { - // Compute usable capacity (everything after the header) - uint32_t usable = static_cast(size_ - sizeof(RingBufferHeader)); - // Round down to power of 2 for fast modulo - uint32_t cap = next_pow2(usable); - if (cap > usable) cap >>= 1; // Don't exceed actual space - if (cap < 64) cap = 64; // Minimum useful size - - // Zero out the entire region first - std::memset(mapped_, 0, size_); - - ring_->capacity = cap; - ring_->mask = cap - 1; - ring_->write_pos.store(0, std::memory_order_relaxed); - ring_->read_pos.store(0, std::memory_order_relaxed); -} - -void SharedMemoryIPC::cleanup() { - if (mapped_) { -#ifdef _WIN32 - UnmapViewOfFile(mapped_); - if (shm_handle_) { - CloseHandle(shm_handle_); - shm_handle_ = NULL; - } -#else - munmap(mapped_, size_); - if (fd_ >= 0) { - // If we're the creator, unlink the shared memory - if (creator_) { - shm_unlink(name_.c_str()); - } - ::close(fd_); - fd_ = -1; - } -#endif - mapped_ = nullptr; - ring_ = nullptr; - data_ = nullptr; - } - valid_ = false; -} - -// ---- Write operations ---- - -bool SharedMemoryIPC::write(const void* data, size_t len) { - // Message = [4-byte LE length][payload] - size_t total = 4 + len; - if (total > free_bytes()) return false; - - uint32_t wp = ring_->write_pos.load(std::memory_order_relaxed); - uint32_t mask = ring_->mask; - uint32_t cap = ring_->capacity; - - // Write length prefix (little-endian) - uint32_t le_len = static_cast(len); - uint8_t len_bytes[4] = { - static_cast(le_len & 0xFF), - static_cast((le_len >> 8) & 0xFF), - static_cast((le_len >> 16) & 0xFF), - static_cast((le_len >> 24) & 0xFF), - }; - - // Write length prefix (may wrap) - for (int i = 0; i < 4; i++) { - data_[(wp + i) & mask] = len_bytes[i]; - } - - // Write payload (may wrap) - const uint8_t* src = static_cast(data); - uint32_t start = (wp + 4) & mask; - - if (start + len <= cap) { - // No wrap - std::memcpy(data_ + start, src, len); - } else { - // Wraps around - uint32_t first = cap - start; - std::memcpy(data_ + start, src, first); - std::memcpy(data_, src + first, len - first); - } - - // Publish with release semantics so consumer sees the data - ring_->write_pos.store((wp + static_cast(total)) & mask, - std::memory_order_release); - return true; -} - -bool SharedMemoryIPC::write_raw(const void* data, size_t len) { - if (len > free_bytes()) return false; - - uint32_t wp = ring_->write_pos.load(std::memory_order_relaxed); - uint32_t mask = ring_->mask; - uint32_t cap = ring_->capacity; - - const uint8_t* src = static_cast(data); - - if (wp + len <= cap) { - std::memcpy(data_ + wp, src, len); - } else { - uint32_t first = cap - wp; - std::memcpy(data_ + wp, src, first); - std::memcpy(data_, src + first, len - first); - } - - ring_->write_pos.store((wp + static_cast(len)) & mask, - std::memory_order_release); - return true; -} - -// ---- Read operations ---- - -size_t SharedMemoryIPC::read(void* buffer, size_t max_len) { - if (!has_message()) return 0; - - uint32_t rp = ring_->read_pos.load(std::memory_order_relaxed); - uint32_t mask = ring_->mask; - uint32_t cap = ring_->capacity; - - // Read length prefix - uint8_t len_bytes[4]; - for (int i = 0; i < 4; i++) { - len_bytes[i] = data_[(rp + i) & mask]; - } - uint32_t msg_len = static_cast(len_bytes[0]) - | (static_cast(len_bytes[1]) << 8) - | (static_cast(len_bytes[2]) << 16) - | (static_cast(len_bytes[3]) << 24); - - if (msg_len > max_len) { - // Buffer too small — still consume the message - // Skip over it entirely - uint32_t total = 4 + msg_len; - ring_->read_pos.store((rp + total) & mask, std::memory_order_release); - return 0; - } - - // Read payload - uint8_t* dst = static_cast(buffer); - uint32_t start = (rp + 4) & mask; - - if (start + msg_len <= cap) { - std::memcpy(dst, data_ + start, msg_len); - } else { - uint32_t first = cap - start; - std::memcpy(dst, data_ + start, first); - std::memcpy(dst + first, data_, msg_len - first); - } - - uint32_t total = 4 + msg_len; - ring_->read_pos.store((rp + total) & mask, std::memory_order_release); - return msg_len; -} - -size_t SharedMemoryIPC::read_raw(void* buffer, size_t len) { - uint32_t avail = used_bytes(); - if (avail == 0) return 0; - - size_t to_read = std::min(len, static_cast(avail)); - uint32_t rp = ring_->read_pos.load(std::memory_order_relaxed); - uint32_t mask = ring_->mask; - uint32_t cap = ring_->capacity; - - uint8_t* dst = static_cast(buffer); - - if (rp + to_read <= cap) { - std::memcpy(dst, data_ + rp, to_read); - } else { - uint32_t first = cap - rp; - std::memcpy(dst, data_ + rp, first); - std::memcpy(dst + first, data_, to_read - first); - } - - ring_->read_pos.store((rp + static_cast(to_read)) & mask, - std::memory_order_release); - return to_read; -} - -uint32_t SharedMemoryIPC::peek_message_len() const { - uint32_t wp = ring_->write_pos.load(std::memory_order_acquire); - uint32_t rp = ring_->read_pos.load(std::memory_order_acquire); - - // Calculate available bytes - uint32_t used = (wp >= rp) ? (wp - rp) : (ring_->capacity - rp + wp); - if (used < 4) return 0; // Not even a complete length prefix - - uint32_t mask = ring_->mask; - uint8_t len_bytes[4]; - for (int i = 0; i < 4; i++) { - len_bytes[i] = data_[(rp + i) & mask]; - } - uint32_t msg_len = static_cast(len_bytes[0]) - | (static_cast(len_bytes[1]) << 8) - | (static_cast(len_bytes[2]) << 16) - | (static_cast(len_bytes[3]) << 24); - - // Check if the full message payload is available - if (used < 4 + msg_len) return 0; - - return msg_len; -} - -// ---- Synchronization ---- - -bool SharedMemoryIPC::wait_for_data(int timeout_ms) { - auto deadline = std::chrono::steady_clock::now() - + std::chrono::milliseconds(timeout_ms); - - // Spin phase: ~1000 iterations (~1-10 µs) - for (int i = 0; i < 1000; i++) { - if (used_bytes() > 0) return true; - } - - // Yield phase: exponential backoff - int sleep_us = 10; - while (true) { - if (used_bytes() > 0) return true; - if (std::chrono::steady_clock::now() >= deadline) return false; - - std::this_thread::sleep_for(std::chrono::microseconds(sleep_us)); - sleep_us = std::min(sleep_us * 2, 1000); // Cap at 1ms - } -} - -bool SharedMemoryIPC::has_message() const { - uint32_t wp = ring_->write_pos.load(std::memory_order_acquire); - uint32_t rp = ring_->read_pos.load(std::memory_order_acquire); - uint32_t used = (wp >= rp) ? (wp - rp) : (ring_->capacity - rp + wp); - - if (used < 4) return false; // No length prefix - - uint32_t mask = ring_->mask; - uint8_t len_bytes[4]; - for (int i = 0; i < 4; i++) { - len_bytes[i] = data_[(rp + i) & mask]; - } - uint32_t msg_len = static_cast(len_bytes[0]) - | (static_cast(len_bytes[1]) << 8) - | (static_cast(len_bytes[2]) << 16) - | (static_cast(len_bytes[3]) << 24); - - return used >= 4 + msg_len; -} - -uint32_t SharedMemoryIPC::used_bytes() const { - uint32_t wp = ring_->write_pos.load(std::memory_order_acquire); - uint32_t rp = ring_->read_pos.load(std::memory_order_acquire); - return (wp >= rp) ? (wp - rp) : (ring_->capacity - rp + wp); -} - -uint32_t SharedMemoryIPC::free_bytes() const { - uint32_t wp = ring_->write_pos.load(std::memory_order_acquire); - uint32_t rp = ring_->read_pos.load(std::memory_order_acquire); - uint32_t used = (wp >= rp) ? (wp - rp) : (ring_->capacity - rp + wp); - return ring_->capacity - used - 1; // -1 because full == empty in ring buffer -} - -// =========================================================== -// IPCChannel implementation -// =========================================================== - -IPCChannel::IPCChannel(const char* name, size_t cmd_size, size_t resp_size, bool create) { - std::string cmd_name = std::string(name) + "_cmd"; - std::string resp_name = std::string(name) + "_resp"; - - cmd_ = std::make_unique(cmd_name.c_str(), cmd_size, create); - resp_ = std::make_unique(resp_name.c_str(), resp_size, create); -} - -IPCChannel::~IPCChannel() = default; - -bool IPCChannel::send_command(const void* data, size_t len) { - return cmd_->write(data, len); -} - -size_t IPCChannel::recv_response(void* buffer, size_t max_len) { - return resp_->read(buffer, max_len); -} - -size_t IPCChannel::recv_command(void* buffer, size_t max_len) { - return cmd_->read(buffer, max_len); -} - -bool IPCChannel::send_response(const void* data, size_t len) { - return resp_->write(data, len); -} - -bool IPCChannel::wait_for_command(int timeout_ms) { - return cmd_->wait_for_data(timeout_ms); -} - -bool IPCChannel::wait_for_response(int timeout_ms) { - return resp_->wait_for_data(timeout_ms); -} - -bool IPCChannel::is_valid() const { - return cmd_ && cmd_->is_valid() && resp_ && resp_->is_valid(); -} - -} // namespace pymc diff --git a/native/core/ipc_shm.h b/native/core/ipc_shm.h deleted file mode 100755 index d8d5732..0000000 --- a/native/core/ipc_shm.h +++ /dev/null @@ -1,187 +0,0 @@ -// ============================================================ -// PyMC - Shared Memory IPC Layer -// Lock-free ring buffer over POSIX shared memory (Linux) -// or CreateFileMapping (Windows) for zero-copy Python<->C++ IPC -// -// Architecture: -// - Two ring buffers per channel: one for commands (Python->C++), -// one for responses (C++->Python) -// - Each message is length-prefixed: [uint32_t len][payload...] -// - Lock-free via atomic read/write positions with proper -// memory ordering (acquire/release semantics) -// - Cache-line aligned positions to avoid false sharing -// ============================================================ - -#ifndef PYMC_IPC_SHM_H -#define PYMC_IPC_SHM_H - -#include -#include -#include -#include -#include - -#ifdef _WIN32 -// Prevent windows.h from defining min/max macros that conflict with -// std::min / std::max (MSVC error C2589). -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include -#else -#include -#include -#include -#include -#include -#include -#endif - -namespace pymc { - -// ----------------------------------------------------------- -// Ring buffer header — lives at the start of the shared region -// ----------------------------------------------------------- -struct RingBufferHeader { - // Cache-line aligned to prevent false sharing between - // the producer (write_pos) and consumer (read_pos). - alignas(64) std::atomic write_pos; // next slot to write - alignas(64) std::atomic read_pos; // next slot to read - uint32_t capacity; // total buffer capacity in bytes (must be power of 2) - uint32_t mask; // capacity - 1, for fast modulo - // data[] follows immediately after this header -}; - -// ----------------------------------------------------------- -// SharedMemoryIPC — manages a single shared memory region -// containing a lock-free SPSC ring buffer. -// -// Usage pattern: -// Python side: create=true, writes commands, reads responses -// C++ side: create=false, reads commands, writes responses -// -// For bidirectional communication, create TWO SharedMemoryIPC -// instances (one per direction) sharing the same SHM name -// with different suffixes. -// ----------------------------------------------------------- -class SharedMemoryIPC { -public: - // Create or open a shared memory ring buffer. - // name: unique name for the shared memory object - // size: total size including header (must be >= 4096, will be rounded to page) - // create: true = creator (Python side), false = opener (C++ side) - SharedMemoryIPC(const char* name, size_t size, bool create); - - ~SharedMemoryIPC(); - - // Non-copyable - SharedMemoryIPC(const SharedMemoryIPC&) = delete; - SharedMemoryIPC& operator=(const SharedMemoryIPC&) = delete; - - // ---- Write side (producer) ---- - - // Write a message to the ring buffer. - // Non-blocking: returns false if not enough space. - // Message format: [4-byte little-endian length][payload] - bool write(const void* data, size_t len); - - // Convenience: write raw bytes without length prefix. - // Used when the consumer knows the expected size. - bool write_raw(const void* data, size_t len); - - // ---- Read side (consumer) ---- - - // Read the next message from the ring buffer. - // Returns the number of payload bytes read, or 0 if empty/insufficient buffer. - // The 4-byte length prefix is consumed automatically. - size_t read(void* buffer, size_t max_len); - - // Read raw bytes (no length prefix). - // Returns number of bytes actually read (may be < len if buffer empty). - size_t read_raw(void* buffer, size_t len); - - // Peek at the next message length without consuming it. - // Returns 0 if no complete message is available. - uint32_t peek_message_len() const; - - // ---- Synchronization ---- - - // Block until data is available or timeout expires. - // Uses a lightweight spin-wait with exponential backoff. - // Returns true if data is available, false on timeout. - bool wait_for_data(int timeout_ms); - - // Check if there is at least one complete message available. - bool has_message() const; - - // Get the number of bytes used in the ring buffer. - uint32_t used_bytes() const; - - // Get the number of free bytes available for writing. - uint32_t free_bytes() const; - - // ---- Status ---- - - bool is_valid() const { return mapped_ != nullptr; } - size_t total_size() const { return size_; } - const char* name() const { return name_.c_str(); } - -private: - void init_ring_buffer(); - void cleanup(); - - std::string name_; - size_t size_; - bool creator_; - bool valid_; - -#ifdef _WIN32 - HANDLE shm_handle_; -#else - int fd_; -#endif - - void* mapped_; - RingBufferHeader* ring_; - uint8_t* data_; // points to ring_->data[0] -}; - -// ----------------------------------------------------------- -// IPCChannel — bidirectional channel using two ring buffers -// -// Two shared memory regions are created: -// {name}_cmd : Python writes commands, C++ reads them -// {name}_resp : C++ writes responses, Python reads them -// ----------------------------------------------------------- -class IPCChannel { -public: - IPCChannel(const char* name, size_t cmd_size, size_t resp_size, bool create); - ~IPCChannel(); - - IPCChannel(const IPCChannel&) = delete; - IPCChannel& operator=(const IPCChannel&) = delete; - - // Python side: send command, receive response - bool send_command(const void* data, size_t len); - size_t recv_response(void* buffer, size_t max_len); - - // C++ side: receive command, send response - size_t recv_command(void* buffer, size_t max_len); - bool send_response(const void* data, size_t len); - - // Wait for a command to arrive (C++ side) or response (Python side) - bool wait_for_command(int timeout_ms); - bool wait_for_response(int timeout_ms); - - bool is_valid() const; - - SharedMemoryIPC& cmd_channel() { return *cmd_; } - SharedMemoryIPC& resp_channel() { return *resp_; } - -private: - std::unique_ptr cmd_; - std::unique_ptr resp_; -}; - -} // namespace pymc - -#endif // PYMC_IPC_SHM_H diff --git a/native/lighting/light_engine.cpp b/native/lighting/light_engine.cpp deleted file mode 100755 index 15af78a..0000000 --- a/native/lighting/light_engine.cpp +++ /dev/null @@ -1,414 +0,0 @@ -// ============================================================ -// PyMC - Light Engine Implementation -// BFS-based light propagation with incremental updates -// ============================================================ - -#include "light_engine.h" - -#include -#include -#include -#include - -namespace pymc { - -// =========================================================== -// Default block light properties -// =========================================================== - -// Well-known block IDs (matching terrain_gen.cpp and blocks.py) -static constexpr uint16_t BL_AIR = 0; -static constexpr uint16_t BL_STONE = 1; -static constexpr uint16_t BL_GRASS_BLOCK = 9; -static constexpr uint16_t BL_DIRT = 10; -static constexpr uint16_t BL_BEDROCK = 79; -static constexpr uint16_t BL_WATER = 80; -static constexpr uint16_t BL_LAVA = 96; -static constexpr uint16_t BL_SAND = 112; -static constexpr uint16_t BL_GLASS = 519; -static constexpr uint16_t BL_GLOWSTONE = 922; -static constexpr uint16_t BL_REDSTONE_LAMP_OFF = 923; -static constexpr uint16_t BL_REDSTONE_LAMP_ON = 924; -static constexpr uint16_t BL_TORCH = 1987; -static constexpr uint16_t BL_LANTERN = 2265; -static constexpr uint16_t BL_CAMPFIRE = 1358; -static constexpr uint16_t BL_SOUL_CAMPFIRE = 1359; -static constexpr uint16_t BL_SHROOMLIGHT = 1712; -static constexpr uint16_t BL_SEA_LANTERN = 997; -static constexpr uint16_t BL_CONDUIT = 1199; -static constexpr uint16_t BL_BEACON = 866; -static constexpr uint16_t BL_OAK_LEAVES = 264; -static constexpr uint16_t BL_SPRUCE_LEAVES = 292; -static constexpr uint16_t BL_BIRCH_LEAVES = 320; -static constexpr uint16_t BL_ICE = 655; -static constexpr uint16_t BL_PACKED_ICE = 727; -static constexpr uint16_t BL_FROSTED_ICE = 728; - -// Helper: index into a flat section array [sec][y][z][x] -static inline int light_idx(int sec, int y, int z, int x) { - return ((sec * LIGHT_SECTION_SIZE + y) * LIGHT_SECTION_SIZE + z) * LIGHT_SECTION_SIZE + x; -} - -// Helper: index into flat blocks array [sec][y][z][x] -static inline int block_idx(int sec, int y, int z, int x) { - return ((sec * LIGHT_SECTION_SIZE + y) * LIGHT_SECTION_SIZE + z) * LIGHT_SECTION_SIZE + x; -} - -LightEngine::LightEngine() { - init_default_block_info(); -} - -LightEngine::~LightEngine() = default; - -void LightEngine::init_default_block_info() { - // Air: fully transparent - custom_block_info_[BL_AIR] = {LightType::LIGHT_TRANSPARENT, LightType::LIGHT_TRANSPARENT, 0, 0}; - - // Water: filters light (reduces by 1 extra per block) - custom_block_info_[BL_WATER] = {LightType::LIGHT_FILTER, LightType::LIGHT_FILTER, 0, 1}; - - // Lava: emits block light 15 - custom_block_info_[BL_LAVA] = {LightType::LIGHT_FILTER, LightType::LIGHT_SOURCE, 15, 1}; - - // Glass: transparent to both - custom_block_info_[BL_GLASS] = {LightType::LIGHT_TRANSPARENT, LightType::LIGHT_TRANSPARENT, 0, 0}; - - // Leaves: filter sky and block light - custom_block_info_[BL_OAK_LEAVES] = {LightType::LIGHT_FILTER, LightType::LIGHT_FILTER, 0, 1}; - custom_block_info_[BL_SPRUCE_LEAVES] = {LightType::LIGHT_FILTER, LightType::LIGHT_FILTER, 0, 1}; - custom_block_info_[BL_BIRCH_LEAVES] = {LightType::LIGHT_FILTER, LightType::LIGHT_FILTER, 0, 1}; - - // Light sources - custom_block_info_[BL_GLOWSTONE] = {LightType::LIGHT_FILTER, LightType::LIGHT_SOURCE, 15, 0}; - custom_block_info_[BL_SEA_LANTERN] = {LightType::LIGHT_FILTER, LightType::LIGHT_SOURCE, 15, 0}; - custom_block_info_[BL_SHROOMLIGHT] = {LightType::LIGHT_FILTER, LightType::LIGHT_SOURCE, 15, 0}; - custom_block_info_[BL_TORCH] = {LightType::LIGHT_TRANSPARENT, LightType::LIGHT_SOURCE, 14, 0}; - custom_block_info_[BL_LANTERN] = {LightType::LIGHT_FILTER, LightType::LIGHT_SOURCE, 15, 0}; - custom_block_info_[BL_CAMPFIRE] = {LightType::LIGHT_FILTER, LightType::LIGHT_SOURCE, 15, 0}; - custom_block_info_[BL_SOUL_CAMPFIRE] = {LightType::LIGHT_FILTER, LightType::LIGHT_SOURCE, 10, 0}; - custom_block_info_[BL_CONDUIT] = {LightType::LIGHT_FILTER, LightType::LIGHT_SOURCE, 15, 0}; - custom_block_info_[BL_BEACON] = {LightType::LIGHT_FILTER, LightType::LIGHT_SOURCE, 15, 0}; - custom_block_info_[BL_REDSTONE_LAMP_ON] = {LightType::LIGHT_FILTER, LightType::LIGHT_SOURCE, 15, 0}; - custom_block_info_[BL_FROSTED_ICE] = {LightType::LIGHT_FILTER, LightType::LIGHT_TRANSPARENT, 0, 1}; - custom_block_info_[BL_ICE] = {LightType::LIGHT_FILTER, LightType::LIGHT_TRANSPARENT, 0, 0}; -} - -BlockLightInfo LightEngine::get_block_info(uint16_t block_state) const { - auto it = custom_block_info_.find(block_state); - if (it != custom_block_info_.end()) { - return it->second; - } - - // Default: opaque block - if (block_state == BL_AIR) { - return {LightType::LIGHT_TRANSPARENT, LightType::LIGHT_TRANSPARENT, 0, 0}; - } - - return {LightType::LIGHT_OPAQUE, LightType::LIGHT_OPAQUE, 0, 0}; -} - -void LightEngine::set_block_info(uint16_t block_state, const BlockLightInfo& info) { - custom_block_info_[block_state] = info; -} - -// =========================================================== -// Full chunk lighting calculation -// =========================================================== - -void LightEngine::calculate_chunk_lighting( - const uint16_t* blocks, - uint8_t* sky_light, - uint8_t* block_light -) { - // Initialize all light to 0 - std::memset(sky_light, 0, LIGHT_SECTION_COUNT * SECTION_VOLUME); - std::memset(block_light, 0, LIGHT_SECTION_COUNT * SECTION_VOLUME); - - // Phase 1: Sky light propagation - propagate_sky_light(sky_light, blocks, 0, 0); - - // Phase 2: Block light propagation - propagate_block_light(block_light, blocks); -} - -// =========================================================== -// Sky light propagation -// =========================================================== - -void LightEngine::propagate_sky_light( - uint8_t* sky_light, - const uint16_t* blocks, - int /*chunk_x*/, int /*chunk_z*/ -) { - // Step 1: Initialize sky light from the top. - // Top boundary section (index 25) - for (int z = 0; z < LIGHT_SECTION_SIZE; z++) { - for (int x = 0; x < LIGHT_SECTION_SIZE; x++) { - sky_light[light_idx(25, 0, z, x)] = LIGHT_MAX_LEVEL; - } - } - - // Step 2: Cast columns downward. - std::deque queue; - - for (int z = 0; z < LIGHT_SECTION_SIZE; z++) { - for (int x = 0; x < LIGHT_SECTION_SIZE; x++) { - uint8_t current_light = LIGHT_MAX_LEVEL; - bool blocked = false; - - // Walk down from section 23 (top game section) to 0 (bottom) - for (int sec = LIGHT_CHUNK_SECTIONS - 1; sec >= 0 && !blocked; sec--) { - for (int y = LIGHT_SECTION_SIZE - 1; y >= 0 && !blocked; y--) { - uint16_t block = blocks[block_idx(sec, y, z, x)]; - BlockLightInfo info = get_block_info(block); - - if (info.sky_type == LightType::LIGHT_OPAQUE) { - sky_light[light_idx(sec + 1, y, z, x)] = current_light; - blocked = true; - break; - } - - if (info.sky_type == LightType::LIGHT_FILTER) { - current_light = std::max(0, current_light - 1 - info.filter_level); - } - - sky_light[light_idx(sec + 1, y, z, x)] = current_light; - - if (current_light > 0 && current_light < LIGHT_MAX_LEVEL) { - int world_y = (sec + 1) * LIGHT_SECTION_SIZE + y + LIGHT_MIN_Y; - queue.push_back({x, world_y, z}); - } - } - } - } - } - - // Step 3: BFS propagate sky light horizontally and diagonally. - bfs_propagate(sky_light, blocks, queue, true); -} - -// =========================================================== -// Block light propagation -// =========================================================== - -void LightEngine::propagate_block_light( - uint8_t* block_light, - const uint16_t* blocks -) { - std::deque queue; - - // Find all light sources and seed the BFS - for (int sec = 0; sec < LIGHT_CHUNK_SECTIONS; sec++) { - for (int y = 0; y < LIGHT_SECTION_SIZE; y++) { - for (int z = 0; z < LIGHT_SECTION_SIZE; z++) { - for (int x = 0; x < LIGHT_SECTION_SIZE; x++) { - uint16_t block = blocks[block_idx(sec, y, z, x)]; - BlockLightInfo info = get_block_info(block); - - if (info.block_type == LightType::LIGHT_SOURCE && info.emitted_light > 0) { - block_light[light_idx(sec + 1, y, z, x)] = info.emitted_light; - int world_y = sec * LIGHT_SECTION_SIZE + y + LIGHT_MIN_Y; - queue.push_back({x, world_y, z}); - } - } - } - } - } - - bfs_propagate(block_light, blocks, queue, false); -} - -void LightEngine::bfs_propagate( - uint8_t* light, - const uint16_t* blocks, - std::deque& queue, - bool is_sky_light -) { - // 6-connected neighbors - static constexpr int dx[] = {-1, 1, 0, 0, 0, 0}; - static constexpr int dy[] = {0, 0, -1, 1, 0, 0}; - static constexpr int dz[] = {0, 0, 0, 0, -1, 1}; - - while (!queue.empty()) { - LightPos pos = queue.front(); - queue.pop_front(); - - // Convert world y to section/local coordinates - int local_y = pos.y - LIGHT_MIN_Y; - int sec = local_y / LIGHT_SECTION_SIZE; - int y_in_sec = local_y % LIGHT_SECTION_SIZE; - - if (sec < 0 || sec >= LIGHT_SECTION_COUNT) continue; - if (y_in_sec < 0 || y_in_sec >= LIGHT_SECTION_SIZE) continue; - if (pos.x < 0 || pos.x >= LIGHT_SECTION_SIZE) continue; - if (pos.z < 0 || pos.z >= LIGHT_SECTION_SIZE) continue; - - uint8_t current = light[light_idx(sec, y_in_sec, pos.z, pos.x)]; - if (current == 0) continue; - - for (int d = 0; d < 6; d++) { - int nx = pos.x + dx[d]; - int ny = pos.y + dy[d]; - int nz = pos.z + dz[d]; - - if (nx < 0 || nx >= LIGHT_SECTION_SIZE) continue; - if (nz < 0 || nz >= LIGHT_SECTION_SIZE) continue; - - int n_local_y = ny - LIGHT_MIN_Y; - int n_sec = n_local_y / LIGHT_SECTION_SIZE; - int n_y = n_local_y % LIGHT_SECTION_SIZE; - - if (n_sec < 0 || n_sec >= LIGHT_SECTION_COUNT) continue; - if (n_y < 0 || n_y >= LIGHT_SECTION_SIZE) continue; - - uint16_t neighbor_block = BL_AIR; - int block_sec = n_sec - 1; - if (block_sec >= 0 && block_sec < LIGHT_CHUNK_SECTIONS) { - neighbor_block = blocks[block_idx(block_sec, n_y, nz, nx)]; - } - - BlockLightInfo info = get_block_info(neighbor_block); - if (info.block_type == LightType::LIGHT_OPAQUE && info.sky_type == LightType::LIGHT_OPAQUE) { - continue; - } - - uint8_t decrease = 1; - if (is_sky_light && info.sky_type == LightType::LIGHT_FILTER) { - decrease += info.filter_level; - } else if (!is_sky_light && info.block_type == LightType::LIGHT_FILTER) { - decrease += info.filter_level; - } - - uint8_t new_light = (current > decrease) ? (current - decrease) : 0; - - if (is_sky_light && dy[d] < 0 && info.sky_type == LightType::LIGHT_TRANSPARENT) { - new_light = current; - } - - uint8_t& existing = light[light_idx(n_sec, n_y, nz, nx)]; - if (new_light > existing) { - existing = new_light; - if (new_light > 1) { - queue.push_back({nx, ny, nz}); - } - } - } - } -} - -// =========================================================== -// Incremental update -// =========================================================== - -std::vector LightEngine::update_block_light( - int x, int y, int z, - uint16_t old_block, uint16_t new_block -) { - std::vector updates; - - BlockLightInfo old_info = get_block_info(old_block); - BlockLightInfo new_info = get_block_info(new_block); - - if (old_info.sky_type == new_info.sky_type && - old_info.block_type == new_info.block_type && - old_info.emitted_light == new_info.emitted_light && - old_info.filter_level == new_info.filter_level) { - return updates; - } - - LightUpdate update; - update.x = x; - update.y = y; - update.z = z; - update.new_sky_light = 0; - update.new_block_light = 0; - - if (new_info.block_type == LightType::LIGHT_SOURCE) { - update.new_block_light = new_info.emitted_light; - } - - if (new_info.sky_type == LightType::LIGHT_TRANSPARENT) { - update.new_sky_light = LIGHT_MAX_LEVEL; - } - - updates.push_back(update); - - static constexpr int dx[] = {-1, 1, 0, 0, 0, 0}; - static constexpr int dy[] = {0, 0, -1, 1, 0, 0}; - static constexpr int dz[] = {0, 0, 0, 0, -1, 1}; - - for (int d = 0; d < 6; d++) { - LightUpdate neighbor; - neighbor.x = x + dx[d]; - neighbor.y = y + dy[d]; - neighbor.z = z + dz[d]; - neighbor.new_sky_light = 0; - neighbor.new_block_light = 0; - updates.push_back(neighbor); - } - - return updates; -} - -// =========================================================== -// Section cache management -// =========================================================== - -void LightEngine::set_section_data(int chunk_x, int section_y, int chunk_z, - const uint8_t* sky_light, const uint8_t* block_light, - const uint16_t* blocks) { - int64_t key = make_section_key(chunk_x, section_y, chunk_z); - auto& data = section_cache_[key]; - std::memcpy(data.sky_light, sky_light, SECTION_VOLUME); - std::memcpy(data.block_light, block_light, SECTION_VOLUME); - std::memcpy(data.blocks, blocks, SECTION_VOLUME * sizeof(uint16_t)); -} - -uint8_t LightEngine::get_sky_light_at(int x, int y, int z) const { - int cx = x >> 4; - int cz = z >> 4; - int lx = x & 15; - int lz = z & 15; - int local_y = y - LIGHT_MIN_Y; - int sec = local_y / LIGHT_SECTION_SIZE; - int ly = local_y % LIGHT_SECTION_SIZE; - - int64_t key = make_section_key(cx, sec, cz); - auto it = section_cache_.find(key); - if (it == section_cache_.end()) return 0; - return it->second.sky_light[ly * LIGHT_SECTION_SIZE * LIGHT_SECTION_SIZE + lz * LIGHT_SECTION_SIZE + lx]; -} - -uint8_t LightEngine::get_block_light_at(int x, int y, int z) const { - int cx = x >> 4; - int cz = z >> 4; - int lx = x & 15; - int lz = z & 15; - int local_y = y - LIGHT_MIN_Y; - int sec = local_y / LIGHT_SECTION_SIZE; - int ly = local_y % LIGHT_SECTION_SIZE; - - int64_t key = make_section_key(cx, sec, cz); - auto it = section_cache_.find(key); - if (it == section_cache_.end()) return 0; - return it->second.block_light[ly * LIGHT_SECTION_SIZE * LIGHT_SECTION_SIZE + lz * LIGHT_SECTION_SIZE + lx]; -} - -uint8_t LightEngine::light_decrease(uint16_t block_state, bool is_sky_light) const { - BlockLightInfo info = get_block_info(block_state); - if (info.sky_type == LightType::LIGHT_OPAQUE) return LIGHT_MAX_LEVEL; - uint8_t decrease = 1; - if (is_sky_light && info.sky_type == LightType::LIGHT_FILTER) { - decrease += info.filter_level; - } else if (!is_sky_light && info.block_type == LightType::LIGHT_FILTER) { - decrease += info.filter_level; - } - return decrease; -} - -bool LightEngine::is_transparent(uint16_t block_state) const { - BlockLightInfo info = get_block_info(block_state); - return info.sky_type != LightType::LIGHT_OPAQUE; -} - -} // namespace pymc diff --git a/native/lighting/light_engine.h b/native/lighting/light_engine.h deleted file mode 100755 index ae7d575..0000000 --- a/native/lighting/light_engine.h +++ /dev/null @@ -1,201 +0,0 @@ -// ============================================================ -// PyMC - Light Propagation Engine -// -// Implements proper Minecraft 1.21.1 light propagation: -// - Sky light: BFS flood-fill from top down through -// air/transparent blocks -// - Block light: BFS flood-fill from light sources outward -// - Handles light-blocking and light-filtering blocks -// - Incremental updates: only recalculate when blocks change -// -// Light levels are stored per-subchunk (16x16x16 sections), -// with boundary sections for seamless inter-chunk transitions. -// ============================================================ - -#ifndef PYMC_LIGHT_ENGINE_H -#define PYMC_LIGHT_ENGINE_H - -#include -#include -#include -#include -#include -#include -#include - -// Undefine Windows macros that conflict with our enum values -#ifdef TRANSPARENT -#undef TRANSPARENT -#endif -#ifdef OPAQUE -#undef OPAQUE -#endif -#ifdef FILTER -#undef FILTER -#endif - -namespace pymc { - -// ----------------------------------------------------------- -// Constants -// ----------------------------------------------------------- -static constexpr int LIGHT_SECTION_SIZE = 16; -static constexpr int LIGHT_CHUNK_SECTIONS = 24; // 384 / 16 -static constexpr int LIGHT_SECTION_COUNT = 26; // CHUNK_SECTIONS + 2 boundary sections -static constexpr int LIGHT_MAX_LEVEL = 15; -static constexpr int LIGHT_MIN_Y = -64; - -// ----------------------------------------------------------- -// Block light properties -// ----------------------------------------------------------- -enum class LightType : uint8_t { - LIGHT_TRANSPARENT = 0, // Air, glass, etc. — light passes through fully - LIGHT_FILTER = 1, // Water, leaves, etc. — light decreases by 1 extra - LIGHT_OPAQUE = 2, // Stone, dirt, etc. — blocks all light - LIGHT_SOURCE = 3, // Glowstone, torch, etc. — emits light -}; - -// Block light info for a single block -struct BlockLightInfo { - LightType sky_type; // How this block affects sky light - LightType block_type; // How this block affects block light - uint8_t emitted_light; // Light level emitted (0-15) - uint8_t filter_level; // Extra light reduction when filtering (0-2) -}; - -// ----------------------------------------------------------- -// Light update entry -// ----------------------------------------------------------- -struct LightUpdate { - int32_t x, y, z; - uint8_t new_sky_light; - uint8_t new_block_light; -}; - -// ----------------------------------------------------------- -// BlockPos for light engine -// ----------------------------------------------------------- -struct LightPos { - int32_t x, y, z; - bool operator==(const LightPos& o) const { - return x == o.x && y == o.y && z == o.z; - } -}; - -struct LightPosHash { - size_t operator()(const LightPos& p) const { - size_t h = 14695981039346656037ULL; - h ^= static_cast(static_cast(p.x)); - h *= 1099511628211ULL; - h ^= static_cast(static_cast(p.y)); - h *= 1099511628211ULL; - h ^= static_cast(static_cast(p.z)); - h *= 1099511628211ULL; - return h; - } -}; - -// ----------------------------------------------------------- -// LightEngine — main class -// ----------------------------------------------------------- -class LightEngine { -public: - LightEngine(); - ~LightEngine(); - - // ---- Full chunk lighting calculation ---- - - // Calculate lighting for an entire chunk column using flat arrays. - // blocks: flat array of 98304 uint16_t (y*256 + z*16 + x ordering) - // sky_light: Output sky light (LIGHT_SECTION_COUNT * 4096 bytes) - // block_light: Output block light (LIGHT_SECTION_COUNT * 4096 bytes) - void calculate_chunk_lighting( - const uint16_t* blocks, - uint8_t* sky_light, - uint8_t* block_light - ); - - // ---- Incremental update ---- - - // Update lighting when a single block changes. - // Returns the list of positions whose light levels changed. - std::vector update_block_light( - int x, int y, int z, - uint16_t old_block, uint16_t new_block - ); - - // ---- Block property lookup ---- - - // Get the light properties of a block by its state ID. - BlockLightInfo get_block_info(uint16_t block_state) const; - - // Register a custom block light info - void set_block_info(uint16_t block_state, const BlockLightInfo& info); - - // ---- Internal light data access ---- - - // Set the light data for a chunk section - void set_section_data(int chunk_x, int section_y, int chunk_z, - const uint8_t* sky_light, const uint8_t* block_light, - const uint16_t* blocks); - - // Get light level at a world position - uint8_t get_sky_light_at(int x, int y, int z) const; - uint8_t get_block_light_at(int x, int y, int z) const; - -private: - // Custom block info overrides - std::unordered_map custom_block_info_; - - // Cached light data for loaded chunks - static constexpr int SECTION_VOLUME = LIGHT_SECTION_SIZE * LIGHT_SECTION_SIZE * LIGHT_SECTION_SIZE; - - struct SectionData { - uint8_t sky_light[SECTION_VOLUME]; - uint8_t block_light[SECTION_VOLUME]; - uint16_t blocks[SECTION_VOLUME]; - }; - - static int64_t make_section_key(int cx, int sy, int cz) { - return (static_cast(cx & 0x3FFFFF) << 42) - | (static_cast(sy & 0x1FF) << 21) - | (static_cast(cz & 0x3FFFFF)); - } - - std::unordered_map section_cache_; - - // ---- Internal BFS-based propagation ---- - // These use flat pointer arrays to avoid C++ array dimension issues - // across different compilers and platforms. - - void propagate_sky_light( - uint8_t* sky_light, - const uint16_t* blocks, - int chunk_x, int chunk_z - ); - - void propagate_block_light( - uint8_t* block_light, - const uint16_t* blocks - ); - - void bfs_propagate( - uint8_t* light, - const uint16_t* blocks, - std::deque& queue, - bool is_sky_light - ); - - // Calculate the light decrease when passing through a block - uint8_t light_decrease(uint16_t block_state, bool is_sky_light) const; - - // Check if a block is transparent to light - bool is_transparent(uint16_t block_state) const; - - // Initialize default block light properties - void init_default_block_info(); -}; - -} // namespace pymc - -#endif // PYMC_LIGHT_ENGINE_H diff --git a/native/mob_ai.cpp b/native/mob_ai.cpp index c7acc19..58bb408 100755 --- a/native/mob_ai.cpp +++ b/native/mob_ai.cpp @@ -21,7 +21,8 @@ namespace { -constexpr uint8_t kTickCommand = 'T'; +constexpr uint8_t kTickCommand = 'T'; // one mob, players included +constexpr uint8_t kBatchCommand = 'B'; // many mobs: players sent once, one reply per mob, in order constexpr uint32_t kResponsePayloadSize = 80; enum MobType : int32_t { @@ -343,7 +344,7 @@ AiOutput tick_ai(const MobInput& in, const std::vector& players) { return out; } -bool read_tick_request(MobInput& in, std::vector& players) { +bool read_mob_fields(MobInput& in) { if (!read_exact(&in.mob_type, sizeof(in.mob_type))) return false; if (!read_exact(&in.entity_id, sizeof(in.entity_id))) return false; if (!read_exact(&in.age_ticks, sizeof(in.age_ticks))) return false; @@ -363,6 +364,10 @@ bool read_tick_request(MobInput& in, std::vector& players) { if (!read_exact(&in.target_x, sizeof(in.target_x))) return false; if (!read_exact(&in.target_y, sizeof(in.target_y))) return false; if (!read_exact(&in.target_z, sizeof(in.target_z))) return false; + return true; +} + +bool read_players(MobInput& in, std::vector& players) { if (!read_exact(&in.player_count, sizeof(in.player_count))) return false; if (in.player_count > 256) { @@ -378,6 +383,10 @@ bool read_tick_request(MobInput& in, std::vector& players) { return true; } +bool read_tick_request(MobInput& in, std::vector& players) { + return read_mob_fields(in) && read_players(in, players); +} + bool write_response(const AiOutput& out) { std::vector payload; payload.reserve(kResponsePayloadSize); @@ -409,26 +418,48 @@ int main() { _setmode(_fileno(stdin), _O_BINARY); _setmode(_fileno(stdout), _O_BINARY); #endif - setvbuf(stdin, nullptr, _IONBF, 0); - setvbuf(stdout, nullptr, _IONBF, 0); + // Buffered pipes: a request is ~30 fields and was read one syscall per field when unbuffered. + // Replies are flushed explicitly after each one below. + static char in_buffer[1 << 16]; + static char out_buffer[1 << 14]; + setvbuf(stdin, in_buffer, _IOFBF, sizeof(in_buffer)); + setvbuf(stdout, out_buffer, _IOFBF, sizeof(out_buffer)); while (true) { uint8_t command = 0; if (!read_exact(&command, 1)) { break; } - if (command != kTickCommand) { - break; - } - - MobInput input{}; - std::vector players; - if (!read_tick_request(input, players)) { - break; - } - - const AiOutput out = tick_ai(input, players); - if (!write_response(out)) { + if (command == kTickCommand) { + MobInput input{}; + std::vector players; + if (!read_tick_request(input, players)) { + break; + } + if (!write_response(tick_ai(input, players))) { + break; + } + } else if (command == kBatchCommand) { + // uint32 mob_count, the players once, then each mob's fields (no player list per mob) + uint32_t mob_count = 0; + if (!read_exact(&mob_count, sizeof(mob_count)) || mob_count > 65536) { + break; + } + MobInput shared{}; + std::vector players; + if (!read_players(shared, players)) { + break; + } + bool ok = true; + for (uint32_t i = 0; i < mob_count && ok; ++i) { + MobInput input{}; + input.player_count = shared.player_count; + ok = read_mob_fields(input) && write_response(tick_ai(input, players)); + } + if (!ok) { + break; + } + } else { break; } std::fflush(stdout); diff --git a/native/mods/fabric_api.h b/native/mods/fabric_api.h deleted file mode 100755 index 2f5b64f..0000000 --- a/native/mods/fabric_api.h +++ /dev/null @@ -1,4 +0,0 @@ -// This file intentionally left empty. -// PYMC does NOT support Fabric mods. Fabric mods require a JVM with -// Mixin bytecode injection, which cannot be replicated in a Python/C++ -// server. Use the PYMC Native Mod API (pymc_mod_api.h) instead. diff --git a/native/mods/forge_api.h b/native/mods/forge_api.h deleted file mode 100755 index a3ab517..0000000 --- a/native/mods/forge_api.h +++ /dev/null @@ -1,4 +0,0 @@ -// This file intentionally left empty. -// PYMC does NOT support Forge/NeoForge mods. Forge mods require a JVM -// with Mixin bytecode injection, which cannot be replicated in a -// Python/C++ server. Use the PYMC Native Mod API (pymc_mod_api.h) instead. diff --git a/native/mods/jvm_interface.h b/native/mods/jvm_interface.h deleted file mode 100755 index 1fdb1c7..0000000 --- a/native/mods/jvm_interface.h +++ /dev/null @@ -1,4 +0,0 @@ -// This file intentionally left empty. -// PYMC does NOT embed a JVM. Java mod/plugin support requires JVM + -// Mixin bytecode injection, which cannot be replicated in a Python/C++ -// server. Use the PYMC Native Mod API (pymc_mod_api.h) instead. diff --git a/native/mods/mod_loader.h b/native/mods/mod_loader.h deleted file mode 100755 index 44bc062..0000000 --- a/native/mods/mod_loader.h +++ /dev/null @@ -1,285 +0,0 @@ -// ============================================================ -// PyMC - Native Mod API: Mod Loader -// -// PYMC provides a Python-native mod API. It does NOT support -// Java Fabric/Forge/NeoForge/Quilt mods, as those require -// JVM + Mixin bytecode injection which cannot be replicated -// in a Python/C++ server. -// -// This mod loader discovers and loads PYMC native Python mods, -// manages their lifecycle, and dispatches events. -// -// Architecture: -// ModLoader -// ├── Mod Discovery - Scan mods/ directory for Python packages -// ├── Metadata Parsing - Read pymc_mod.json descriptors -// ├── Dependency Graph - Topological sort for load ordering -// ├── Lifecycle Manager - load/enable/disable/unload -// └── Event Dispatcher - Fire events to mod callbacks -// -// Mod identification: -// - pymc_mod.json -> PYMC native mod descriptor -// - __pymc_mod__.py -> PYMC native mod entry point -// -// Loading pipeline: -// 1. Scan mods directory for Python packages -// 2. Parse mod metadata from pymc_mod.json (id, version, deps) -// 3. Resolve dependency graph (topological sort) -// 4. Load each mod package via Python importlib -// 5. Call mod lifecycle methods (on_load, on_enable, etc.) -// 6. Register event listeners from mod callbacks -// 7. Fire initialization events -// ============================================================ - -#ifndef PYMC_MOD_LOADER_H -#define PYMC_MOD_LOADER_H - -#include -#include -#include -#include -#include -#include -#include - -// =========================================================== -// ModLoaderType -// =========================================================== - -enum class ModLoaderType { - PYMC_NATIVE // PYMC native Python mod -}; - -// Convert ModLoaderType to string (for debugging/logging) -inline const char* mod_loader_type_name(ModLoaderType type) { - switch (type) { - case ModLoaderType::PYMC_NATIVE: return "PYMC Native"; - default: return "Unknown"; - } -} - -// =========================================================== -// ModInfo -// =========================================================== - -struct ModInfo { - std::string mod_id; // Unique mod identifier (e.g. "my_cool_mod") - std::string name; // Human-readable mod name - std::string version; // Mod version string - std::string description; // Mod description - ModLoaderType loader_type; // Always PYMC_NATIVE for PYMC mods - std::string entry_point; // Python module/class entry point - std::vector dependencies; // Required mod IDs - std::vector soft_dependencies; // Optional mod IDs - std::string package_path; // Path to the Python package directory - std::string api_version; // Target PYMC mod API version - std::string mc_version; // Target Minecraft version (e.g. "1.21.1") - - // Additional metadata from pymc_mod.json - std::map extra_metadata; - - ModInfo() : loader_type(ModLoaderType::PYMC_NATIVE) {} - - // Check if this mod depends on another mod - bool depends_on(const std::string& other_mod_id) const { - for (const auto& dep : dependencies) { - if (dep == other_mod_id) return true; - } - return false; - } - - // Check if this mod has a soft dependency on another mod - bool soft_depends_on(const std::string& other_mod_id) const { - for (const auto& dep : soft_dependencies) { - if (dep == other_mod_id) return true; - } - return false; - } -}; - -// =========================================================== -// ModState -// =========================================================== - -enum class ModState { - DISCOVERED, // Found on disk, metadata parsed - LOADED, // Python package imported successfully - INITIALIZED, // Mod on_load() called - ENABLED, // Mod is active and running - DISABLED, // Mod was enabled but now disabled - ERRORED, // Mod encountered an error - UNLOADED // Mod has been unloaded -}; - -inline const char* mod_state_name(ModState state) { - switch (state) { - case ModState::DISCOVERED: return "Discovered"; - case ModState::LOADED: return "Loaded"; - case ModState::INITIALIZED: return "Initialized"; - case ModState::ENABLED: return "Enabled"; - case ModState::DISABLED: return "Disabled"; - case ModState::ERRORED: return "Errored"; - case ModState::UNLOADED: return "Unloaded"; - default: return "Unknown"; - } -} - -// =========================================================== -// ModInstance -// =========================================================== - -class ModInstance { -public: - ModInstance(const ModInfo& info) - : info_(info), state_(ModState::DISCOVERED) - {} - - const ModInfo& info() const { return info_; } - ModState state() const { return state_; } - void set_state(ModState s) { state_ = s; } - - const std::string& mod_id() const { return info_.mod_id; } - ModLoaderType loader_type() const { return info_.loader_type; } - - // Check if this mod is in an active state - bool is_active() const { - return state_ == ModState::ENABLED || state_ == ModState::INITIALIZED; - } - - // Check if this mod is in a recoverable error state - bool is_errored() const { return state_ == ModState::ERRORED; } - - // Set/get error message (when state is ERRORED) - void set_error(const std::string& err) { error_message_ = err; } - const std::string& error() const { return error_message_; } - -private: - ModInfo info_; - ModState state_; - std::string error_message_; -}; - -// =========================================================== -// ModLoader -// =========================================================== - -class ModLoader { -public: - ModLoader(); - ~ModLoader(); - - // --- Mod Discovery --- - - // Scan a directory for PYMC native mod packages - // Looks for directories containing pymc_mod.json or __pymc_mod__.py - // Returns: list of ModInfo for all discovered mods - std::vector scan_mods_directory(const std::string& dir_path); - - // --- Mod Loading --- - - // Load a PYMC native mod from its package directory - // Returns: true if the mod was loaded successfully - bool load_mod(const std::string& package_path); - - // Load all discovered mods (in dependency order) - // Returns: number of mods loaded successfully - int load_all(); - - // --- Lifecycle --- - - // Initialize all loaded mods (call on_load callbacks) - // Returns: true if all mods initialized successfully - bool initialize_all(); - - // Enable a specific mod by ID - bool enable_mod(const std::string& mod_id); - - // Disable a specific mod by ID - bool disable_mod(const std::string& mod_id); - - // Shutdown all mods (disable in reverse dependency order) - void shutdown_all(); - - // --- Query --- - - // Get all loaded mods - const std::vector& get_loaded_mods() const; - - // Get a mod instance by ID - std::shared_ptr get_mod(const std::string& mod_id) const; - - // Check if a mod is loaded - bool is_mod_loaded(const std::string& mod_id) const; - - // Get mod state - ModState get_mod_state(const std::string& mod_id) const; - - // Get number of loaded mods - size_t mod_count() const { return mods_.size(); } - - // --- API Handler Registration --- - - // Register a mod API callback - // When a mod calls an API method, the handler is invoked - void register_api_handler(const std::string& api_name, - std::function&)> handler); - - // --- Event Dispatch --- - - // Fire a mod event to all registered listeners - void fire_event(const std::string& event_name, - const std::map& data); - - // Register a listener for a specific event type - // Returns: listener ID for later unregistration - int register_event_listener(const std::string& event_name, - std::function&)> listener); - - // Unregister an event listener by ID - bool unregister_event_listener(int listener_id); - - // --- Dependency Resolution --- - - // Resolve the dependency order for all loaded mods - // Returns: ordered list of mod IDs (dependencies first) - std::vector resolve_dependency_order() const; - - // Check if all dependencies for a mod are satisfied - bool check_dependencies(const ModInfo& info) const; - -private: - // --- Mod Metadata Parsing --- - - // Parse PYMC mod metadata from pymc_mod.json - bool parse_pymc_mod_json(const std::string& package_path, ModInfo& info); - - // --- Internal Helpers --- - - // Topological sort for dependency resolution - bool topological_sort(const std::vector& mod_ids, - std::vector& out_order) const; - -private: - // All loaded mods (mod_id -> instance) - std::unordered_map> mods_; - - // Ordered list of mod IDs (dependency-sorted) - std::vector load_order_; - - // Discovered mods (from scan, before loading) - std::vector discovered_mods_; - - // API handlers (api_name -> handler function) - std::map&)>> api_handlers_; - - // Event listeners (event_name -> list of (id, handler)) - std::map&)>>>> event_listeners_; - - // Next event listener ID - int next_listener_id_ = 0; - - // Mutex for thread safety - mutable std::mutex mutex_; -}; - -#endif // PYMC_MOD_LOADER_H diff --git a/native/mods/pymc_mod_api.h b/native/mods/pymc_mod_api.h deleted file mode 100755 index a9afa6a..0000000 --- a/native/mods/pymc_mod_api.h +++ /dev/null @@ -1,152 +0,0 @@ -// ============================================================ -// PyMC - Native Mod API: C API Bridge -// -// Defines the C API for PYMC native mods, exposed via ctypes -// to Python. This is the interface that PYMC Python mods use -// to interact with the C++ server core. -// -// PYMC provides a Python-native mod API. It does NOT support -// Java Fabric/Forge/NeoForge/Quilt mods, as those require -// JVM + Mixin bytecode injection which cannot be replicated -// in a Python/C++ server. -// -// Architecture: -// C API Functions (extern "C") -// ├── Registration -// │ ├── pymc_mod_register_block() - Custom blocks -// │ ├── pymc_mod_register_item() - Custom items -// │ ├── pymc_mod_register_biome() - Custom biomes -// │ └── pymc_mod_register_entity_type() - Custom entities -// ├── Events -// │ ├── pymc_mod_register_event_listener() - Event callbacks -// │ └── pymc_mod_fire_event() - Fire events -// └── Server Query -// ├── pymc_mod_get_server_tps() - Server TPS -// ├── pymc_mod_get_online_players() - Online count -// ├── pymc_mod_broadcast_message() - Broadcast chat -// └── pymc_mod_dispatch_command() - Execute command -// ============================================================ - -#ifndef PYMC_MOD_API_H -#define PYMC_MOD_API_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// =========================================================== -// Property Structures -// =========================================================== - -// Block properties for registration -struct BlockProperties { - const char* material; // e.g. "stone", "wood", "metal" - const char* sound_group; // e.g. "stone", "wood", "grass" - float hardness; // Mining hardness (0 = instant, -1 = unbreakable) - float resistance; // Blast resistance - float slipperiness; // Friction multiplier (0.0 - 1.0) - int light_level; // Emitted light level (0-15) - int is_opaque; // Whether block blocks light - int is_solid; // Whether block supports other blocks - int has_collision; // Whether entities collide with block - int is_air; // Whether this is an air-like block -}; - -// Item properties for registration -struct ItemProperties { - const char* group; // Item group / creative tab - int max_count; // Max stack size (1-64) - int max_damage; // Max durability (0 = not damageable) - int is_fireproof; // Whether item resists fire - int is_food; // Whether this is a food item - float food_nutrition; // Food nutrition value - float food_saturation; // Food saturation modifier - const char* rarity; // "common", "uncommon", "rare", "epic" -}; - -// =========================================================== -// Registration Functions -// =========================================================== - -// Register a custom block with the server -// block_id: unique identifier (e.g. "mymod:custom_block") -// props: block property struct -// Returns: 0 on success, non-zero on failure -int pymc_mod_register_block(const char* block_id, const struct BlockProperties* props); - -// Register a custom item with the server -// item_id: unique identifier (e.g. "mymod:custom_item") -// props: item property struct -// Returns: 0 on success, non-zero on failure -int pymc_mod_register_item(const char* item_id, const struct ItemProperties* props); - -// Register a custom biome with the server -// biome_id: unique identifier (e.g. "mymod:crystal_forest") -// temperature: biome temperature (0.0 - 2.0) -// downfall: rainfall amount (0.0 - 1.0) -// precipitation: "rain", "snow", or "none" -// Returns: 0 on success, non-zero on failure -int pymc_mod_register_biome(const char* biome_id, float temperature, - float downfall, const char* precipitation); - -// Register a custom entity type with the server -// entity_id: unique identifier (e.g. "mymod:golem") -// width: entity hitbox width -// height: entity hitbox height -// is_summonable: whether /summon can create this entity -// Returns: 0 on success, non-zero on failure -int pymc_mod_register_entity_type(const char* entity_id, float width, - float height, int is_summonable); - -// =========================================================== -// Event Functions -// =========================================================== - -// Callback type for event listeners -// event_name: name of the event that fired -// data_json: JSON-encoded event data (key-value pairs) -// Returns: 0 to continue, non-zero to cancel (if cancellable) -typedef int (*pymc_event_callback)(const char* event_name, const char* data_json); - -// Register a callback for a specific event type -// event_name: event to listen for (e.g. "block_break", "player_join") -// callback: function pointer to call when event fires -// Returns: listener ID (>= 0) on success, -1 on failure -int pymc_mod_register_event_listener(const char* event_name, - pymc_event_callback callback); - -// Fire an event to all registered listeners -// event_name: event type to fire -// data_json: JSON-encoded event data -// Returns: 0 if no listener cancelled, non-zero if cancelled -int pymc_mod_fire_event(const char* event_name, const char* data_json); - -// =========================================================== -// Server Query Functions -// =========================================================== - -// Get the current server TPS (ticks per second) -// Returns: TPS as double (20.0 = ideal) -double pymc_mod_get_server_tps(void); - -// Get the number of currently online players -// Returns: player count -int pymc_mod_get_online_players(void); - -// Broadcast a chat message to all online players -// message: the message to broadcast -// Returns: 0 on success, non-zero on failure -int pymc_mod_broadcast_message(const char* message); - -// Dispatch a server command as if typed in console -// command: the command string (without leading /) -// Returns: 0 on success, non-zero on failure -int pymc_mod_dispatch_command(const char* command); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // PYMC_MOD_API_H diff --git a/native/physics/physics_engine.cpp b/native/physics/physics_engine.cpp deleted file mode 100755 index 128d3db..0000000 --- a/native/physics/physics_engine.cpp +++ /dev/null @@ -1,506 +0,0 @@ -// ============================================================ -// PyMC - Physics Engine Implementation -// AABB collision, gravity, drag, fluid flow, falling blocks -// ============================================================ - -#include "physics_engine.h" - -#include -#include -#include -#include -#include - -namespace pymc { - -// Well-known block IDs -static constexpr uint16_t BL_AIR = 0; -static constexpr uint16_t BL_STONE = 1; -static constexpr uint16_t BL_WATER = 80; -static constexpr uint16_t BL_LAVA = 96; -static constexpr uint16_t BL_SAND = 112; -static constexpr uint16_t BL_GRAVEL = 118; -static constexpr uint16_t BL_ANVIL = 1658; -static constexpr uint16_t BL_SNOW_LAYER = 562; -static constexpr uint16_t BL_SLAB_BOTTOM = 928; -static constexpr uint16_t BL_SLAB_TOP = 929; -static constexpr uint16_t BL_CACTUS = 658; - -PhysicsEngine::PhysicsEngine() { - init_default_shapes(); -} - -PhysicsEngine::~PhysicsEngine() = default; - -// =========================================================== -// Entity management -// =========================================================== - -void PhysicsEngine::set_entity(const PhysicsEntity& entity) { - entities_[entity.entity_id] = entity; -} - -void PhysicsEngine::remove_entity(int32_t entity_id) { - entities_.erase(entity_id); -} - -// =========================================================== -// Block data management -// =========================================================== - -void PhysicsEngine::set_blocks(const std::vector& blocks) { - for (const auto& bd : blocks) { - blocks_[{bd.x, bd.y, bd.z}] = bd.block_state; - } -} - -void PhysicsEngine::clear_blocks() { - blocks_.clear(); -} - -// =========================================================== -// Physics tick -// =========================================================== - -std::vector PhysicsEngine::tick() { - std::vector updates; - updates.reserve(entities_.size()); - - for (auto& [id, entity] : entities_) { - PhysicsUpdate update; - update.entity_id = id; - update.new_x = entity.x; - update.new_y = entity.y; - update.new_z = entity.z; - update.new_vx = entity.vx; - update.new_vy = entity.vy; - update.new_vz = entity.vz; - update.on_ground = entity.on_ground; - update.collided_x = false; - update.collided_y = false; - update.collided_z = false; - update.landed = false; - update.landed_block_state = 0; - update.landed_x = update.landed_y = update.landed_z = 0; - - // Apply gravity and drag - apply_forces(entity); - - // Resolve collisions with world blocks - resolve_collisions(entity, update); - - // Handle falling blocks - if (entity.is_falling_block && entity.on_ground) { - update.landed = true; - update.landed_block_state = entity.block_state; - update.landed_x = static_cast(std::floor(entity.x)); - update.landed_y = static_cast(std::floor(entity.y)); - update.landed_z = static_cast(std::floor(entity.z)); - } - - // Item entities: apply extra drag when on ground - if (entity.is_item && entity.on_ground) { - entity.vx *= 0.6; - entity.vz *= 0.6; - } - - update.new_x = entity.x; - update.new_y = entity.y; - update.new_z = entity.z; - update.new_vx = entity.vx; - update.new_vy = entity.vy; - update.new_vz = entity.vz; - update.on_ground = entity.on_ground; - - updates.push_back(update); - } - - return updates; -} - -// =========================================================== -// Force application -// =========================================================== - -void PhysicsEngine::apply_forces(PhysicsEntity& entity) { - // Gravity - if (entity.has_gravity) { - double g = GRAVITY * entity.gravity_multiplier; - entity.vy = std::clamp(entity.vy - g, -MAX_VELOCITY, MAX_VELOCITY); - } - - // Drag - if (entity.has_drag) { - double d = DRAG * entity.drag_multiplier; - entity.vx *= d; - entity.vy *= d; - entity.vz *= d; - } - - // Item entities: extra gravity - if (entity.is_item) { - entity.vy = std::clamp(entity.vy - 0.04, -MAX_VELOCITY, MAX_VELOCITY); - } -} - -// =========================================================== -// Collision resolution -// =========================================================== - -void PhysicsEngine::resolve_collisions(PhysicsEntity& entity, PhysicsUpdate& update) { - // Move in each axis separately for proper sliding collision - - // X axis - entity.x += entity.vx; - AABB entity_box = entity.world_aabb(); - auto collisions = get_potential_collisions(entity_box); - for (const auto& block_aabb : collisions) { - if (entity_box.intersects(block_aabb)) { - if (entity.vx > 0) { - entity.x = block_aabb.min_x - entity.bounding_box.max_x - ENTITY_PADDING; - } else if (entity.vx < 0) { - entity.x = block_aabb.max_x - entity.bounding_box.min_x + ENTITY_PADDING; - } - entity.vx = 0; - update.collided_x = true; - entity_box = entity.world_aabb(); - } - } - - // Y axis - entity.y += entity.vy; - entity_box = entity.world_aabb(); - collisions = get_potential_collisions(entity_box); - bool hit_ground = false; - for (const auto& block_aabb : collisions) { - if (entity_box.intersects(block_aabb)) { - if (entity.vy < 0) { - entity.y = block_aabb.max_y - entity.bounding_box.min_y + ENTITY_PADDING; - hit_ground = true; - } else if (entity.vy > 0) { - entity.y = block_aabb.min_y - entity.bounding_box.max_y - ENTITY_PADDING; - } - entity.vy = 0; - update.collided_y = true; - entity_box = entity.world_aabb(); - } - } - - // Auto-step: if we hit a wall but there's a 1-block gap above - if (update.collided_x && !update.collided_y && entity.on_ground) { - // Try stepping up - double old_y = entity.y; - entity.y += STEP_HEIGHT; - AABB step_box = entity.world_aabb(); - bool can_step = true; - auto step_collisions = get_potential_collisions(step_box); - for (const auto& block_aabb : step_collisions) { - if (step_box.intersects(block_aabb)) { - can_step = false; - break; - } - } - if (can_step) { - // Step succeeded — resolve X again - entity.x += entity.vx; - } else { - // Step failed — revert Y - entity.y = old_y; - } - } - - entity.on_ground = hit_ground || (entity.on_ground && update.collided_y); - - // Z axis - entity.z += entity.vz; - entity_box = entity.world_aabb(); - collisions = get_potential_collisions(entity_box); - for (const auto& block_aabb : collisions) { - if (entity_box.intersects(block_aabb)) { - if (entity.vz > 0) { - entity.z = block_aabb.min_z - entity.bounding_box.max_z - ENTITY_PADDING; - } else if (entity.vz < 0) { - entity.z = block_aabb.max_z - entity.bounding_box.min_z + ENTITY_PADDING; - } - entity.vz = 0; - update.collided_z = true; - entity_box = entity.world_aabb(); - } - } - - // Check if still on ground (detect floor below) - if (!hit_ground && entity.on_ground) { - AABB ground_check = entity.world_aabb(); - ground_check.min_y -= 0.05; - ground_check.max_y = ground_check.min_y + 0.05; - auto ground_collisions = get_potential_collisions(ground_check); - entity.on_ground = !ground_collisions.empty(); - } - - // Apply friction when on ground - if (entity.on_ground) { - entity.vx *= 0.6; - entity.vz *= 0.6; - } -} - -std::vector PhysicsEngine::get_potential_collisions(const AABB& entity_aabb) const { - std::vector result; - - // Calculate block range that could overlap with the entity - int32_t min_bx = static_cast(std::floor(entity_aabb.min_x)); - int32_t max_bx = static_cast(std::floor(entity_aabb.max_x)); - int32_t min_by = static_cast(std::floor(entity_aabb.min_y)); - int32_t max_by = static_cast(std::floor(entity_aabb.max_y)); - int32_t min_bz = static_cast(std::floor(entity_aabb.min_z)); - int32_t max_bz = static_cast(std::floor(entity_aabb.max_z)); - - for (int32_t bx = min_bx; bx <= max_bx; bx++) { - for (int32_t by = min_by; by <= max_by; by++) { - for (int32_t bz = min_bz; bz <= max_bz; bz++) { - uint16_t block = get_block_at(bx, by, bz); - if (block == BL_AIR) continue; - - BlockShape shape = get_block_shape(block); - if (shape == BlockShape::EMPTY || shape == BlockShape::FLUID) continue; - - AABB block_aabb; - if (get_block_aabb(block, block_aabb)) { - // Transform to world coordinates - block_aabb = block_aabb.offset( - static_cast(bx), - static_cast(by), - static_cast(bz) - ); - result.push_back(block_aabb); - } - } - } - } - - return result; -} - -CollisionResult PhysicsEngine::swept_aabb(const AABB& entity, const AABB& block, - double dx, double dy, double dz) const { - CollisionResult result; - result.overlap_x = result.overlap_y = result.overlap_z = 0; - result.block_x = result.block_y = result.block_z = 0; - result.collided = false; - - // Expand block by entity size - AABB expanded = block; - expanded.min_x -= entity.width() / 2; - expanded.max_x += entity.width() / 2; - expanded.min_y -= entity.height() / 2; - expanded.max_y += entity.height() / 2; - expanded.min_z -= entity.depth() / 2; - expanded.max_z += entity.depth() / 2; - - // Calculate entry/exit times for each axis - double t_min = 0.0; - double t_max = 1.0; - int collision_axis = -1; - - // X axis - if (std::abs(dx) < 1e-10) { - if (entity.min_x > expanded.max_x || entity.max_x < expanded.min_x) { - return result; // No collision - } - } else { - double t_entry_x = (dx > 0) ? - (expanded.min_x - entity.max_x) / dx : - (expanded.max_x - entity.min_x) / dx; - double t_exit_x = (dx > 0) ? - (expanded.max_x - entity.min_x) / dx : - (expanded.min_x - entity.max_x) / dx; - if (t_entry_x > t_min) { t_min = t_entry_x; collision_axis = 0; } - if (t_exit_x < t_max) t_max = t_exit_x; - } - - // Y axis - if (std::abs(dy) < 1e-10) { - if (entity.min_y > expanded.max_y || entity.max_y < expanded.min_y) { - return result; - } - } else { - double t_entry_y = (dy > 0) ? - (expanded.min_y - entity.max_y) / dy : - (expanded.max_y - entity.min_y) / dy; - double t_exit_y = (dy > 0) ? - (expanded.max_y - entity.min_y) / dy : - (expanded.min_y - entity.max_y) / dy; - if (t_entry_y > t_min) { t_min = t_entry_y; collision_axis = 1; } - if (t_exit_y < t_max) t_max = t_exit_y; - } - - // Z axis - if (std::abs(dz) < 1e-10) { - if (entity.min_z > expanded.max_z || entity.max_z < expanded.min_z) { - return result; - } - } else { - double t_entry_z = (dz > 0) ? - (expanded.min_z - entity.max_z) / dz : - (expanded.max_z - entity.min_z) / dz; - double t_exit_z = (dz > 0) ? - (expanded.max_z - entity.min_z) / dz : - (expanded.min_z - entity.max_z) / dz; - if (t_entry_z > t_min) { t_min = t_entry_z; collision_axis = 2; } - if (t_exit_z < t_max) t_max = t_exit_z; - } - - if (t_min > t_max || t_min > 1.0 || t_min < 0.0) { - return result; // No collision within this tick - } - - result.collided = true; - result.block_x = static_cast(std::floor((block.min_x + block.max_x) / 2)); - result.block_y = static_cast(std::floor((block.min_y + block.max_y) / 2)); - result.block_z = static_cast(std::floor((block.min_z + block.max_z) / 2)); - - if (collision_axis == 0) result.overlap_x = dx * (1.0 - t_min); - if (collision_axis == 1) result.overlap_y = dy * (1.0 - t_min); - if (collision_axis == 2) result.overlap_z = dz * (1.0 - t_min); - - return result; -} - -// =========================================================== -// Block property lookup -// =========================================================== - -bool PhysicsEngine::is_solid(int32_t x, int32_t y, int32_t z) const { - uint16_t block = get_block_at(x, y, z); - if (block == BL_AIR) return false; - BlockShape shape = get_block_shape(block); - return shape == BlockShape::FULL || shape == BlockShape::PARTIAL; -} - -uint16_t PhysicsEngine::get_block_at(int32_t x, int32_t y, int32_t z) const { - auto it = blocks_.find({x, y, z}); - return it != blocks_.end() ? it->second : BL_AIR; -} - -BlockShape PhysicsEngine::get_block_shape(uint16_t block_state) const { - // Air, water, lava: no collision - if (block_state == BL_AIR || block_state == BL_WATER || block_state == BL_LAVA) { - return BlockShape::EMPTY; - } - - // Most blocks are full cubes - // Special cases for partial blocks are handled in get_block_aabb - return BlockShape::FULL; -} - -bool PhysicsEngine::get_block_aabb(uint16_t block_state, AABB& out) const { - if (block_state == BL_AIR) return false; - if (block_state == BL_WATER || block_state == BL_LAVA) return false; - - // Default: full 1x1x1 cube - out = {0.0, 0.0, 0.0, 1.0, 1.0, 1.0}; - - // Special cases for partial blocks - // Slabs (bottom) - if (block_state == BL_SLAB_BOTTOM) { - out = {0.0, 0.0, 0.0, 1.0, 0.5, 1.0}; - } - // Slabs (top) - if (block_state == BL_SLAB_TOP) { - out = {0.0, 0.5, 0.0, 1.0, 1.0, 1.0}; - } - // Snow layers - if (block_state == BL_SNOW_LAYER) { - out = {0.0, 0.0, 0.0, 1.0, 0.125, 1.0}; - } - // Cactus: slightly smaller - if (block_state == BL_CACTUS) { - out = {0.0625, 0.0, 0.0625, 0.9375, 1.0, 0.9375}; - } - - return true; -} - -bool PhysicsEngine::is_fluid(uint16_t block_state) const { - return block_state == BL_WATER || block_state == BL_LAVA; -} - -// =========================================================== -// Fluid simulation -// =========================================================== - -void PhysicsEngine::add_fluid_source(int x, int y, int z, uint16_t block_state, int8_t level) { - fluid_sources_.push_back({x, y, z, block_state, level}); -} - -void PhysicsEngine::remove_fluid_source(int x, int y, int z) { - fluid_sources_.erase( - std::remove_if(fluid_sources_.begin(), fluid_sources_.end(), - [x, y, z](const FluidSource& f) { - return f.x == x && f.y == y && f.z == z; - }), - fluid_sources_.end()); -} - -std::vector PhysicsEngine::tick_fluids() { - std::vector updates; - - for (const auto& source : fluid_sources_) { - bool is_lava = (source.block_state == BL_LAVA); - - // Fluid flows horizontally and downward - // Level decreases by 1 each block from source (max 7 for water, 3 for lava) - int max_level = is_lava ? 3 : 7; - int flow_rate = is_lava ? 2 : 1; // Lava flows slower - - // Flow downward first - int32_t below_x = source.x; - int32_t below_y = source.y - 1; - int32_t below_z = source.z; - - if (!is_solid(below_x, below_y, below_z) && - get_block_at(below_x, below_y, below_z) != source.block_state) { - FluidUpdate down; - down.x = below_x; - down.y = below_y; - down.z = below_z; - down.new_block_state = source.block_state; - down.new_fluid_level = 0; // Falling fluid = source level - updates.push_back(down); - } else { - // Flow horizontally - static constexpr int dx[] = {-1, 1, 0, 0}; - static constexpr int dz[] = {0, 0, -1, 1}; - - for (int d = 0; d < 4; d++) { - int32_t nx = source.x + dx[d]; - int32_t nz = source.z + dz[d]; - - if (!is_solid(nx, source.y, nz) && - get_block_at(nx, source.y, nz) != source.block_state) { - FluidUpdate horizontal; - horizontal.x = nx; - horizontal.y = source.y; - horizontal.z = nz; - horizontal.new_block_state = source.block_state; - horizontal.new_fluid_level = static_cast( - std::min(source.level + 1, max_level)); - updates.push_back(horizontal); - } - } - } - } - - return updates; -} - -// =========================================================== -// Default shape initialization -// =========================================================== - -void PhysicsEngine::init_default_shapes() { - // Block shapes are determined dynamically by get_block_shape() - // This method is for future extension with custom block registries -} - -} // namespace pymc diff --git a/native/physics/physics_engine.h b/native/physics/physics_engine.h deleted file mode 100755 index 9a69be6..0000000 --- a/native/physics/physics_engine.h +++ /dev/null @@ -1,280 +0,0 @@ -// ============================================================ -// PyMC - Physics Engine -// -// High-performance physics simulation: -// - AABB collision detection and resolution -// - Entity-world collision with swept collision -// - Fluid flow simulation -// - Falling block entities (sand, gravel, anvils, etc.) -// - Gravity and drag -// -// The engine operates on a "snapshot" model: -// 1. Python sends the current entity positions + nearby blocks -// 2. C++ runs physics tick -// 3. C++ returns updated positions + collision events -// ============================================================ - -#ifndef PYMC_PHYSICS_ENGINE_H -#define PYMC_PHYSICS_ENGINE_H - -#include -#include -#include -#include -#include -#include - -namespace pymc { - -// ----------------------------------------------------------- -// Constants -// ----------------------------------------------------------- -constexpr double GRAVITY = 0.08; // Blocks per tick^2 -constexpr double DRAG = 0.98; // Velocity multiplier per tick -constexpr double MAX_VELOCITY = 3.92; // Terminal velocity -constexpr double STEP_HEIGHT = 0.6; // Max height to auto-step -constexpr double ENTITY_PADDING = 0.001; // Collision padding - -// ----------------------------------------------------------- -// AABB (Axis-Aligned Bounding Box) -// ----------------------------------------------------------- -struct AABB { - double min_x, min_y, min_z; - double max_x, max_y, max_z; - - double width() const { return max_x - min_x; } - double height() const { return max_y - min_y; } - double depth() const { return max_z - min_z; } - - // Expand the AABB by the given amount in all directions - AABB expand(double dx, double dy, double dz) const { - AABB result = *this; - if (dx < 0) result.min_x += dx; - else result.max_x += dx; - if (dy < 0) result.min_y += dy; - else result.max_y += dy; - if (dz < 0) result.min_z += dz; - else result.max_z += dz; - return result; - } - - // Check if this AABB intersects another - bool intersects(const AABB& other) const { - return min_x < other.max_x && max_x > other.min_x && - min_y < other.max_y && max_y > other.min_y && - min_z < other.max_z && max_z > other.min_z; - } - - // Move the AABB by the given offset - AABB offset(double dx, double dy, double dz) const { - return {min_x + dx, min_y + dy, min_z + dz, - max_x + dx, max_y + dy, max_z + dz}; - } -}; - -// ----------------------------------------------------------- -// Entity physics state -// ----------------------------------------------------------- -struct PhysicsEntity { - int32_t entity_id; - double x, y, z; // Position (center-bottom) - double vx, vy, vz; // Velocity - AABB bounding_box; // Relative to position - bool on_ground; - bool has_gravity; - bool has_drag; - double gravity_multiplier; // 1.0 = normal - double drag_multiplier; // 1.0 = normal - - // Entity type flags - bool is_item; // Item entities have special physics - bool is_falling_block; // Sand, gravel, etc. - bool is_projectile; // Arrows, etc. - - // Block state for falling block entities - uint16_t block_state; - - PhysicsEntity() - : entity_id(0), x(0), y(0), z(0) - , vx(0), vy(0), vz(0) - , bounding_box{-0.3, 0.0, -0.3, 0.3, 1.8, 0.3} - , on_ground(false), has_gravity(true), has_drag(true) - , gravity_multiplier(1.0), drag_multiplier(1.0) - , is_item(false), is_falling_block(false), is_projectile(false) - , block_state(0) - {} - - // Get the world-space AABB - AABB world_aabb() const { - return bounding_box.offset(x, y, z); - } -}; - -// ----------------------------------------------------------- -// Block data for collision (sent from Python) -// ----------------------------------------------------------- -struct BlockData { - int32_t x, y, z; - uint16_t block_state; -}; - -// ----------------------------------------------------------- -// Collision result -// ----------------------------------------------------------- -struct CollisionResult { - double overlap_x, overlap_y, overlap_z; - int32_t block_x, block_y, block_z; - bool collided; -}; - -// ----------------------------------------------------------- -// Physics update result -// ----------------------------------------------------------- -struct PhysicsUpdate { - int32_t entity_id; - double new_x, new_y, new_z; - double new_vx, new_vy, new_vz; - bool on_ground; - - // Collision events - bool collided_x, collided_y, collided_z; - - // For falling blocks that have landed - bool landed; - uint16_t landed_block_state; - int32_t landed_x, landed_y, landed_z; -}; - -// ----------------------------------------------------------- -// Fluid flow update -// ----------------------------------------------------------- -struct FluidUpdate { - int32_t x, y, z; - uint16_t new_block_state; // The fluid block to place - int8_t new_fluid_level; // Fluid level (0-7 for water/lava) -}; - -// ----------------------------------------------------------- -// Block collision shape -// ----------------------------------------------------------- -enum class BlockShape : uint8_t { - EMPTY = 0, // No collision (air, etc.) - FULL = 1, // Full 1x1x1 cube - PARTIAL = 2, // Has a custom AABB (slabs, stairs, etc.) - FLUID = 3, // Fluid block (water, lava) — special handling -}; - -// ----------------------------------------------------------- -// PhysicsEngine — main class -// ----------------------------------------------------------- -class PhysicsEngine { -public: - PhysicsEngine(); - ~PhysicsEngine(); - - // ---- Entity management ---- - - // Add or update an entity - void set_entity(const PhysicsEntity& entity); - - // Remove an entity - void remove_entity(int32_t entity_id); - - // ---- Block data management ---- - - // Set blocks for collision detection. - // Python sends only the blocks near entities. - void set_blocks(const std::vector& blocks); - - // Clear all block data (call when chunks unload) - void clear_blocks(); - - // ---- Simulation ---- - - // Process one physics tick. - // Returns updated entity positions and collision events. - std::vector tick(); - - // ---- Block property lookup ---- - - // Get the collision shape of a block - BlockShape get_block_shape(uint16_t block_state) const; - - // Get the collision AABB of a block (in block-local coordinates) - // Returns true if the block has collision, false if empty - bool get_block_aabb(uint16_t block_state, AABB& out) const; - - // Check if a block is a fluid - bool is_fluid(uint16_t block_state) const; - - // ---- Fluid simulation ---- - - // Process fluid flow for all tracked fluid blocks - std::vector tick_fluids(); - - // Add a fluid source block - void add_fluid_source(int x, int y, int z, uint16_t block_state, int8_t level); - - // Remove a fluid source - void remove_fluid_source(int x, int y, int z); - -private: - // Entity map - std::unordered_map entities_; - - // Block data (spatial hash for fast lookup) - struct BlockKey { - int32_t x, y, z; - bool operator==(const BlockKey& o) const { - return x == o.x && y == o.y && z == o.z; - } - }; - - struct BlockKeyHash { - size_t operator()(const BlockKey& k) const { - size_t h = 14695981039346656037ULL; - h ^= static_cast(k.x); h *= 1099511628211ULL; - h ^= static_cast(k.y); h *= 1099511628211ULL; - h ^= static_cast(k.z); h *= 1099511628211ULL; - return h; - } - }; - - std::unordered_map blocks_; - - // Fluid sources - struct FluidSource { - int32_t x, y, z; - uint16_t block_state; - int8_t level; - }; - std::vector fluid_sources_; - - // ---- Internal methods ---- - - // Apply gravity and drag to an entity - void apply_forces(PhysicsEntity& entity); - - // Resolve entity-world collisions - void resolve_collisions(PhysicsEntity& entity, PhysicsUpdate& update); - - // Get all block AABBs that could collide with the given entity AABB - std::vector get_potential_collisions(const AABB& entity_aabb) const; - - // Swept AABB collision test - CollisionResult swept_aabb(const AABB& entity, const AABB& block, - double dx, double dy, double dz) const; - - // Check if a block position is solid - bool is_solid(int32_t x, int32_t y, int32_t z) const; - - // Get block state at position (0 = air if not tracked) - uint16_t get_block_at(int32_t x, int32_t y, int32_t z) const; - - // Initialize default block shapes - void init_default_shapes(); -}; - -} // namespace pymc - -#endif // PYMC_PHYSICS_ENGINE_H diff --git a/native/plugins/bukkit_api.h b/native/plugins/bukkit_api.h deleted file mode 100755 index 3eec885..0000000 --- a/native/plugins/bukkit_api.h +++ /dev/null @@ -1,404 +0,0 @@ -// ============================================================ -// PyMC - Plugin API: Server/World/Player Types -// -// PYMC Plugin API provides a Bukkit-inspired event system for -// Python plugins. It does NOT run Java Bukkit/Paper plugins. -// -// Java Bukkit/Paper plugins require a JVM and the full Bukkit -// class hierarchy, which cannot be provided by a Python/C++ -// server. This API provides equivalent data types and operations -// for PYMC's own Python plugin system. -// -// Architecture: -// PyMCServer → PYMC server operations -// PyMCPlayer → PYMC Connection operations -// PyMCWorld → PYMC WorldStorage + terrain operations -// PyMCBlock → PYMC block state operations -// ============================================================ - -#ifndef PYMC_PLUGIN_API_H -#define PYMC_PLUGIN_API_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace pymc { -namespace plugins { - -// =========================================================== -// Basic Types -// =========================================================== - -struct Location { - std::string world_name; - double x, y, z; - float pitch, yaw; - - Location() - : x(0), y(64), z(0), pitch(0), yaw(0) {} - - Location(double x_, double y_, double z_) - : x(x_), y(y_), z(z_), pitch(0), yaw(0) {} - - Location(const std::string& world, double x_, double y_, double z_) - : world_name(world), x(x_), y(y_), z(z_), pitch(0), yaw(0) {} - - double distance(const Location& other) const { - double dx = x - other.x; - double dy = y - other.y; - double dz = z - other.z; - return std::sqrt(dx * dx + dy * dy + dz * dz); - } - - int block_x() const { return static_cast(std::floor(x)); } - int block_y() const { return static_cast(std::floor(y)); } - int block_z() const { return static_cast(std::floor(z)); } -}; - -enum class GameMode { - SURVIVAL = 0, - CREATIVE = 1, - ADVENTURE = 2, - SPECTATOR = 3 -}; - -enum class Difficulty { - PEACEFUL = 0, - EASY = 1, - NORMAL = 2, - HARD = 3 -}; - -enum class WeatherType { - CLEAR, - RAIN, - THUNDER -}; - -enum class SoundCategory { - MASTER, - MUSIC, - RECORDS, - WEATHER, - BLOCKS, - HOSTILE, - NEUTRAL, - PLAYERS, - AMBIENT, - VOICE -}; - -// =========================================================== -// BlockData -// =========================================================== - -struct BlockData { - std::string material; // e.g. "minecraft:stone" - std::map properties; // block state properties - - BlockData() = default; - explicit BlockData(const std::string& mat) : material(mat) {} - - bool is_air() const { - return material == "minecraft:air" || material == "minecraft:cave_air"; - } - - // Get a block state property - std::optional get_property(const std::string& key) const { - auto it = properties.find(key); - if (it != properties.end()) return it->second; - return std::nullopt; - } - - // Set a block state property - void set_property(const std::string& key, const std::string& value) { - properties[key] = value; - } -}; - -// =========================================================== -// PyMCBlock -// =========================================================== - -class PyMCBlock { -public: - PyMCBlock(const Location& loc, const BlockData& data) - : location_(loc), data_(data) {} - - // Block position - int x() const { return location_.block_x(); } - int y() const { return location_.block_y(); } - int z() const { return location_.block_z(); } - const Location& location() const { return location_; } - - // Block data - const BlockData& block_data() const { return data_; } - void set_block_data(const BlockData& data) { data_ = data; } - - // Convenience - const std::string& type() const { return data_.material; } - bool is_air() const { return data_.is_air(); } - -private: - Location location_; - BlockData data_; -}; - -// =========================================================== -// PyMCPlayer -// =========================================================== - -class PyMCPlayer { -public: - explicit PyMCPlayer(const std::string& uuid, const std::string& name) - : uuid_(uuid), name_(name), location_("world", 0, 64, 0) - , health_(20.0), max_health_(20.0), food_level_(20) - , game_mode_(GameMode::SURVIVAL), online_(true) - , experience_(0), experience_level_(0) - , flying_(false), allow_flight_(false) - {} - - // Identity - const std::string& uuid() const { return uuid_; } - const std::string& name() const { return name_; } - - // Location - const Location& location() const { return location_; } - void set_location(const Location& loc) { location_ = loc; } - - // Teleport the player - void teleport(const Location& loc); - - // Health - double health() const { return health_; } - void set_health(double h) { health_ = std::max(0.0, std::min(h, max_health_)); } - double max_health() const { return max_health_; } - - // Food - int food_level() const { return food_level_; } - void set_food_level(int f) { food_level_ = std::max(0, std::min(f, 20)); } - - // Game mode - GameMode game_mode() const { return game_mode_; } - void set_game_mode(GameMode mode) { game_mode_ = mode; } - - // Experience - int experience_level() const { return experience_level_; } - void set_experience_level(int lvl) { experience_level_ = std::max(0, lvl); } - float experience() const { return experience_; } - void set_experience(float exp) { experience_ = std::max(0.0f, std::min(exp, 1.0f)); } - - // Flight - bool is_flying() const { return flying_; } - void set_flying(bool fly) { flying_ = fly; } - bool get_allow_flight() const { return allow_flight_; } - void set_allow_flight(bool allow) { allow_flight_ = allow; } - - // Online status - bool is_online() const { return online_; } - void set_online(bool o) { online_ = o; } - - // Communication - void send_message(const std::string& msg); - void send_title(const std::string& title, const std::string& subtitle, - int fade_in = 10, int stay = 70, int fade_out = 20); - void send_action_bar(const std::string& msg); - - // Inventory - void give_item(const std::string& material, int amount = 1); - void clear_inventory(); - - // Permissions - bool has_permission(const std::string& perm) const; - void set_permission(const std::string& perm, bool value); - -private: - std::string uuid_; - std::string name_; - Location location_; - double health_; - double max_health_; - int food_level_; - GameMode game_mode_; - bool online_; - float experience_; - int experience_level_; - bool flying_; - bool allow_flight_; - std::map permissions_; -}; - -// =========================================================== -// PyMCWorld -// =========================================================== - -class PyMCWorld { -public: - explicit PyMCWorld(const std::string& name) - : name_(name), difficulty_(Difficulty::NORMAL) - , time_(0), full_time_(0), weather_(WeatherType::CLEAR) - , thundering_(false), weather_duration_(0) - , spawn_location_(name, 0, 64, 0) - , sea_level_(63), min_height_(-64), max_height_(319) - {} - - // Identity - const std::string& name() const { return name_; } - - // World properties - Difficulty difficulty() const { return difficulty_; } - void set_difficulty(Difficulty d) { difficulty_ = d; } - - int sea_level() const { return sea_level_; } - int min_height() const { return min_height_; } - int max_height() const { return max_height_; } - - // Time - long time() const { return time_; } - void set_time(long t) { time_ = t % 24000; } - long full_time() const { return full_time_; } - void set_full_time(long t) { full_time_ = t; } - - // Weather - WeatherType weather() const { return weather_; } - void set_weather(WeatherType w) { weather_ = w; } - bool is_thundering() const { return thundering_; } - void set_thundering(bool t) { thundering_ = t; } - int weather_duration() const { return weather_duration_; } - void set_weather_duration(int d) { weather_duration_ = d; } - - // Spawn - const Location& spawn_location() const { return spawn_location_; } - void set_spawn_location(const Location& loc) { spawn_location_ = loc; } - - // Block operations → PYMC WorldStorage + terrain operations - PyMCBlock get_block_at(int x, int y, int z); - void set_block_at(int x, int y, int z, const BlockData& data); - - // Chunk operations → PYMC chunk system - bool is_chunk_loaded(int cx, int cz) const; - bool load_chunk(int cx, int cz); - void unload_chunk(int cx, int cz); - - // Entity operations - void spawn_entity(const std::string& entity_type, const Location& loc); - std::vector get_entities_in_chunk(int cx, int cz) const; - - // Player operations - std::vector> get_players() const; - - // Height - int get_highest_block_y_at(int x, int z); - - // Biome - std::string get_biome_at(int x, int z) const; - void set_biome_at(int x, int z, const std::string& biome); - -private: - std::string name_; - Difficulty difficulty_; - long time_; - long full_time_; - WeatherType weather_; - bool thundering_; - int weather_duration_; - Location spawn_location_; - int sea_level_; - int min_height_; - int max_height_; -}; - -// =========================================================== -// PyMCServer -// =========================================================== - -class PyMCServer { -public: - PyMCServer() - : server_name_("PYMC"), server_version_("1.21.1") - , api_version_("1.21"), max_players_(20) - , motd_("A PYMC Server"), tps_(20.0) - {} - - // Server info - const std::string& server_name() const { return server_name_; } - const std::string& server_version() const { return server_version_; } - const std::string& api_version() const { return api_version_; } - const std::string& motd() const { return motd_; } - void set_motd(const std::string& m) { motd_ = m; } - - // Players → PYMC Connection operations - std::vector get_online_players() const; - std::shared_ptr get_player(const std::string& name) const; - std::shared_ptr get_player_by_uuid(const std::string& uuid) const; - int online_player_count() const; - int max_players() const { return max_players_; } - void set_max_players(int m) { max_players_ = m; } - - // Broadcast - void broadcast_message(const std::string& msg); - void broadcast_message(const std::string& msg, const std::string& permission); - - // Commands → PYMC command dispatcher - bool dispatch_command(const std::string& cmd); - bool dispatch_command(const std::string& cmd, const std::string& sender); - - // Worlds → PYMC WorldStorage - std::vector get_world_names() const; - std::shared_ptr get_world(const std::string& name) const; - std::shared_ptr create_world(const std::string& name); - - // Server properties - double tps() const { return tps_; } - bool is_running() const { return running_; } - void shutdown(); - void set_shutdown(bool s) { running_ = !s; } - - // Plugin management - bool is_plugin_enabled(const std::string& name) const; - - // Scheduler (maps to PYMC's tick loop) - using TaskCallback = std::function; - int schedule_sync_delayed_task(TaskCallback task, long delay_ticks = 0); - int schedule_sync_repeating_task(TaskCallback task, long delay_ticks, long period_ticks); - void cancel_task(int task_id); - void cancel_all_tasks(); - -private: - std::string server_name_; - std::string server_version_; - std::string api_version_; - int max_players_; - std::string motd_; - double tps_; - bool running_ = true; - - // Player registry (uuid -> player) - mutable std::unordered_map> players_; - - // World registry (name -> world) - mutable std::unordered_map> worlds_; - - // Scheduler - int next_task_id_ = 0; - struct ScheduledTask { - int id; - TaskCallback callback; - long execute_tick; - long period; // 0 = one-shot - bool sync; // always true for now - }; - std::vector scheduled_tasks_; -}; - -} // namespace plugins -} // namespace pymc - -#endif // PYMC_PLUGIN_API_H diff --git a/native/plugins/event_system.h b/native/plugins/event_system.h deleted file mode 100755 index ba78ebc..0000000 --- a/native/plugins/event_system.h +++ /dev/null @@ -1,464 +0,0 @@ -// ============================================================ -// PyMC - Event System -// -// Provides an event bus that allows PYMC Python plugins and mods -// to register listeners for game events and receive callbacks -// when those events fire. -// -// The event system is inspired by Bukkit's event model but is -// PYMC-native — it does NOT run Java Bukkit/Paper plugins. -// -// Architecture: -// EventBus - Central event dispatch hub -// Event - Base event with cancellation support -// EventPriority - Listener priority ordering -// EventHandler - Type-erased callback wrapper -// -// Event flow: -// 1. PYMC detects game action (player join, block break, etc.) -// 2. Event is created with relevant data -// 3. EventBus fires event to all registered listeners -// 4. Listeners are called in priority order (LOWEST→MONITOR) -// 5. Any listener can cancel the event -// 6. PYMC checks cancellation before proceeding -// ============================================================ - -#ifndef PYMC_EVENT_SYSTEM_H -#define PYMC_EVENT_SYSTEM_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace pymc { -namespace plugins { - -// =========================================================== -// EventPriority -// =========================================================== - -enum class EventPriority { - LOWEST = 0, // First to execute; other plugins can override - LOW = 1, - NORMAL = 2, // Default priority - HIGH = 3, - HIGHEST = 4, // Last to modify the event - MONITOR = 5 // Read-only; should not modify the event -}; - -// Convert priority to string (for debugging) -inline const char* event_priority_name(EventPriority p) { - switch (p) { - case EventPriority::LOWEST: return "LOWEST"; - case EventPriority::LOW: return "LOW"; - case EventPriority::NORMAL: return "NORMAL"; - case EventPriority::HIGH: return "HIGH"; - case EventPriority::HIGHEST: return "HIGHEST"; - case EventPriority::MONITOR: return "MONITOR"; - default: return "UNKNOWN"; - } -} - -// =========================================================== -// Event -// =========================================================== - -struct Event { - // Event type name (e.g. "PlayerJoinEvent", "BlockBreakEvent") - std::string name; - - // Event data key-value pairs (type-erased for flexibility) - std::map data; - - // Whether the event has been cancelled - // Only cancellable events respect this flag - bool cancelled = false; - - // Whether this event is cancellable - bool cancellable = true; - - // The plugin that created this event (empty if PYMC-internal) - std::string source_plugin; - - // Timestamp (game tick when event fired) - long tick = 0; - - Event() = default; - explicit Event(const std::string& n, bool cancellable_ = true) - : name(n), cancellable(cancellable_) {} - - // Convenience data accessors - void set_data(const std::string& key, const std::string& value) { - data[key] = value; - } - - std::string get_data(const std::string& key, - const std::string& default_val = "") const { - auto it = data.find(key); - return it != data.end() ? it->second : default_val; - } - - bool has_data(const std::string& key) const { - return data.find(key) != data.end(); - } - - // Cancel the event - void cancel() { - if (cancellable) cancelled = true; - } - - // Un-cancel the event - void uncancel() { - cancelled = false; - } -}; - -// =========================================================== -// Common Event Types (Bukkit-compatible names) -// =========================================================== - -namespace event_names { - -// Player events -constexpr const char* PLAYER_JOIN = "PlayerJoinEvent"; -constexpr const char* PLAYER_QUIT = "PlayerQuitEvent"; -constexpr const char* PLAYER_KICK = "PlayerKickEvent"; -constexpr const char* PLAYER_CHAT = "AsyncPlayerChatEvent"; -constexpr const char* PLAYER_COMMAND = "PlayerCommandPreprocessEvent"; -constexpr const char* PLAYER_MOVE = "PlayerMoveEvent"; -constexpr const char* PLAYER_TELEPORT = "PlayerTeleportEvent"; -constexpr const char* PLAYER_INTERACT = "PlayerInteractEvent"; -constexpr const char* PLAYER_RESPAWN = "PlayerRespawnEvent"; -constexpr const char* PLAYER_DEATH = "PlayerDeathEvent"; -constexpr const char* PLAYER_GAME_MODE = "PlayerGameModeChangeEvent"; -constexpr const char* PLAYER_EXP_CHANGE = "PlayerExpChangeEvent"; -constexpr const char* PLAYER_LEVEL_CHANGE = "PlayerLevelChangeEvent"; -constexpr const char* PLAYER_TOGGLE_FLIGHT = "PlayerToggleFlightEvent"; -constexpr const char* PLAYER_TOGGLE_SNEAK = "PlayerToggleSneakEvent"; -constexpr const char* PLAYER_TOGGLE_SPRINT = "PlayerToggleSprintEvent"; -constexpr const char* PLAYER_PORTAL = "PlayerPortalEvent"; -constexpr const char* PLAYER_BED_ENTER = "PlayerBedEnterEvent"; -constexpr const char* PLAYER_FISH = "PlayerFishEvent"; -constexpr const char* PLAYER_ITEM_BREAK = "PlayerItemBreakEvent"; -constexpr const char* PLAYER_ITEM_HELD = "PlayerItemHeldEvent"; -constexpr const char* PLAYER_SWAP_HAND = "PlayerSwapHandItemsEvent"; -constexpr const char* PLAYER_EGG_THROW = "PlayerEggThrowEvent"; - -// Block events -constexpr const char* BLOCK_BREAK = "BlockBreakEvent"; -constexpr const char* BLOCK_PLACE = "BlockPlaceEvent"; -constexpr const char* BLOCK_DAMAGE = "BlockDamageEvent"; -constexpr const char* BLOCK_BURN = "BlockBurnEvent"; -constexpr const char* BLOCK_IGNITE = "BlockIgniteEvent"; -constexpr const char* BLOCK_REDSTONE = "BlockRedstoneEvent"; -constexpr const char* BLOCK_EXPLODE = "BlockExplodeEvent"; -constexpr const char* BLOCK_DISPENSE = "BlockDispenseEvent"; -constexpr const char* BLOCK_FORM = "BlockFormEvent"; -constexpr const char* BLOCK_SPREAD = "BlockSpreadEvent"; -constexpr const char* BLOCK_FROM_TO = "BlockFromToEvent"; -constexpr const char* BLOCK_PHYSICS = "BlockPhysicsEvent"; -constexpr const char* BLOCK_MULTIPLACE = "BlockMultiPlaceEvent"; -constexpr const char* SIGN_CHANGE = "SignChangeEvent"; -constexpr const char* NOTE_PLAY = "NotePlayEvent"; - -// Entity events -constexpr const char* ENTITY_DAMAGE = "EntityDamageEvent"; -constexpr const char* ENTITY_DAMAGE_BY_ENTITY = "EntityDamageByEntityEvent"; -constexpr const char* ENTITY_DEATH = "EntityDeathEvent"; -constexpr const char* ENTITY_SPAWN = "EntitySpawnEvent"; -constexpr const char* ENTITY_REMOVE = "EntityRemoveEvent"; -constexpr const char* ENTITY_EXPLODE = "EntityExplodeEvent"; -constexpr const char* ENTITY_TARGET = "EntityTargetEvent"; -constexpr const char* ENTITY_SHOOT_BOW = "EntityShootBowEvent"; -constexpr const char* ENTITY_REGAIN_HEALTH = "EntityRegainHealthEvent"; -constexpr const char* ENTITY_PORTAL_ENTER = "EntityPortalEnterEvent"; -constexpr const char* PROJECTILE_HIT = "ProjectileHitEvent"; -constexpr const char* PROJECTILE_LAUNCH = "ProjectileLaunchEvent"; -constexpr const char* FOOD_LEVEL_CHANGE = "FoodLevelChangeEvent"; - -// World events -constexpr const char* CHUNK_LOAD = "ChunkLoadEvent"; -constexpr const char* CHUNK_UNLOAD = "ChunkUnloadEvent"; -constexpr const char* CHUNK_POPULATE = "ChunkPopulateEvent"; -constexpr const char* WORLD_LOAD = "WorldLoadEvent"; -constexpr const char* WORLD_UNLOAD = "WorldUnloadEvent"; -constexpr const char* WORLD_SAVE = "WorldSaveEvent"; -constexpr const char* WEATHER_CHANGE = "WeatherChangeEvent"; -constexpr const char* THUNDER_CHANGE = "ThunderChangeEvent"; -constexpr const char* TIME_CHANGE = "TimeChangeEvent"; - -// Server events -constexpr const char* SERVER_COMMAND = "ServerCommandEvent"; -constexpr const char* REMOTE_COMMAND = "RemoteServerCommandEvent"; -constexpr const char* PLUGIN_ENABLE = "PluginEnableEvent"; -constexpr const char* PLUGIN_DISABLE = "PluginDisableEvent"; - -// Inventory events -constexpr const char* INVENTORY_CLICK = "InventoryClickEvent"; -constexpr const char* INVENTORY_OPEN = "InventoryOpenEvent"; -constexpr const char* INVENTORY_CLOSE = "InventoryCloseEvent"; -constexpr const char* INVENTORY_DRAG = "InventoryDragEvent"; -constexpr const char* CRAFT_ITEM = "CraftItemEvent"; -constexpr const char* BREW_EVENT = "BrewEvent"; -constexpr const char* FURNACE_SMELT = "FurnaceSmeltEvent"; -constexpr const char* FURNACE_BURN = "FurnaceBurnEvent"; -constexpr const char* PREPARE_ANVIL = "PrepareAnvilEvent"; -constexpr const char* PREPARE_CRAFT = "PrepareItemCraftEvent"; - -// Vehicle events -constexpr const char* VEHICLE_CREATE = "VehicleCreateEvent"; -constexpr const char* VEHICLE_DESTROY = "VehicleDestroyEvent"; -constexpr const char* VEHICLE_ENTER = "VehicleEnterEvent"; -constexpr const char* VEHICLE_EXIT = "VehicleExitEvent"; -constexpr const char* VEHICLE_MOVE = "VehicleMoveEvent"; -constexpr const char* VEHICLE_DAMAGE = "VehicleDamageEvent"; -constexpr const char* VEHICLE_COLLISION = "VehicleEntityCollisionEvent"; - -// Hanging events -constexpr const char* HANGING_BREAK = "HangingBreakEvent"; -constexpr const char* HANGING_PLACE = "HangingPlaceEvent"; - -} // namespace event_names - -// =========================================================== -// EventHandler -// =========================================================== - -// Type-erased event handler that wraps a std::function -class EventHandler { -public: - using Callback = std::function; - - EventHandler(EventPriority priority, Callback callback, - const std::string& plugin_name = "") - : priority_(priority) - , callback_(std::move(callback)) - , plugin_name_(plugin_name) - , active_(true) - {} - - // Call the handler - void operator()(Event& event) { - if (active_) { - callback_(event); - } - } - - EventPriority priority() const { return priority_; } - const std::string& plugin_name() const { return plugin_name_; } - bool is_active() const { return active_; } - void set_active(bool a) { active_ = a; } - - // Comparison for priority ordering - bool operator<(const EventHandler& other) const { - return static_cast(priority_) < static_cast(other.priority_); - } - -private: - EventPriority priority_; - Callback callback_; - std::string plugin_name_; - bool active_; -}; - -// =========================================================== -// EventBus -// =========================================================== - -class EventBus { -public: - EventBus() = default; - ~EventBus() = default; - - // --- Listener Registration --- - - // Register a listener for a specific event type - // Returns: handler ID (for later unregistration) - int register_listener(const std::string& event_name, - EventPriority priority, - EventHandler::Callback handler, - const std::string& plugin_name = ""); - - // Convenience: register at NORMAL priority - int register_listener(const std::string& event_name, - EventHandler::Callback handler, - const std::string& plugin_name = ""); - - // Unregister a specific handler by ID - bool unregister_handler(int handler_id); - - // Unregister all handlers for a plugin - void unregister_all(const std::string& plugin_name); - - // Unregister all handlers for a specific event - void unregister_event(const std::string& event_name); - - // --- Event Firing --- - - // Fire an event to all registered listeners in priority order - void fire_event(Event& event); - - // Fire an event (copy, returns the event after processing) - Event fire_event_copy(const Event& event); - - // --- Query --- - - // Check if any listeners are registered for an event - bool has_listeners(const std::string& event_name) const; - - // Get number of listeners for an event - size_t listener_count(const std::string& event_name) const; - - // Get total number of listeners across all events - size_t total_listener_count() const; - - // Get all event names that have listeners - std::vector registered_event_names() const; - -private: - // Re-sort handlers for an event (called after registration changes) - void sort_handlers(const std::string& event_name); - -private: - // event_name -> list of (handler_id, handler) - std::unordered_map>> handlers_; - - // Next handler ID - int next_handler_id_ = 0; - - // Mutex for thread safety - mutable std::mutex mutex_; -}; - -// =========================================================== -// Inline Implementations -// =========================================================== - -inline int EventBus::register_listener( - const std::string& event_name, - EventPriority priority, - EventHandler::Callback handler, - const std::string& plugin_name) -{ - std::lock_guard lock(mutex_); - int id = next_handler_id_++; - auto& list = handlers_[event_name]; - list.emplace_back(id, EventHandler(priority, std::move(handler), plugin_name)); - sort_handlers(event_name); - return id; -} - -inline int EventBus::register_listener( - const std::string& event_name, - EventHandler::Callback handler, - const std::string& plugin_name) -{ - return register_listener(event_name, EventPriority::NORMAL, - std::move(handler), plugin_name); -} - -inline bool EventBus::unregister_handler(int handler_id) { - std::lock_guard lock(mutex_); - for (auto& [name, list] : handlers_) { - auto it = std::remove_if(list.begin(), list.end(), - [handler_id](const auto& pair) { - return pair.first == handler_id; - }); - if (it != list.end()) { - list.erase(it, list.end()); - return true; - } - } - return false; -} - -inline void EventBus::unregister_all(const std::string& plugin_name) { - std::lock_guard lock(mutex_); - for (auto& [name, list] : handlers_) { - auto it = std::remove_if(list.begin(), list.end(), - [&plugin_name](const auto& pair) { - return pair.second.plugin_name() == plugin_name; - }); - list.erase(it, list.end()); - } -} - -inline void EventBus::unregister_event(const std::string& event_name) { - std::lock_guard lock(mutex_); - handlers_.erase(event_name); -} - -inline void EventBus::fire_event(Event& event) { - std::lock_guard lock(mutex_); - auto it = handlers_.find(event.name); - if (it == handlers_.end()) return; - - for (auto& [id, handler] : it->second) { - if (!handler.is_active()) continue; - // MONITOR handlers should not modify the event, - // but we can't enforce this in C++ - it's a convention - handler(event); - // If event is cancelled and handler is MONITOR, still fire - // (MONITOR is for reading, not cancelling) - } -} - -inline Event EventBus::fire_event_copy(const Event& event) { - Event copy = event; - fire_event(copy); - return copy; -} - -inline bool EventBus::has_listeners(const std::string& event_name) const { - std::lock_guard lock(mutex_); - auto it = handlers_.find(event_name); - return it != handlers_.end() && !it->second.empty(); -} - -inline size_t EventBus::listener_count(const std::string& event_name) const { - std::lock_guard lock(mutex_); - auto it = handlers_.find(event_name); - return it != handlers_.end() ? it->second.size() : 0; -} - -inline size_t EventBus::total_listener_count() const { - std::lock_guard lock(mutex_); - size_t total = 0; - for (const auto& [name, list] : handlers_) { - total += list.size(); - } - return total; -} - -inline std::vector EventBus::registered_event_names() const { - std::lock_guard lock(mutex_); - std::vector names; - names.reserve(handlers_.size()); - for (const auto& [name, list] : handlers_) { - if (!list.empty()) { - names.push_back(name); - } - } - return names; -} - -inline void EventBus::sort_handlers(const std::string& event_name) { - auto it = handlers_.find(event_name); - if (it == handlers_.end()) return; - std::stable_sort(it->second.begin(), it->second.end(), - [](const auto& a, const auto& b) { - return a.second < b.second; - }); -} - -} // namespace plugins -} // namespace pymc - -#endif // PYMC_EVENT_SYSTEM_H diff --git a/native/plugins/jvm_bridge.h b/native/plugins/jvm_bridge.h deleted file mode 100755 index 493333d..0000000 --- a/native/plugins/jvm_bridge.h +++ /dev/null @@ -1,4 +0,0 @@ -// This file intentionally left empty. -// PYMC does NOT embed a JVM. Java plugin support (Bukkit/Paper) -// requires a JVM, which cannot be meaningfully embedded in a -// Python/C++ server. Use the PYMC Plugin API instead. diff --git a/native/plugins/plugin_loader.h b/native/plugins/plugin_loader.h deleted file mode 100755 index fa28bfc..0000000 --- a/native/plugins/plugin_loader.h +++ /dev/null @@ -1,204 +0,0 @@ -// ============================================================ -// PyMC - Plugin API: Plugin Loader -// -// Provides the core plugin loading infrastructure for PYMC -// native Python plugins. -// -// PYMC Plugin API provides a Bukkit-inspired event system for -// Python plugins. It does NOT run Java Bukkit/Paper plugins. -// -// Architecture: -// PluginLoader -// ├── EventBus - Event dispatch system -// ├── PyMCAPI - Server API types (PyMCServer, PyMCPlayer, etc.) -// └── PluginManager - Lifecycle management -// ============================================================ - -#ifndef PYMC_PLUGIN_LOADER_H -#define PYMC_PLUGIN_LOADER_H - -#include -#include -#include -#include -#include -#include - -#include "event_system.h" -#include "bukkit_api.h" - -namespace pymc { -namespace plugins { - -// =========================================================== -// PluginMetadata -// =========================================================== - -struct PluginMetadata { - std::string name; // Plugin name - std::string version; // Plugin version - std::string main_class; // Python module/class entry point - std::string api_version; // Target PYMC API version (e.g. "1.21") - std::string description; // Human-readable description - std::vector authors; - std::vector depend; // Hard dependencies - std::vector softdepend; // Soft dependencies - std::vector loadbefore; // Load before these - std::string prefix; // Log prefix -}; - -// =========================================================== -// PluginState -// =========================================================== - -enum class PluginState { - UNLOADED, - LOADED, - ENABLING, - ENABLED, - DISABLING, - DISABLED, - ERRORED -}; - -// =========================================================== -// PluginInstance -// =========================================================== - -class PluginInstance { -public: - PluginInstance(const std::string& package_path, const PluginMetadata& meta) - : package_path_(package_path) - , metadata_(meta) - , state_(PluginState::UNLOADED) - , event_bus_(std::make_shared()) - {} - - const std::string& package_path() const { return package_path_; } - const PluginMetadata& metadata() const { return metadata_; } - PluginState state() const { return state_; } - void set_state(PluginState s) { state_ = s; } - std::shared_ptr event_bus() { return event_bus_; } - - // Register a command handler for this plugin - void register_command(const std::string& name, - std::function handler) { - commands_[name] = handler; - } - - // Check if plugin handles a command - bool has_command(const std::string& name) const { - return commands_.find(name) != commands_.end(); - } - - // Execute a command handler - void execute_command(const std::string& name, const std::string& args) { - auto it = commands_.find(name); - if (it != commands_.end()) { - it->second(args); - } - } - -private: - std::string package_path_; - PluginMetadata metadata_; - PluginState state_; - std::shared_ptr event_bus_; - std::unordered_map> commands_; -}; - -// =========================================================== -// PluginLoader -// =========================================================== - -class PluginLoader { -public: - PluginLoader(); - ~PluginLoader(); - - // --- Initialization --- - - // Initialize the plugin system - bool initialize(); - - // Shut down the plugin system (disables all plugins) - void shutdown(); - - // --- Plugin Loading --- - - // Load a PYMC Python plugin from its package directory - // Returns: true if the plugin was loaded successfully - bool load_plugin(const std::string& package_path); - - // Load all plugins from a directory - // Scans for Python packages with pymc_plugin.json or plugin.yml - // Returns: number of plugins loaded successfully - int load_plugins_from_dir(const std::string& plugins_dir); - - // --- Lifecycle --- - - // Call on_enable() for all loaded plugins - void enable_all(); - - // Call on_disable() for all loaded plugins - void disable_all(); - - // Enable a specific plugin by name - bool enable_plugin(const std::string& name); - - // Disable a specific plugin by name - bool disable_plugin(const std::string& name); - - // --- Event System --- - - // Fire an event to all registered listeners - void fire_event(const Event& event); - - // Fire an event only to a specific plugin's listeners - void fire_event_to_plugin(const std::string& plugin_name, const Event& event); - - // --- Query --- - - // Get list of loaded plugin names - std::vector get_plugin_names() const; - - // Check if a plugin is loaded - bool is_plugin_loaded(const std::string& name) const; - - // Get plugin state - PluginState get_plugin_state(const std::string& name) const; - - // Get the PyMCServer API interface - PyMCServer& server_api() { return server_api_; } - - // Get total number of loaded plugins - size_t plugin_count() const { return plugins_.size(); } - -private: - // Parse pymc_plugin.json from a plugin package - bool parse_plugin_json(const std::string& package_path, PluginMetadata& out); - - // Resolve plugin dependencies (topological sort) - bool resolve_dependencies(std::vector& load_order); - - // Check if all dependencies for a plugin are satisfied - bool check_dependencies(const PluginMetadata& meta) const; - - // Internal enable logic - bool enable_plugin_internal(const std::shared_ptr& plugin); - - // Internal disable logic - void disable_plugin_internal(const std::shared_ptr& plugin); - -private: - bool initialized_; - PyMCServer server_api_; - std::unordered_map> plugins_; - std::vector load_order_; // Dependency-sorted load order - mutable std::mutex mutex_; -}; - -} // namespace plugins -} // namespace pymc - -#endif // PYMC_PLUGIN_LOADER_H diff --git a/native/plugins/plugin_loader_api.cpp b/native/plugins/plugin_loader_api.cpp deleted file mode 100755 index ba455bd..0000000 --- a/native/plugins/plugin_loader_api.cpp +++ /dev/null @@ -1,197 +0,0 @@ -// ============================================================ -// PyMC - Plugin Loader C API Bridge Implementation -// -// Provides C-compatible stub API for Python ctypes bindings. -// Full PluginLoader/BukkitServer implementation requires JVM -// integration; these stubs allow the shared library to compile -// and load while the Python side handles actual plugin logic. -// ============================================================ - -#include "plugin_loader_api.h" -#include "event_system.h" - -#include -#include -#include -#include - -// =========================================================== -// Internal state -// =========================================================== - -static bool g_initialized = false; -static int g_plugin_count = 0; - -struct PythonCallback { - std::string event_name; - int priority; - void (*callback)(const char* event_name, const char* data_json); -}; - -static std::vector g_python_callbacks; -static int g_next_handler_id = 0; - -// =========================================================== -// Plugin Loader Lifecycle -// =========================================================== - -int pymc_plugin_loader_initialize() { - g_initialized = true; - return 1; -} - -void pymc_plugin_loader_shutdown() { - g_initialized = false; - g_plugin_count = 0; - g_python_callbacks.clear(); -} - -// =========================================================== -// Plugin Loading (stubs — Python handles actual loading) -// =========================================================== - -int pymc_plugin_loader_load_plugin(const char* jar_path) { - if (!jar_path) return 0; - // Stub: actual loading handled by Python ModManager - g_plugin_count++; - return 1; -} - -int pymc_plugin_loader_load_plugins_from_dir(const char* plugins_dir) { - if (!plugins_dir) return 0; - // Stub: return 0 loaded; Python handles directory scanning - return 0; -} - -// =========================================================== -// Plugin Lifecycle -// =========================================================== - -int pymc_plugin_loader_enable_all() { - return g_initialized ? 1 : 0; -} - -void pymc_plugin_loader_disable_all() { - // No-op stub -} - -int pymc_plugin_loader_enable_plugin(const char* name) { - if (!name) return 0; - return 1; // Stub: always success -} - -int pymc_plugin_loader_disable_plugin(const char* name) { - // No-op stub - return 1; -} - -// =========================================================== -// Event System -// =========================================================== - -int pymc_plugin_loader_fire_event(const char* event_name, const char* data_json) { - if (!event_name) return 1; - - // Dispatch to all registered Python callbacks - for (const auto& cb : g_python_callbacks) { - if (cb.event_name == event_name || cb.event_name == "*") { - cb.callback(event_name, data_json ? data_json : ""); - } - } - - return 1; // Not cancelled -} - -int pymc_plugin_loader_register_listener( - const char* event_name, - int priority, - void (*callback)(const char* event_name, const char* data_json)) -{ - if (!event_name || !callback) return -1; - - int id = g_next_handler_id++; - PythonCallback pcb; - pcb.event_name = std::string(event_name); - pcb.priority = priority; - pcb.callback = callback; - g_python_callbacks.push_back(pcb); - - return id; -} - -int pymc_plugin_loader_unregister_handler(int /*handler_id*/) { - return 0; -} - -// =========================================================== -// Query -// =========================================================== - -int pymc_plugin_loader_plugin_count() { - return g_plugin_count; -} - -int pymc_plugin_loader_is_plugin_loaded(const char* name) { - if (!name) return 0; - return 0; // Stub: Python manages plugin state -} - -int pymc_plugin_loader_get_plugin_state(const char* name) { - if (!name) return 0; - return 0; // 0 = DISCOVERED (stub) -} - -double pymc_plugin_loader_get_tps() { - return 20.0; // Stub: return ideal TPS -} - -// =========================================================== -// Bukkit API Bridge (stubs — Python handles actual operations) -// =========================================================== - -void pymc_plugin_loader_broadcast_message(const char* message) { - // Stub: Python PluginManager handles broadcasting -} - -int pymc_plugin_loader_dispatch_command(const char* command) { - if (!command) return 0; - return 0; // Stub: not dispatched -} - -int pymc_plugin_loader_online_player_count() { - return 0; // Stub -} - -char* pymc_plugin_loader_get_online_players() { - const char* empty = "[]"; - char* cstr = new char[3]; - std::strcpy(cstr, empty); - return cstr; -} - -char* pymc_plugin_loader_get_world_names() { - const char* worlds = "[\"minecraft:overworld\"]"; - size_t len = std::strlen(worlds); - char* cstr = new char[len + 1]; - std::strcpy(cstr, worlds); - return cstr; -} - -void pymc_plugin_loader_free_string(char* str) { - delete[] str; -} - -// =========================================================== -// Version Info -// =========================================================== - -static const char* PLUGIN_LOADER_VERSION = "1.0.0"; -static const int PLUGIN_LOADER_API_VERSION = 1; - -const char* pymc_plugin_loader_get_version() { - return PLUGIN_LOADER_VERSION; -} - -int pymc_plugin_loader_get_api_version() { - return PLUGIN_LOADER_API_VERSION; -} diff --git a/native/plugins/plugin_loader_api.h b/native/plugins/plugin_loader_api.h deleted file mode 100755 index 9d4146b..0000000 --- a/native/plugins/plugin_loader_api.h +++ /dev/null @@ -1,142 +0,0 @@ -// ============================================================ -// PyMC - Plugin Loader C API Bridge -// -// Provides a C-compatible API that can be called from Python -// via ctypes to interact with the plugin compatibility layer. -// ============================================================ - -#ifdef _WIN32 -#define PYMC_EXPORT __declspec(dllexport) -#else -#define PYMC_EXPORT __attribute__((visibility("default"))) -#endif - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// =========================================================== -// Plugin Loader Lifecycle -// =========================================================== - -// Initialize the plugin loader system (sets up JVM bridge, API mappings) -// Returns: 1 on success, 0 on failure -PYMC_EXPORT int pymc_plugin_loader_initialize(); - -// Shut down the plugin loader (disables all plugins, tears down JVM) -PYMC_EXPORT void pymc_plugin_loader_shutdown(); - -// =========================================================== -// Plugin Loading -// =========================================================== - -// Load a .jar plugin file -// jar_path: path to the .jar file -// Returns: 1 if loaded successfully, 0 on failure -PYMC_EXPORT int pymc_plugin_loader_load_plugin(const char* jar_path); - -// Load all .jar files from a directory -// plugins_dir: directory containing .jar files -// Returns: number of plugins loaded successfully -PYMC_EXPORT int pymc_plugin_loader_load_plugins_from_dir(const char* plugins_dir); - -// =========================================================== -// Plugin Lifecycle -// =========================================================== - -// Enable all loaded plugins -// Returns: 1 on success, 0 on failure -PYMC_EXPORT int pymc_plugin_loader_enable_all(); - -// Disable all loaded plugins -PYMC_EXPORT void pymc_plugin_loader_disable_all(); - -// Enable a specific plugin by name -// Returns: 1 on success, 0 on failure (not found or error) -PYMC_EXPORT int pymc_plugin_loader_enable_plugin(const char* name); - -// Disable a specific plugin by name -// Returns: 1 on success, 0 on failure -PYMC_EXPORT int pymc_plugin_loader_disable_plugin(const char* name); - -// =========================================================== -// Event System -// =========================================================== - -// Fire an event to all registered listeners -// event_name: name of the event (e.g. "PlayerJoinEvent") -// data_json: JSON string with event data -// Returns: 1 if event was NOT cancelled, 0 if cancelled -PYMC_EXPORT int pymc_plugin_loader_fire_event(const char* event_name, - const char* data_json); - -// Register a Python-side event listener -// event_name: name of the event -// priority: 0=LOWEST, 1=LOW, 2=NORMAL, 3=HIGH, 4=HIGHEST, 5=MONITOR -// callback: function pointer called with (event_name, data_json) -// Returns: handler ID, or -1 on failure -PYMC_EXPORT int pymc_plugin_loader_register_listener( - const char* event_name, - int priority, - void (*callback)(const char* event_name, const char* data_json)); - -// Unregister a listener by handler ID -// Returns: 1 on success, 0 on failure -PYMC_EXPORT int pymc_plugin_loader_unregister_handler(int handler_id); - -// =========================================================== -// Query -// =========================================================== - -// Get the number of loaded plugins -PYMC_EXPORT int pymc_plugin_loader_plugin_count(); - -// Check if a plugin is loaded -// Returns: 1 if loaded, 0 if not -PYMC_EXPORT int pymc_plugin_loader_is_plugin_loaded(const char* name); - -// Get plugin state (0=UNLOADED, 1=LOADED, 2=ENABLING, 3=ENABLED, -// 4=DISABLING, 5=DISABLED, 6=ERRORED) -PYMC_EXPORT int pymc_plugin_loader_get_plugin_state(const char* name); - -// Get the server TPS -PYMC_EXPORT double pymc_plugin_loader_get_tps(); - -// =========================================================== -// Bukkit API Bridge -// =========================================================== - -// Broadcast a message to all online players -PYMC_EXPORT void pymc_plugin_loader_broadcast_message(const char* message); - -// Dispatch a server command -// Returns: 1 if command was handled, 0 if not -PYMC_EXPORT int pymc_plugin_loader_dispatch_command(const char* command); - -// Get online player count -PYMC_EXPORT int pymc_plugin_loader_online_player_count(); - -// Get online player names as a JSON array string -// Caller must free the returned string with pymc_plugin_loader_free_string -PYMC_EXPORT char* pymc_plugin_loader_get_online_players(); - -// Get world names as a JSON array string -// Caller must free the returned string with pymc_plugin_loader_free_string -PYMC_EXPORT char* pymc_plugin_loader_get_world_names(); - -// Free a string returned by the plugin loader API -PYMC_EXPORT void pymc_plugin_loader_free_string(char* str); - -// =========================================================== -// Version Info -// =========================================================== - -PYMC_EXPORT const char* pymc_plugin_loader_get_version(); -PYMC_EXPORT int pymc_plugin_loader_get_api_version(); - -#ifdef __cplusplus -} -#endif diff --git a/native/pymc_native_server.cpp b/native/pymc_native_server.cpp deleted file mode 100755 index 22e9374..0000000 --- a/native/pymc_native_server.cpp +++ /dev/null @@ -1,483 +0,0 @@ -// ============================================================ -// PyMC - Native Server Process -// -// Long-running C++ process that communicates with Python via -// shared memory IPC. Handles: -// - Redstone simulation -// - Light propagation -// - Physics collision detection -// - Terrain generation (delegated to existing terrain_gen) -// - Mob AI (delegated to existing mob_ai) -// -// Protocol (over shared memory ring buffer): -// -// Command format: [1 byte command type][variable payload] -// Response format: [4 byte LE status][variable payload] -// -// Commands: -// 0x01: TICK - Process one tick for all engines -// 0x02: ADD_REDSTONE - Add redstone component -// 0x03: REMOVE_REDSTONE - Remove redstone component -// 0x04: SET_POWER - Set power level -// 0x05: CALC_LIGHT - Calculate chunk lighting -// 0x06: UPDATE_LIGHT - Incremental light update -// 0x07: SET_ENTITY - Add/update physics entity -// 0x08: REMOVE_ENTITY - Remove physics entity -// 0x09: SET_BLOCKS - Set block data for physics -// 0x0A: TICK_FLUIDS - Process fluid simulation -// 0x0B: PING - Keep-alive ping -// 0xFF: SHUTDOWN - Graceful shutdown -// -// ============================================================ - -#include "../core/ipc_shm.h" -#include "../redstone/redstone_engine.h" -#include "../lighting/light_engine.h" -#include "../physics/physics_engine.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -// Command types -constexpr uint8_t CMD_TICK = 0x01; -constexpr uint8_t CMD_ADD_REDSTONE = 0x02; -constexpr uint8_t CMD_REMOVE_REDSTONE = 0x03; -constexpr uint8_t CMD_SET_POWER = 0x04; -constexpr uint8_t CMD_CALC_LIGHT = 0x05; -constexpr uint8_t CMD_UPDATE_LIGHT = 0x06; -constexpr uint8_t CMD_SET_ENTITY = 0x07; -constexpr uint8_t CMD_REMOVE_ENTITY = 0x08; -constexpr uint8_t CMD_SET_BLOCKS = 0x09; -constexpr uint8_t CMD_TICK_FLUIDS = 0x0A; -constexpr uint8_t CMD_PING = 0x0B; -constexpr uint8_t CMD_SHUTDOWN = 0xFF; - -// Response status -constexpr uint32_t STATUS_OK = 0; -constexpr uint32_t STATUS_ERROR = 1; -constexpr uint32_t STATUS_UNKNOWN_CMD = 2; - -// Global shutdown flag -std::atomic g_running{true}; - -void signal_handler(int sig) { - g_running = false; -} - -// Read a little-endian uint32 from buffer -uint32_t read_u32_le(const uint8_t* p) { - return static_cast(p[0]) - | (static_cast(p[1]) << 8) - | (static_cast(p[2]) << 16) - | (static_cast(p[3]) << 24); -} - -// Read a little-endian int32 from buffer -int32_t read_i32_le(const uint8_t* p) { - return static_cast(read_u32_le(p)); -} - -// Read a little-endian float64 from buffer -double read_f64_le(const uint8_t* p) { - double val; - std::memcpy(&val, p, 8); - return val; -} - -// Read a little-endian uint16 from buffer -uint16_t read_u16_le(const uint8_t* p) { - return static_cast(p[0]) | (static_cast(p[1]) << 8); -} - -// Write a little-endian uint32 to buffer -void write_u32_le(uint8_t* p, uint32_t v) { - p[0] = v & 0xFF; - p[1] = (v >> 8) & 0xFF; - p[2] = (v >> 16) & 0xFF; - p[3] = (v >> 24) & 0xFF; -} - -// Write a little-endian int32 to buffer -void write_i32_le(uint8_t* p, int32_t v) { - write_u32_le(p, static_cast(v)); -} - -// Write a little-endian float64 to buffer -void write_f64_le(uint8_t* p, double v) { - std::memcpy(p, &v, 8); -} - -// Write a little-endian uint16 to buffer -void write_u16_le(uint8_t* p, uint16_t v) { - p[0] = v & 0xFF; - p[1] = (v >> 8) & 0xFF; -} - -// Append to response vector -template -void append_le(std::vector& out, T val) { - size_t old_size = out.size(); - out.resize(old_size + sizeof(T)); - if constexpr (sizeof(T) == 1) { - out[old_size] = static_cast(val); - } else if constexpr (sizeof(T) == 2) { - write_u16_le(&out[old_size], static_cast(val)); - } else if constexpr (sizeof(T) == 4) { - if constexpr (std::is_integral_v) { - write_i32_le(&out[old_size], static_cast(val)); - } else { - std::memcpy(&out[old_size], &val, 4); - } - } else if constexpr (sizeof(T) == 8) { - write_f64_le(&out[old_size], static_cast(val)); - } -} - -} // anonymous namespace - -int main(int argc, char* argv[]) { - // Parse arguments - const char* shm_name = "/pymc_native"; - size_t cmd_size = 16 * 1024 * 1024; // 16 MB command buffer - size_t resp_size = 16 * 1024 * 1024; // 16 MB response buffer - - for (int i = 1; i < argc; i++) { - if (std::string(argv[i]) == "--name" && i + 1 < argc) { - shm_name = argv[++i]; - } else if (std::string(argv[i]) == "--cmd-size" && i + 1 < argc) { - cmd_size = std::stoul(argv[++i]); - } else if (std::string(argv[i]) == "--resp-size" && i + 1 < argc) { - resp_size = std::stoul(argv[++i]); - } - } - - // Install signal handlers - std::signal(SIGINT, signal_handler); - std::signal(SIGTERM, signal_handler); - - fprintf(stderr, "[PYMC Native] Starting with SHM name: %s\n", shm_name); - fprintf(stderr, "[PYMC Native] Command buffer: %zu MB, Response buffer: %zu MB\n", - cmd_size / (1024*1024), resp_size / (1024*1024)); - - // Open IPC channel (C++ is the consumer: create=false) - pymc::IPCChannel channel(shm_name, cmd_size, resp_size, false); - if (!channel.is_valid()) { - fprintf(stderr, "[PYMC Native] Failed to open IPC channel\n"); - return 1; - } - - fprintf(stderr, "[PYMC Native] IPC channel opened successfully\n"); - - // Initialize engines - pymc::RedstoneEngine redstone; - pymc::LightEngine lighting; - pymc::PhysicsEngine physics; - - fprintf(stderr, "[PYMC Native] All engines initialized, entering main loop\n"); - - // Main command loop - uint8_t cmd_buffer[256 * 1024]; // 256 KB for individual commands - std::vector response; - - while (g_running) { - // Wait for a command with 100ms timeout - if (!channel.wait_for_command(100)) { - continue; // Timeout, check g_running - } - - // Read the command - size_t cmd_len = channel.recv_command(cmd_buffer, sizeof(cmd_buffer)); - if (cmd_len == 0) { - continue; - } - - const uint8_t* cmd = cmd_buffer; - uint8_t cmd_type = cmd[0]; - const uint8_t* payload = cmd + 1; - size_t payload_len = cmd_len - 1; - - response.clear(); - // Reserve space for status - response.resize(4); - - switch (cmd_type) { - case CMD_PING: { - write_u32_le(response.data(), STATUS_OK); - append_le(response, 1); // pong = 1 - break; - } - - case CMD_SHUTDOWN: { - write_u32_le(response.data(), STATUS_OK); - channel.send_response(response.data(), response.size()); - g_running = false; - continue; - } - - case CMD_TICK: { - // Process one tick for all engines - - // Redstone tick - auto redstone_updates = redstone.tick(); - - // Physics tick - auto physics_updates = physics.tick(); - - // Build response - write_u32_le(response.data(), STATUS_OK); - - // Redstone updates - append_le(response, static_cast(redstone_updates.size())); - for (const auto& upd : redstone_updates) { - append_le(response, upd.x); - append_le(response, upd.y); - append_le(response, upd.z); - append_le(response, upd.new_block_state); - append_le(response, upd.flags); - } - - // Physics updates - append_le(response, static_cast(physics_updates.size())); - for (const auto& upd : physics_updates) { - append_le(response, upd.entity_id); - append_le(response, upd.new_x); - append_le(response, upd.new_y); - append_le(response, upd.new_z); - append_le(response, upd.new_vx); - append_le(response, upd.new_vy); - append_le(response, upd.new_vz); - append_le(response, upd.on_ground ? 1 : 0); - append_le(response, upd.landed ? 1 : 0); - if (upd.landed) { - append_le(response, upd.landed_block_state); - append_le(response, upd.landed_x); - append_le(response, upd.landed_y); - append_le(response, upd.landed_z); - } - } - - break; - } - - case CMD_ADD_REDSTONE: { - // Payload: [4 x][4 y][4 z][1 type][1 facing] - if (payload_len < 10) { - write_u32_le(response.data(), STATUS_ERROR); - break; - } - int32_t x = read_i32_le(payload); - int32_t y = read_i32_le(payload + 4); - int32_t z = read_i32_le(payload + 8); - auto type = static_cast(payload[12]); - auto facing = static_cast(payload[13]); - - redstone.add_component(x, y, z, type, facing); - write_u32_le(response.data(), STATUS_OK); - break; - } - - case CMD_REMOVE_REDSTONE: { - if (payload_len < 12) { - write_u32_le(response.data(), STATUS_ERROR); - break; - } - int32_t x = read_i32_le(payload); - int32_t y = read_i32_le(payload + 4); - int32_t z = read_i32_le(payload + 8); - - redstone.remove_component(x, y, z); - write_u32_le(response.data(), STATUS_OK); - break; - } - - case CMD_SET_POWER: { - if (payload_len < 16) { - write_u32_le(response.data(), STATUS_ERROR); - break; - } - int32_t x = read_i32_le(payload); - int32_t y = read_i32_le(payload + 4); - int32_t z = read_i32_le(payload + 8); - int32_t level = read_i32_le(payload + 12); - - redstone.set_power_level(x, y, z, level); - write_u32_le(response.data(), STATUS_OK); - break; - } - - case CMD_CALC_LIGHT: { - // Payload: flat block array (98304 * 2 = 196608 bytes) - constexpr size_t expected_size = pymc::LIGHT_CHUNK_SECTIONS * 16 * 16 * 16 * 2; - if (payload_len < expected_size) { - write_u32_le(response.data(), STATUS_ERROR); - append_le(response, static_cast(payload_len)); - append_le(response, static_cast(expected_size)); - break; - } - - // Convert to uint16 array - std::vector blocks(pymc::LIGHT_CHUNK_SECTIONS * 16 * 16 * 16); - for (size_t i = 0; i < blocks.size(); i++) { - blocks[i] = read_u16_le(payload + i * 2); - } - - std::vector sky_light(pymc::LIGHT_SECTION_COUNT * 4096); - std::vector block_light(pymc::LIGHT_SECTION_COUNT * 4096); - - lighting.calculate_chunk_lighting( - blocks.data(), - sky_light.data(), - block_light.data() - ); - - write_u32_le(response.data(), STATUS_OK); - // Append sky light data - response.insert(response.end(), sky_light.begin(), sky_light.end()); - // Append block light data - response.insert(response.end(), block_light.begin(), block_light.end()); - break; - } - - case CMD_UPDATE_LIGHT: { - if (payload_len < 14) { - write_u32_le(response.data(), STATUS_ERROR); - break; - } - int32_t x = read_i32_le(payload); - int32_t y = read_i32_le(payload + 4); - int32_t z = read_i32_le(payload + 8); - uint16_t old_block = read_u16_le(payload + 12); - uint16_t new_block = read_u16_le(payload + 14); - - auto updates = lighting.update_block_light(x, y, z, old_block, new_block); - - write_u32_le(response.data(), STATUS_OK); - append_le(response, static_cast(updates.size())); - for (const auto& upd : updates) { - append_le(response, upd.x); - append_le(response, upd.y); - append_le(response, upd.z); - append_le(response, upd.new_sky_light); - append_le(response, upd.new_block_light); - } - break; - } - - case CMD_SET_ENTITY: { - // Payload: [4 entity_id][8 x][8 y][8 z][8 vx][8 vy][8 vz] - // [8 bb_min_x][8 bb_min_y][8 bb_min_z] - // [8 bb_max_x][8 bb_max_y][8 bb_max_z] - // [1 on_ground][1 has_gravity][1 is_item][1 is_falling_block] - // [2 block_state] - constexpr size_t expected = 4 + 6*8 + 6*8 + 4 + 2; - if (payload_len < expected) { - write_u32_le(response.data(), STATUS_ERROR); - break; - } - - pymc::PhysicsEntity entity; - entity.entity_id = read_i32_le(payload); - entity.x = read_f64_le(payload + 4); - entity.y = read_f64_le(payload + 12); - entity.z = read_f64_le(payload + 20); - entity.vx = read_f64_le(payload + 28); - entity.vy = read_f64_le(payload + 36); - entity.vz = read_f64_le(payload + 44); - entity.bounding_box.min_x = read_f64_le(payload + 52); - entity.bounding_box.min_y = read_f64_le(payload + 60); - entity.bounding_box.min_z = read_f64_le(payload + 68); - entity.bounding_box.max_x = read_f64_le(payload + 76); - entity.bounding_box.max_y = read_f64_le(payload + 84); - entity.bounding_box.max_z = read_f64_le(payload + 92); - entity.on_ground = payload[100] != 0; - entity.has_gravity = payload[101] != 0; - entity.is_item = payload[102] != 0; - entity.is_falling_block = payload[103] != 0; - entity.block_state = read_u16_le(payload + 104); - - physics.set_entity(entity); - write_u32_le(response.data(), STATUS_OK); - break; - } - - case CMD_REMOVE_ENTITY: { - if (payload_len < 4) { - write_u32_le(response.data(), STATUS_ERROR); - break; - } - int32_t entity_id = read_i32_le(payload); - physics.remove_entity(entity_id); - write_u32_le(response.data(), STATUS_OK); - break; - } - - case CMD_SET_BLOCKS: { - // Payload: [4 count][count * (4 x + 4 y + 4 z + 2 block_state)] - if (payload_len < 4) { - write_u32_le(response.data(), STATUS_ERROR); - break; - } - uint32_t count = read_u32_le(payload); - size_t expected = 4 + count * 14; - if (payload_len < expected) { - write_u32_le(response.data(), STATUS_ERROR); - break; - } - - std::vector blocks(count); - const uint8_t* p = payload + 4; - for (uint32_t i = 0; i < count; i++) { - blocks[i].x = read_i32_le(p); - blocks[i].y = read_i32_le(p + 4); - blocks[i].z = read_i32_le(p + 8); - blocks[i].block_state = read_u16_le(p + 12); - p += 14; - } - - physics.set_blocks(blocks); - write_u32_le(response.data(), STATUS_OK); - break; - } - - case CMD_TICK_FLUIDS: { - auto fluid_updates = physics.tick_fluids(); - - write_u32_le(response.data(), STATUS_OK); - append_le(response, static_cast(fluid_updates.size())); - for (const auto& upd : fluid_updates) { - append_le(response, upd.x); - append_le(response, upd.y); - append_le(response, upd.z); - append_le(response, upd.new_block_state); - append_le(response, upd.new_fluid_level); - } - break; - } - - default: { - write_u32_le(response.data(), STATUS_UNKNOWN_CMD); - append_le(response, cmd_type); - break; - } - } - - // Send response - if (!channel.send_response(response.data(), response.size())) { - fprintf(stderr, "[PYMC Native] Failed to send response\n"); - // If the response buffer is full, the Python side is probably stuck - // We'll continue trying - } - } - - fprintf(stderr, "[PYMC Native] Shutting down gracefully\n"); - return 0; -} diff --git a/native/redstone/redstone_engine.cpp b/native/redstone/redstone_engine.cpp deleted file mode 100755 index 354afff..0000000 --- a/native/redstone/redstone_engine.cpp +++ /dev/null @@ -1,391 +0,0 @@ -// ============================================================ -// PyMC - Redstone Engine Implementation -// High-performance redstone simulation with dirty-flag tracking -// ============================================================ - -#include "redstone_engine.h" - -#include -#include -#include - -namespace pymc { - -RedstoneEngine::RedstoneEngine() = default; -RedstoneEngine::~RedstoneEngine() = default; - -// ---- Component management ---- - -void RedstoneEngine::add_component(int x, int y, int z, ComponentType type, Facing facing) { - BlockPos pos{x, y, z}; - auto& comp = components_[pos]; - comp.pos = pos; - comp.type = type; - comp.facing = facing; - comp.power = 0; - comp.powered = false; - comp.dirty = true; - comp.delay = 1; - comp.delay_counter = 0; - comp.output_power = 0; - comp.side_input_power = 0; - comp.compare_mode = true; - comp.extended = false; - comp.detection_counter = 0; - comp.active = false; - comp.active_ticks = 0; - - dirty_set_.insert(pos); - mark_neighbors_dirty(pos); -} - -void RedstoneEngine::remove_component(int x, int y, int z) { - BlockPos pos{x, y, z}; - auto it = components_.find(pos); - if (it != components_.end()) { - mark_neighbors_dirty(pos); - components_.erase(it); - dirty_set_.erase(pos); - } -} - -void RedstoneEngine::set_power_level(int x, int y, int z, int level) { - BlockPos pos{x, y, z}; - auto it = components_.find(pos); - if (it != components_.end()) { - it->second.power = static_cast(std::clamp(level, 0, 15)); - it->second.dirty = true; - dirty_set_.insert(pos); - } -} - -int RedstoneEngine::get_power_level(int x, int y, int z) const { - BlockPos pos{x, y, z}; - auto it = components_.find(pos); - if (it != components_.end()) { - return it->second.power; - } - return 0; -} - -void RedstoneEngine::mark_dirty(int x, int y, int z) { - BlockPos pos{x, y, z}; - auto it = components_.find(pos); - if (it != components_.end()) { - it->second.dirty = true; - dirty_set_.insert(pos); - } -} - -// ---- Simulation ---- - -std::vector RedstoneEngine::tick() { - pending_updates_.clear(); - - // Process delayed updates (repeaters, etc.) - std::vector next_delayed; - for (auto& du : delayed_updates_) { - du.remaining_ticks--; - if (du.remaining_ticks <= 0) { - auto it = components_.find(du.pos); - if (it != components_.end()) { - it->second.output_power = du.target_power; - it->second.dirty = true; - dirty_set_.insert(du.pos); - } - } else { - next_delayed.push_back(du); - } - } - delayed_updates_ = std::move(next_delayed); - - // Process all dirty components using BFS-like propagation - // We iterate up to 16 times to handle cascading updates - for (int iteration = 0; iteration < 16 && !dirty_set_.empty(); iteration++) { - auto current_dirty = std::move(dirty_set_); - dirty_set_.clear(); - - for (const auto& pos : current_dirty) { - auto it = components_.find(pos); - if (it == components_.end()) continue; - - auto& comp = it->second; - comp.dirty = false; - - int old_power = comp.power; - bool old_powered = comp.powered; - - switch (comp.type) { - case ComponentType::WIRE: - update_wire(comp); - break; - case ComponentType::TORCH: - update_torch(comp); - break; - case ComponentType::REPEATER: - update_repeater(comp); - break; - case ComponentType::COMPARATOR: - update_comparator(comp); - break; - case ComponentType::PISTON: - case ComponentType::STICKY_PISTON: - update_piston(comp); - break; - case ComponentType::OBSERVER: - update_observer(comp); - break; - case ComponentType::LEVER: - case ComponentType::BUTTON: - case ComponentType::PRESSURE_PLATE: - case ComponentType::WEIGHTED_PRESSURE_PLATE: - // These are input devices; their power is set externally - if (comp.active) { - comp.powered = true; - comp.power = (comp.type == ComponentType::WEIGHTED_PRESSURE_PLATE) - ? static_cast(std::min(15, static_cast(comp.power))) : 15; - } - break; - case ComponentType::REDSTONE_BLOCK: - comp.powered = true; - comp.power = 15; - break; - default: - break; - } - - // If power state changed, propagate to neighbors - if (comp.power != old_power || comp.powered != old_powered) { - propagate_signal(comp); - } - } - } - - // Process any remaining delayed updates for buttons, etc. - for (auto& [pos, comp] : components_) { - if (comp.type == ComponentType::BUTTON && comp.active) { - comp.active_ticks--; - if (comp.active_ticks <= 0) { - comp.active = false; - comp.powered = false; - comp.power = 0; - dirty_set_.insert(pos); - mark_neighbors_dirty(pos); - } - } - if (comp.type == ComponentType::OBSERVER && comp.detection_counter > 0) { - comp.detection_counter--; - if (comp.detection_counter == 0) { - comp.powered = false; - comp.power = 0; - dirty_set_.insert(pos); - mark_neighbors_dirty(pos); - } - } - } - - return pending_updates_; -} - -// ---- Internal simulation methods ---- - -void RedstoneEngine::update_wire(RedstoneComponent& comp) { - int max_input = get_strongest_input(comp); - - // Wire power decreases by 1 per block from source - int new_power = std::max(0, max_input - 1); - - // Direct power sources override - if (comp.active) { - new_power = std::max(new_power, static_cast(comp.power)); - } - - comp.power = static_cast(std::clamp(new_power, 0, 15)); - comp.powered = comp.power > 0; -} - -void RedstoneEngine::update_torch(RedstoneComponent& comp) { - // A torch is ON when its input is OFF, and vice versa - int input_power = get_input_from_dir(comp.pos, opposite(comp.facing)); - bool input_powered = input_power > 0; - - bool should_be_on = !input_powered; - comp.powered = should_be_on; - comp.power = should_be_on ? 15 : 0; -} - -void RedstoneEngine::update_repeater(RedstoneComponent& comp) { - int input_power = get_input_from_dir(comp.pos, opposite(comp.facing)); - bool input_powered = input_power > 0; - - int target_output = input_powered ? 15 : 0; - - if (target_output != comp.output_power) { - // Schedule the output change after the delay - delayed_updates_.push_back({ - comp.pos, - static_cast(target_output), - comp.delay - }); - } - - // Current output remains until delay expires - comp.powered = comp.output_power > 0; - comp.power = comp.output_power; -} - -void RedstoneEngine::update_comparator(RedstoneComponent& comp) { - int back_input = get_input_from_dir(comp.pos, opposite(comp.facing)); - int side_a = get_input_from_dir(comp.pos, Facing::WEST); // Simplified - int side_b = get_input_from_dir(comp.pos, Facing::EAST); // Simplified - int max_side = std::max(side_a, side_b); - - int output; - if (comp.compare_mode) { - output = (back_input >= max_side) ? back_input : 0; - } else { - output = std::max(0, back_input - max_side); - } - - comp.output_power = static_cast(std::clamp(output, 0, 15)); - comp.power = comp.output_power; - comp.powered = comp.power > 0; -} - -void RedstoneEngine::update_piston(RedstoneComponent& comp) { - int input_power = get_strongest_input(comp); - bool should_extend = input_power > 0; - - if (should_extend != comp.extended) { - comp.extended = should_extend; - // Generate block update for piston extension/retraction - int dx = DIR_OFFSETS[static_cast(comp.facing)].dx; - int dy = DIR_OFFSETS[static_cast(comp.facing)].dy; - int dz = DIR_OFFSETS[static_cast(comp.facing)].dz; - - if (should_extend) { - // Push block in front of piston - add_update(comp.pos.x + dx, comp.pos.y + dy, comp.pos.z + dz, - comp.type == ComponentType::STICKY_PISTON ? -2 : -1, 0x01); - } - add_update(comp.pos.x, comp.pos.y, comp.pos.z, - should_extend ? -3 : -4, 0x02); // Piston head update - } -} - -void RedstoneEngine::update_observer(RedstoneComponent& comp) { - // Observers detect changes in the block they're facing - // Detection is handled externally (Python sends a "block changed" event) - // Here we just manage the pulse output - if (comp.powered && comp.detection_counter > 0) { - // Still in detection pulse - return; - } -} - -void RedstoneEngine::propagate_signal(RedstoneComponent& comp) { - mark_neighbors_dirty(comp.pos); - - // Generate a block state update for this component - // The actual block state encoding is handled by the Python side - add_update(comp.pos.x, comp.pos.y, comp.pos.z, - comp.powered ? 1 : 0, 0x01); -} - -int RedstoneEngine::get_strongest_input(const RedstoneComponent& comp) const { - int max_power = 0; - for (int d = 0; d < DIRECTION_COUNT; d++) { - Facing dir = ALL_DIRECTIONS[d]; - int power = get_input_from_dir(comp.pos, dir); - max_power = std::max(max_power, power); - } - return max_power; -} - -int RedstoneEngine::get_input_from_dir(const BlockPos& pos, Facing from_dir) const { - // Get the power signal coming FROM the direction `from_dir` - // That means we look at the neighbor in that direction - int d = static_cast(from_dir); - BlockPos neighbor{ - pos.x + DIR_OFFSETS[d].dx, - pos.y + DIR_OFFSETS[d].dy, - pos.z + DIR_OFFSETS[d].dz - }; - - auto it = components_.find(neighbor); - if (it == components_.end()) return 0; - - const auto& ncomp = it->second; - - // Different component types propagate differently - switch (ncomp.type) { - case ComponentType::WIRE: - return ncomp.power; - case ComponentType::TORCH: - return ncomp.powered ? 15 : 0; - case ComponentType::REPEATER: - // Repeater only outputs in its facing direction - if (ncomp.facing == from_dir) { - return ncomp.powered ? 15 : 0; - } - return 0; - case ComponentType::COMPARATOR: - // Comparator outputs in its facing direction - if (ncomp.facing == from_dir) { - return ncomp.output_power; - } - return 0; - case ComponentType::LEVER: - case ComponentType::BUTTON: - case ComponentType::PRESSURE_PLATE: - case ComponentType::WEIGHTED_PRESSURE_PLATE: - case ComponentType::DAYLIGHT_DETECTOR: - case ComponentType::REDSTONE_BLOCK: - return ncomp.powered ? 15 : 0; - default: - return 0; - } -} - -void RedstoneEngine::add_update(int x, int y, int z, int new_block_state, int flags) { - pending_updates_.push_back({x, y, z, new_block_state, flags}); -} - -void RedstoneEngine::mark_neighbors_dirty(const BlockPos& pos) { - for (int d = 0; d < DIRECTION_COUNT; d++) { - BlockPos neighbor{ - pos.x + DIR_OFFSETS[d].dx, - pos.y + DIR_OFFSETS[d].dy, - pos.z + DIR_OFFSETS[d].dz - }; - if (components_.count(neighbor)) { - auto& comp = components_.at(neighbor); - comp.dirty = true; - dirty_set_.insert(neighbor); - } - } -} - -// ---- Query ---- - -bool RedstoneEngine::has_component(int x, int y, int z) const { - return components_.count({x, y, z}) > 0; -} - -const RedstoneComponent* RedstoneEngine::get_component(int x, int y, int z) const { - auto it = components_.find({x, y, z}); - return it != components_.end() ? &it->second : nullptr; -} - -std::vector RedstoneEngine::get_pending_updates() const { - return pending_updates_; -} - -void RedstoneEngine::clear() { - components_.clear(); - dirty_set_.clear(); - pending_updates_.clear(); - delayed_updates_.clear(); -} - -} // namespace pymc diff --git a/native/redstone/redstone_engine.h b/native/redstone/redstone_engine.h deleted file mode 100755 index cde1e25..0000000 --- a/native/redstone/redstone_engine.h +++ /dev/null @@ -1,292 +0,0 @@ -// ============================================================ -// PyMC - High-Performance Redstone Simulation Engine -// -// Features: -// - Spatial hash map for O(1) component lookup -// - Dirty flag tracking: only recalculate changed components -// - BFS-based signal propagation -// - Support for all vanilla redstone components: -// wire, torch, repeater, comparator, piston, observer, -// lever, button, pressure plate, etc. -// - Parallel-safe tick processing for independent subgraphs -// ============================================================ - -#ifndef PYMC_REDSTONE_ENGINE_H -#define PYMC_REDSTONE_ENGINE_H - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace pymc { - -// ----------------------------------------------------------- -// Redstone component types -// ----------------------------------------------------------- -enum class ComponentType : uint8_t { - WIRE = 0, - TORCH = 1, - REPEATER = 2, - COMPARATOR = 3, - PISTON = 4, - STICKY_PISTON = 5, - OBSERVER = 6, - LEVER = 7, - BUTTON = 8, - PRESSURE_PLATE = 9, - WEIGHTED_PRESSURE_PLATE = 10, - TRIPWIRE_HOOK = 11, - TRIPWIRE = 12, - DAYLIGHT_DETECTOR = 13, - REDSTONE_BLOCK = 14, - TARGET = 15, - LECTERN = 16, -}; - -// Facing direction -enum class Facing : uint8_t { - DOWN = 0, - UP = 1, - NORTH = 2, - SOUTH = 3, - WEST = 4, - EAST = 5, -}; - -// 6 cardinal directions -constexpr int DIRECTION_COUNT = 6; -constexpr Facing ALL_DIRECTIONS[] = { - Facing::DOWN, Facing::UP, - Facing::NORTH, Facing::SOUTH, - Facing::WEST, Facing::EAST -}; - -// Direction offsets [dir] -> {dx, dy, dz} -struct DirectionOffset { - int dx, dy, dz; -}; - -constexpr DirectionOffset DIR_OFFSETS[] = { - {0, -1, 0}, // DOWN - {0, 1, 0}, // UP - {0, 0, -1}, // NORTH - {0, 0, 1}, // SOUTH - {-1, 0, 0}, // WEST - {1, 0, 0}, // EAST -}; - -// Get opposite facing -inline Facing opposite(Facing f) { - switch (f) { - case Facing::DOWN: return Facing::UP; - case Facing::UP: return Facing::DOWN; - case Facing::NORTH: return Facing::SOUTH; - case Facing::SOUTH: return Facing::NORTH; - case Facing::WEST: return Facing::EAST; - case Facing::EAST: return Facing::WEST; - } - return Facing::NORTH; -} - -// ----------------------------------------------------------- -// Block position key for spatial hash map -// ----------------------------------------------------------- -struct BlockPos { - int32_t x, y, z; - - bool operator==(const BlockPos& o) const { - return x == o.x && y == o.y && z == o.z; - } -}; - -struct BlockPosHash { - size_t operator()(const BlockPos& p) const { - // FNV-1a inspired hash for 3D positions - size_t h = 14695981039346656037ULL; - h ^= static_cast(p.x); - h *= 1099511628211ULL; - h ^= static_cast(p.y); - h *= 1099511628211ULL; - h ^= static_cast(p.z); - h *= 1099511628211ULL; - return h; - } -}; - -// ----------------------------------------------------------- -// Redstone component state -// ----------------------------------------------------------- -struct RedstoneComponent { - BlockPos pos; - ComponentType type; - Facing facing; - - // Signal level (0-15 for wire, 0/1 for most others) - int8_t power; - - // Is this component currently outputting power? - bool powered; - - // Is this component in a "dirty" state (needs recalculation)? - bool dirty; - - // Repeater/comparator specific - int8_t delay; // Repeater delay (1-4 ticks) - int8_t delay_counter; // Current delay countdown - int8_t output_power; // Latched output power (for repeater/comparator) - - // Comparator specific - int8_t side_input_power; // Power from side inputs - bool compare_mode; // true = compare, false = subtract - - // Piston specific - bool extended; - - // Observer specific - int8_t detection_counter; // Ticks since last detection - - // Button/lever/pressure plate - bool active; // Is the switch currently on? - int16_t active_ticks; // Remaining active ticks (for buttons) - - RedstoneComponent() - : pos{0, 0, 0} - , type(ComponentType::WIRE) - , facing(Facing::NORTH) - , power(0) - , powered(false) - , dirty(false) - , delay(1) - , delay_counter(0) - , output_power(0) - , side_input_power(0) - , compare_mode(true) - , extended(false) - , detection_counter(0) - , active(false) - , active_ticks(0) - {} -}; - -// ----------------------------------------------------------- -// Update record — sent back to Python to apply world changes -// ----------------------------------------------------------- -struct RedstoneUpdate { - int32_t x, y, z; - int32_t new_block_state; // The new block state ID to set - int32_t flags; // Update flags (notify neighbors, etc.) -}; - -// ----------------------------------------------------------- -// RedstoneEngine — main simulation class -// ----------------------------------------------------------- -class RedstoneEngine { -public: - RedstoneEngine(); - ~RedstoneEngine(); - - // ---- Component management ---- - - // Add a redstone component at the given position. - void add_component(int x, int y, int z, ComponentType type, Facing facing = Facing::NORTH); - - // Remove a component. - void remove_component(int x, int y, int z); - - // Set the power level of a component directly (e.g., from a lever). - void set_power_level(int x, int y, int z, int level); - - // Get the current power level. - int get_power_level(int x, int y, int z) const; - - // Mark a component as needing recalculation. - void mark_dirty(int x, int y, int z); - - // ---- Simulation ---- - - // Process one redstone tick. - // Returns the list of block state updates to apply. - std::vector tick(); - - // ---- Query ---- - - // Check if a position has a redstone component. - bool has_component(int x, int y, int z) const; - - // Get component at position (nullptr if none). - const RedstoneComponent* get_component(int x, int y, int z) const; - - // Get all pending updates since last tick. - std::vector get_pending_updates() const; - - // Get the number of active components. - size_t component_count() const { return components_.size(); } - - // Clear all components. - void clear(); - -private: - // Spatial hash map of all redstone components - std::unordered_map components_; - - // Set of positions that need recalculation this tick - std::unordered_set dirty_set_; - - // Pending block state updates - std::vector pending_updates_; - - // ---- Internal simulation methods ---- - - // Calculate the power output of a component - int calculate_output_power(RedstoneComponent& comp); - - // Propagate signal from a component to its neighbors - void propagate_signal(RedstoneComponent& comp); - - // Update a wire component's power based on neighbors - void update_wire(RedstoneComponent& comp); - - // Update a torch component - void update_torch(RedstoneComponent& comp); - - // Update a repeater component - void update_repeater(RedstoneComponent& comp); - - // Update a comparator component - void update_comparator(RedstoneComponent& comp); - - // Update a piston component - void update_piston(RedstoneComponent& comp); - - // Update an observer component - void update_observer(RedstoneComponent& comp); - - // Get the strongest signal a component can receive from its neighbors - int get_strongest_input(const RedstoneComponent& comp) const; - - // Get directional input power - int get_input_from_dir(const BlockPos& pos, Facing from_dir) const; - - // Add an update to the pending list - void add_update(int x, int y, int z, int new_block_state, int flags = 0); - - // Mark neighbors as dirty - void mark_neighbors_dirty(const BlockPos& pos); - - // Schedule a delayed update (for repeaters/comparators) - struct DelayedUpdate { - BlockPos pos; - int8_t target_power; - int8_t remaining_ticks; - }; - std::vector delayed_updates_; -}; - -} // namespace pymc - -#endif // PYMC_REDSTONE_ENGINE_H diff --git a/native/vanilla/api.cpp b/native/vanilla/api.cpp index 00b762a..a31ad6e 100644 --- a/native/vanilla/api.cpp +++ b/native/vanilla/api.cpp @@ -4,6 +4,8 @@ // redstone / block updates (BUD, QC, pistons, ...) -> vrs_tick, vrs_block_changed, ... // hoppers -> vrs_tick_hoppers // explosions (rays + exposure, thread safe) -> vrs_explosion_blocks, vrs_exposure +// chunk light (sky + block, no engine state) -> vrs_light_set_tables, vrs_light_compute +// biomes (noise + rules, no engine state) -> vrs_biome_create, vrs_biome_sections // // The engine keeps a mirror of the chunks it reads (loaded through a // callback); every change it makes is logged and drained by Python, which @@ -14,6 +16,8 @@ #include "behaviors.h" #include "hopper.h" +#include "light.h" +#include "biome.h" #if defined(_WIN32) #define VRS_API extern "C" __declspec(dllexport) @@ -31,7 +35,70 @@ static std::recursive_mutex M; static Pos P(int x, int y, int z) { return Pos{x, y, z}; } -VRS_API int vrs_version() { return 3; } +VRS_API int vrs_version() { return 6; } + +// Light: opacity/emission tables by state id (set once), then one call per chunk. +VRS_API void vrs_light_set_tables(const uint8_t* opacity, const uint8_t* emission, int n) { + vrs::light::set_tables(opacity, emission, n); +} +VRS_API void vrs_light_compute(const uint16_t* blocks, int height, uint8_t* sky, uint8_t* block_light) { + vrs::light::compute(blocks, height, sky, block_light); +} + +// Biomes: noise tables for the seven samplers, built in Python (same random generator), +// laid out as [count, persistence, lacunarity, max_value, count x (xo, yo, zo, perm[512])] +// per sampler in the order temperature, humidity, continental, erosion, weirdness, +// swamp, mushroom. names: the biome names joined by '\n', in id order. +VRS_API void* vrs_biome_create(const double* params, int n, const char* names) { + using namespace vrs::biome; + Sampler* s = new Sampler(); + Octaves* sets[7] = {&s->temperature, &s->humidity, &s->continental, &s->erosion, + &s->weirdness, &s->swamp, &s->mushroom}; + int pos = 0; + for (Octaves* o : sets) { + o->count = (int)params[pos]; + o->persistence = params[pos + 1]; + o->lacunarity = params[pos + 2]; + o->max_value = params[pos + 3]; + pos += 4; + o->layers.resize(o->count); + for (Layer& layer : o->layers) { + layer.xo = params[pos]; + layer.yo = params[pos + 1]; + layer.zo = params[pos + 2]; + pos += 3; + for (int i = 0; i < 512; i++) layer.perm[i] = (int)params[pos + i]; + pos += 512; + } + } + if (pos != n) { delete s; return nullptr; } + int index = 0; + const char* p = names; + while (*p) { + const char* end = std::strchr(p, '\n'); + std::string name = end ? std::string(p, end - p) : std::string(p); + s->ids[name] = index++; + if (!end) break; + p = end + 1; + } + return s; +} + +VRS_API void vrs_biome_destroy(void* handle) { delete static_cast(handle); } + +// column_height: 256 entries (x + z*16), index of the highest non-air block + 1, 0 if none. +// out: 24 sections x 64 biome ids (section-major, then y, z, x in 4x4x4 cells). +VRS_API int vrs_biome_sections(void* handle, int chunk_x, int chunk_z, + const int32_t* column_height, int32_t* out) { + if (handle == nullptr) return 0; + vrs::biome::build_sections(*static_cast(handle), chunk_x, chunk_z, + column_height, out); + return 1; +} + +// Chunks kept in the mirror. Every chunk is 196 KB; the rest are re-read from storage on demand. +static size_t g_chunk_limit = 256; +VRS_API void vrs_set_chunk_limit(int n) { LOCK; g_chunk_limit = n < 1 ? 1 : (size_t)n; } VRS_API int vrs_init(const char* blocks_json) { LOCK; @@ -101,7 +168,13 @@ static int guarded(const std::function& fn) { } } -VRS_API int vrs_tick() { LOCK; return guarded([] { G->tick_all(); }); } +VRS_API int vrs_tick() { + LOCK; + return guarded([] { + G->tick_all(); + G->evict(g_chunk_limit); // no pointers into the mirror are held between ticks + }); +} VRS_API int vrs_tick_hoppers(const int32_t* xyz, int n) { LOCK; diff --git a/native/vanilla/biome.h b/native/vanilla/biome.h new file mode 100644 index 0000000..de3cfd2 --- /dev/null +++ b/native/vanilla/biome.h @@ -0,0 +1,237 @@ +// ============================================================ +// PyMC - biome sampling, native port of world/biomes.py +// +// The noise tables (permutations and offsets) are built in Python with the same +// random generator as world/noise.py and passed in, so the octave noise here +// evaluates the same double-precision operations in the same order. Build with +// -ffp-contract=off so no fused multiply-add changes the results +// (tests/test_biome_native.py compares every biome with the Python sampler). +// ============================================================ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace vrs::biome { + +constexpr int MIN_Y = -64; +constexpr int SEA_LEVEL = 63; +constexpr int SECTIONS = 24; +constexpr int SAMPLES_PER_SECTION = 64; // 4 x 4 x 4 biome cells + +struct Layer { + double xo, yo, zo; + int perm[512]; +}; + +struct Octaves { + int count = 0; + double persistence = 0.5, lacunarity = 2.0, max_value = 1.0; + std::vector layers; + + static inline double fade(double t) { return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); } + static inline double lerp(double t, double a, double b) { return a + t * (b - a); } + static inline double grad(int hash, double x, double y, double z) { + int h = hash & 15; + double u = h < 8 ? x : y; + double v; + if (h < 4) v = y; + else if (h == 12 || h == 14) v = x; + else v = z; + return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v); + } + + // ImprovedNoise.noise2d(x, z) = noise(x, 0, z) + static double layer_noise(const Layer& layer, double x, double z) { + x = x + layer.xo; + double y = 0.0 + layer.yo; + z = z + layer.zo; + const int64_t fx = (int64_t)std::floor(x), fy = (int64_t)std::floor(y), fz = (int64_t)std::floor(z); + const int xi = (int)(fx & 255), yi = (int)(fy & 255), zi = (int)(fz & 255); + const double xf = x - (double)fx, yf = y - (double)fy, zf = z - (double)fz; + const double u = fade(xf), v = fade(yf), w = fade(zf); + const int* p = layer.perm; + const int a = p[xi] + yi; + const int aa = p[a] + zi; + const int ab = p[a + 1] + zi; + const int b = p[xi + 1] + yi; + const int ba = p[b] + zi; + const int bb = p[b + 1] + zi; + return lerp(w, + lerp(v, + lerp(u, grad(p[aa], xf, yf, zf), grad(p[ba], xf - 1, yf, zf)), + lerp(u, grad(p[ab], xf, yf - 1, zf), grad(p[bb], xf - 1, yf - 1, zf))), + lerp(v, + lerp(u, grad(p[aa + 1], xf, yf, zf - 1), grad(p[ba + 1], xf - 1, yf, zf - 1)), + lerp(u, grad(p[ab + 1], xf, yf - 1, zf - 1), grad(p[bb + 1], xf - 1, yf - 1, zf - 1)))); + } + + double sample(double x, double z) const { + double total = 0.0, amplitude = 1.0, frequency = 1.0; + for (const Layer& layer : layers) { + total += layer_noise(layer, x * frequency, z * frequency) * amplitude; + amplitude *= persistence; + frequency *= lacunarity; + } + return total / max_value; + } +}; + +struct Sampler { + Octaves temperature, humidity, continental, erosion, weirdness, swamp, mushroom; + std::unordered_map ids; + + int id(const char* name) const { return ids.at(name); } + + struct Climate { double temperature, humidity, continental, erosion, weirdness; }; + + Climate climate(int64_t wx, int64_t wz) const { + return { + temperature.sample((double)wx / 512.0, (double)wz / 512.0), + humidity.sample((double)wx / 384.0, (double)wz / 384.0), + continental.sample((double)wx / 768.0, (double)wz / 768.0), + erosion.sample((double)wx / 256.0, (double)wz / 256.0), + weirdness.sample((double)wx / 192.0, (double)wz / 192.0), + }; + } + + // Port of BiomeSampler.sample_surface_biome; returns the biome id. + int surface(int64_t wx, int64_t wz, int surface_height) const { + const Climate c = climate(wx, wz); + const double swampiness = swamp.sample((double)wx / 160.0, (double)wz / 160.0); + const double mushroom_v = mushroom.sample((double)wx / 2048.0, (double)wz / 2048.0); + const double temp = c.temperature, humid = c.humidity, cont = c.continental; + const double eros = c.erosion, weird = c.weirdness; + const bool deep = surface_height < SEA_LEVEL - 10; + + if (mushroom_v > 0.82 && cont < -0.15) return id("minecraft:mushroom_fields"); + + if (cont < -0.55) { + if (temp < -0.45) return id(deep ? "minecraft:deep_frozen_ocean" : "minecraft:frozen_ocean"); + if (temp < -0.05) return id(deep ? "minecraft:deep_cold_ocean" : "minecraft:cold_ocean"); + if (temp > 0.65) return id(humid > 0.35 ? "minecraft:warm_ocean" : "minecraft:lukewarm_ocean"); + return id(deep ? "minecraft:deep_ocean" : "minecraft:ocean"); + } + + if (cont < -0.42) { + if (temp < -0.25) return id("minecraft:frozen_river"); + return id("minecraft:river"); + } + + if (surface_height <= SEA_LEVEL + 2) { + if (temp < -0.3) return id("minecraft:snowy_beach"); + if (eros < -0.35) return id("minecraft:stony_shore"); + return id("minecraft:beach"); + } + + if (surface_height > 140 || (surface_height > 118 && weird > 0.55)) { + if (temp < -0.45) return id(weird > 0.15 ? "minecraft:jagged_peaks" : "minecraft:frozen_peaks"); + if (temp < -0.1) return id(humid > 0.0 ? "minecraft:snowy_slopes" : "minecraft:grove"); + return id("minecraft:stony_peaks"); + } + + if (surface_height > 110) { + if (temp < -0.2) return id("minecraft:grove"); + return id("minecraft:meadow"); + } + + if (temp > 0.8 && humid < -0.05) { + if (weird > 0.35) return id("minecraft:eroded_badlands"); + if (eros < -0.15) return id("minecraft:wooded_badlands"); + if (humid < -0.3) return id("minecraft:desert"); + return id("minecraft:badlands"); + } + + if (temp > 0.7 && humid > 0.3) { + if (humid > 0.65 && weird > 0.2) return id("minecraft:bamboo_jungle"); + if (humid > 0.5) return id("minecraft:jungle"); + return id("minecraft:sparse_jungle"); + } + + if (0.35 < temp && temp <= 0.8 && humid > 0.35 && surface_height <= SEA_LEVEL + 12) { + return id(swampiness > 0.25 ? "minecraft:mangrove_swamp" : "minecraft:swamp"); + } + + if (temp > 0.45 && humid < 0.15) { + if (weird > 0.45) return id("minecraft:windswept_savanna"); + if (surface_height > 88) return id("minecraft:savanna_plateau"); + return id("minecraft:savanna"); + } + + if (temp < -0.45) { + if (weird > 0.55) return id("minecraft:ice_spikes"); + if (humid > 0.0) return id("minecraft:snowy_taiga"); + return id("minecraft:snowy_plains"); + } + + if (humid < -0.35) { + if (weird > 0.45) return id("minecraft:windswept_gravelly_hills"); + if (weird > 0.15 || surface_height > 90) return id("minecraft:windswept_hills"); + return id("minecraft:plains"); + } + + if (humid > 0.55) { + if (surface_height > 88 && weird > 0.15) return id("minecraft:old_growth_spruce_taiga"); + if (temp < 0.35) return id("minecraft:taiga"); + if (weird > 0.45) return id("minecraft:dark_forest"); + return id("minecraft:forest"); + } + + if (0.45 < humid && humid <= 0.55) { + if (weird > 0.55) return id("minecraft:flower_forest"); + if (weird > 0.25) return id("minecraft:birch_forest"); + return id("minecraft:forest"); + } + + if (0.2 < humid && humid <= 0.45) { + if (surface_height > 95 && weird > 0.35) return id("minecraft:old_growth_birch_forest"); + if (temp < 0.35) return id("minecraft:old_growth_pine_taiga"); + if (weird > 0.5) return id("minecraft:cherry_grove"); + return id("minecraft:plains"); + } + + return id(weird > 0.6 ? "minecraft:sunflower_plains" : "minecraft:plains"); + } + + // Port of BiomeSampler.sample_biome (surface biome plus caves). + int sample(int64_t wx, int wy, int64_t wz, int surface_height) const { + const int surface_id = surface(wx, wz, surface_height); + const Climate c = climate(wx, wz); + const int depth = surface_height - wy; + if (wy < -48 && depth > 16 && c.continental > 0.15 && c.erosion < -0.05) return id("minecraft:deep_dark"); + if (wy < 40 && depth > 12) { + if (c.humidity > 0.35 && c.temperature > 0.0) return id("minecraft:lush_caves"); + if (c.humidity < -0.15 && c.weirdness > 0.0) return id("minecraft:dripstone_caves"); + } + return surface_id; + } +}; + +// Surface heights of the 16x16 columns (index x + z*16), from column_heights: +// the index of the highest non-air block + 1, or 0 when the column is empty. +inline void build_sections(const Sampler& s, int chunk_x, int chunk_z, + const int32_t* column_height, int32_t* out) { + const int64_t base_x = (int64_t)chunk_x * 16, base_z = (int64_t)chunk_z * 16; + for (int section = 0; section < SECTIONS; section++) { + int32_t* dst = out + section * SAMPLES_PER_SECTION; + int k = 0; + for (int local_y = 0; local_y < 4; local_y++) { + for (int bz = 0; bz < 4; bz++) { + for (int bx = 0; bx < 4; bx++, k++) { + const int sample_x = bx * 4 + 2, sample_z = bz * 4 + 2; + const int64_t wx = base_x + sample_x, wz = base_z + sample_z; + const int wy = MIN_Y + section * 16 + local_y * 4 + 2; + const int h = column_height[sample_x + sample_z * 16]; + const int surface_height = h > 0 ? h - 1 + MIN_Y : MIN_Y; + dst[k] = s.sample(wx, wy, wz, surface_height); + } + } + } + } +} + +} // namespace vrs::biome diff --git a/native/vanilla/light.h b/native/vanilla/light.h new file mode 100644 index 0000000..295985d --- /dev/null +++ b/native/vanilla/light.h @@ -0,0 +1,159 @@ +// ============================================================ +// PyMC - per-chunk light (sky + block), native port of world/lighting.py +// +// The algorithm is the one world/lighting.py describes: direct sky light +// column by column, sideways spread from the columns whose light stops +// higher up, then block light from every emitting block. Both spreads are +// FIFO flood fills that re-queue a cell whenever its level improves, so the +// result is the same as the Python version (tests/test_light_native.py +// compares the two on random and generated chunks). +// +// Blocks are a flat [y][z][x] array of state ids: index = y*256 + z*16 + x. +// ============================================================ +#pragma once + +#include +#include +#include +#include +#include + +namespace vrs::light { + +constexpr int LAYER = 256; + +struct Tables { + std::vector opacity; // by state id; states past the end count as 15 + std::vector emission; // by state id +}; + +inline Tables& tables() { + static Tables t; + return t; +} + +// Set once at start-up (before any compute call runs). +inline void set_tables(const uint8_t* opacity, const uint8_t* emission, int n) { + Tables& t = tables(); + t.opacity.assign(opacity, opacity + n); + t.emission.assign(emission, emission + n); +} + +inline int opacity_of(uint16_t state) { + const auto& op = tables().opacity; + return state < op.size() ? op[state] : 15; +} + +inline int emission_of(uint16_t state) { + const auto& em = tables().emission; + return state < em.size() ? em[state] : 0; +} + +using Queue = std::deque>; + +// Flood fill from the queued cells (x, y, z); a neighbour loses max(1, opacity). +inline void spread(uint8_t* light, Queue& queue, const uint16_t* blocks, int height) { + static const int D[6][3] = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; + while (!queue.empty()) { + const auto cell = queue.front(); + queue.pop_front(); + const int x = cell[0], y = cell[1], z = cell[2]; + const int level = light[y * LAYER + z * 16 + x]; + if (level <= 1) continue; + for (const auto& d : D) { + const int nx = x + d[0], ny = y + d[1], nz = z + d[2]; + if (nx < 0 || nx > 15 || nz < 0 || nz > 15 || ny < 0 || ny >= height) continue; + const int index = ny * LAYER + nz * 16 + nx; + const int cost = opacity_of(blocks[index]); + const int new_level = level - (cost > 1 ? cost : 1); + if (new_level <= 0) continue; + if (light[index] < new_level) { + light[index] = (uint8_t)new_level; + queue.push_back({nx, ny, nz}); + } + } + } +} + +// blocks: height*256 state ids. sky and block_light: height*256 levels each (overwritten). +inline void compute(const uint16_t* blocks, int height, uint8_t* sky, uint8_t* block_light) { + const size_t total = (size_t)height * LAYER; + std::memset(sky, 0, total); + std::memset(block_light, 0, total); + if (height <= 0) return; + + // Highest layer that contains anything: everything above is open sky. + int top = height - 1; + while (top >= 0) { + bool any = false; + const uint16_t* layer = blocks + top * LAYER; + for (int i = 0; i < LAYER && !any; i++) any = layer[i] != 0; + if (any) break; + top--; + } + for (size_t i = (size_t)(top + 1) * LAYER; i < total; i++) sky[i] = 15; + + // --- direct sky light, column by column --- + int floors[16][16] = {}; // lowest layer still at level 15, per (z, x) + Queue queue; + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + int level = 15; + bool broke = false; + const int offset = z * 16 + x; + for (int y = top; y >= 0; y--) { + const int cost = opacity_of(blocks[y * LAYER + offset]); + if (level == 15) { + if (cost) { + level -= cost; + floors[z][x] = y + 1; + if (level <= 0) { broke = true; break; } + sky[y * LAYER + offset] = (uint8_t)level; + queue.push_back({x, y, z}); + } else { + sky[y * LAYER + offset] = 15; + } + } else { + level -= cost > 1 ? cost : 1; + if (level <= 0) { broke = true; break; } + sky[y * LAYER + offset] = (uint8_t)level; + queue.push_back({x, y, z}); + } + } + if (!broke) floors[z][x] = 0; + } + } + + // --- sideways spread: cells below the highest neighbouring column's floor --- + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + const int floor = floors[z][x]; + int highest = floor; + if (x > 0 && floors[z][x - 1] > highest) highest = floors[z][x - 1]; + if (x < 15 && floors[z][x + 1] > highest) highest = floors[z][x + 1]; + if (z > 0 && floors[z - 1][x] > highest) highest = floors[z - 1][x]; + if (z < 15 && floors[z + 1][x] > highest) highest = floors[z + 1][x]; + const int stop = highest < top + 1 ? highest : top + 1; + for (int y = floor; y < stop; y++) queue.push_back({x, y, z}); + } + } + spread(sky, queue, blocks, height); + + // --- block light --- + queue.clear(); + for (int y = 0; y <= top; y++) { + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + const uint16_t state = blocks[y * LAYER + z * 16 + x]; + const int emit = emission_of(state); + if (emit > 0) { + block_light[y * LAYER + z * 16 + x] = (uint8_t)emit; + queue.push_back({x, y, z}); + } + } + } + } + if (!queue.empty()) spread(block_light, queue, blocks, height); +} + +} // namespace vrs::light diff --git a/network/managers/metrics.py b/network/managers/metrics.py index 12985b2..738bbf7 100755 --- a/network/managers/metrics.py +++ b/network/managers/metrics.py @@ -14,9 +14,7 @@ """ import time -import os import logging -from typing import Optional logger = logging.getLogger("PyMC.指标") @@ -75,17 +73,6 @@ def __init__(self, window_seconds: float = 60.0): self._total_generated: int = 0 self._total_loaded: int = 0 - def record_generation(self, count: int, loaded: int): - """记录一次区块生成。""" - now = time.time() - self._records.append((now, count)) - self._total_generated += count - loaded - self._total_loaded += loaded - - # 清理过期记录 - cutoff = now - self._window_seconds - self._records = [(t, c) for t, c in self._records if t > cutoff] - @property def chunks_per_second(self) -> float: """最近窗口内的平均每秒区块生成数。""" @@ -159,11 +146,6 @@ def current_rss(self) -> int: return self._samples[-1][1] return 0 - @property - def peak_rss(self) -> int: - """峰值 RSS 内存使用 (字节)。""" - return self._peak_rss - @property def current_rss_mb(self) -> float: """当前 RSS 内存使用 (MB)。""" @@ -187,16 +169,6 @@ def __init__(self): self._packets_received: int = 0 self._start_time: float = time.time() - def record_send(self, byte_count: int, packet_count: int = 1): - """记录发送数据。""" - self._bytes_sent += byte_count - self._packets_sent += packet_count - - def record_receive(self, byte_count: int, packet_count: int = 1): - """记录接收数据。""" - self._bytes_received += byte_count - self._packets_received += packet_count - @property def bytes_sent(self) -> int: return self._bytes_sent diff --git a/network/managers/protocol.py b/network/managers/protocol.py index 4a5ae0c..8dcd43f 100755 --- a/network/managers/protocol.py +++ b/network/managers/protocol.py @@ -12,12 +12,8 @@ - MovementRateLimiter: 移动更新速率限制 """ -import time import logging -from collections import deque -from typing import Optional -from protocol.packet import pack_packet logger = logging.getLogger("PyMC.协议优化") @@ -38,31 +34,6 @@ def __init__(self, max_size: int = 256): self._hits: int = 0 self._misses: int = 0 - def get_or_encode(self, packet_id: int, payload: bytes, - compression_threshold: int) -> bytes: - """ - 获取缓存的数据包帧,或编码并缓存。 - """ - key = (packet_id, payload, compression_threshold) - cached = self._cache.get(key) - if cached is not None: - self._hits += 1 - return cached - - # 编码并缓存 - frame = pack_packet(packet_id, payload, compression_threshold) - self._misses += 1 - - # 如果缓存已满,清除最旧的条目 - if len(self._cache) >= self._max_size: - # 简单策略: 清除一半 - keys = list(self._cache.keys()) - for k in keys[:len(keys) // 2]: - del self._cache[k] - - self._cache[key] = frame - return frame - def invalidate(self, packet_id: int | None = None): """ 使缓存失效。 @@ -75,14 +46,6 @@ def invalidate(self, packet_id: int | None = None): for k in keys_to_remove: del self._cache[k] - @property - def hit_rate(self) -> float: - """缓存命中率。""" - total = self._hits + self._misses - if total == 0: - return 0.0 - return self._hits / total - @property def size(self) -> int: """缓存条目数。""" @@ -114,16 +77,6 @@ def pending_count(self) -> int: """待发送数据包数量。""" return self._pending_count - @property - def pending_bytes(self) -> int: - """待发送字节数。""" - return len(self._buffer) - - @property - def should_flush(self) -> bool: - """判断是否应该刷新缓冲区。""" - return len(self._buffer) >= self._max_batch_size or self._pending_count > 0 - def flush(self) -> bytes: """ 获取并清空缓冲区。 @@ -163,48 +116,3 @@ def __init__(self, min_interval_ticks: int = 1, max_packets_per_window: int = 4, self._total_processed: int = 0 self._total_dropped: int = 0 - def should_process(self, current_tick: float) -> bool: - """ - 判断当前移动数据包是否应该处理。 - - 参数: - current_tick: 当前 tick 时间戳 - - 返回: - True 表示应该处理,False 表示应该跳过 - """ - # 检查窗口重置 - if current_tick - self._window_start >= self._window_ticks: - self._window_start = current_tick - self._window_count = 0 - - # 检查最小间隔 - if current_tick - self._last_processed < self._min_interval: - self._total_dropped += 1 - return False - - # 检查窗口内最大数量 - if self._window_count >= self._max_per_window: - self._total_dropped += 1 - return False - - self._last_processed = current_tick - self._window_count += 1 - self._total_processed += 1 - return True - - @property - def drop_rate(self) -> float: - """丢弃率。""" - total = self._total_processed + self._total_dropped - if total == 0: - return 0.0 - return self._total_dropped / total - - @property - def total_processed(self) -> int: - return self._total_processed - - @property - def total_dropped(self) -> int: - return self._total_dropped diff --git a/network/managers/scheduler.py b/network/managers/scheduler.py index 5b96916..86808b9 100755 --- a/network/managers/scheduler.py +++ b/network/managers/scheduler.py @@ -11,9 +11,8 @@ 这个调度器提供了基于 tick 数而非真实时间的调度机制。 """ -import asyncio import logging -from typing import Callable, Any +from typing import Callable logger = logging.getLogger("PyMC.调度器") diff --git a/network/managers/time.py b/network/managers/time.py index 1d9dd73..31b5211 100755 --- a/network/managers/time.py +++ b/network/managers/time.py @@ -174,22 +174,10 @@ def add_time(self, ticks: int) -> int: self._day_time = max(0, self._day_time + int(ticks)) return self.time - def get_day_time(self) -> float: - """获取以小时表示的游戏时间。""" - return (self.time / MAX_TIME) * 24.0 - def get_day_count(self) -> int: """获取当前是第几天。""" return self._day_time // MAX_TIME - def is_daytime(self) -> bool: - """判断是否为白天。""" - return 0 <= self.time < 12000 or self.time >= 23000 - - def is_nighttime(self) -> bool: - """判断是否为夜晚。""" - return 12000 <= self.time < 23000 - def set_weather(self, weather: str, duration: int = 0): """ 设置天气。 diff --git a/network/server.py b/network/server.py index 83f7e17..68de967 100755 --- a/network/server.py +++ b/network/server.py @@ -11,7 +11,6 @@ from typing import Optional from config import save_config from admin.permissions import PermissionManager, UserCache -from admin.web import WebAdminServer from .connection import Connection, ConnectionState from handlers.handshake import handle_handshake from handlers.status import handle_status @@ -27,15 +26,14 @@ from world.entities import EntityManager from world.redstone import RedstoneEngine from world.vanilla_terrain import VanillaTerrainGenerator -from world.inventory import PlayerInventory -from world.block_behavior import ContainerManager, container_manager +from world.block_behavior import container_manager from world.fluids import FluidSystem from watchdog import WatchdogManager, PlayerNetworkOptimizer from .managers.gamerule import GameruleManager from .managers.time import TimeManager from .managers.scheduler import TickScheduler from .managers.metrics import ServerMetrics -from .managers.protocol import PacketCache, PacketBatcher +from .managers.protocol import PacketCache logger = logging.getLogger("PyMC.服务器") mc_logger = logging.getLogger("minecraft.server") @@ -106,7 +104,8 @@ def __init__(self, config: dict, config_path: str = "server.properties"): self.level_name = world_name world_path = os.path.join(universe, world_name) if universe else world_name self.world_storage = WorldStorage( - world_path, region_format=str(config.get("region-file-format", "anvil"))) + world_path, region_format=str(config.get("region-file-format", "anvil")), + decoded_cache_size=config.get("chunk-decode-cache", None)) self.session_lock = SessionLock(self.world_storage.world_dir) # level.dat: 出生点、世界时间、天气、游戏规则、种子 @@ -151,7 +150,6 @@ def __init__(self, config: dict, config_path: str = "server.properties"): whitelist["enabled"] = bool(config.get("white-list", False)) self.permissions.on_whitelist_toggle = self._on_whitelist_toggle - self.web_admin: WebAdminServer | None = None self.rcon = None self.loop: asyncio.AbstractEventLoop | None = None @@ -305,13 +303,6 @@ def find_player(self, username: str) -> Connection | None: return conn return None - def broadcast_packet(self, packet_id: int, payload: bytes, - exclude: Connection = None): - """向所有在线玩家广播数据包。""" - for conn in self.get_online_players(): - if conn != exclude: - asyncio.ensure_future(conn.send_packet(packet_id, payload)) - def broadcast_system_message(self, text, exclude: Connection = None, log: bool = False): """向所有在线玩家广播系统聊天消息 (字符串或文本组件)。""" @@ -392,6 +383,8 @@ def save_player_state(self, conn: Connection): player_data["inventory"] = conn.inventory_obj.serialize_full() self.world_storage.save_player_data(str(conn.uuid), player_data) + from world.advancements import save as save_advancements + save_advancements(self, conn) def save_all_player_states(self): """保存所有在线玩家存档。""" @@ -463,6 +456,8 @@ async def start(self): self.world_storage.initialize() container_manager.load(str(self.world_storage.world_dir)) container_manager.block_reader = self.get_block_at # double chests read their block states + from world.enchanting_window import set_too_expensive_limit + set_too_expensive_limit(self.config.get("anvil-too-expensive-limit", True)) from world.minecart import load_minecarts load_minecarts(self, self.world_storage.world_dir) self._initialize_terrain_generator() @@ -505,19 +500,6 @@ async def start(self): # 启动游戏循环 (20 TPS) self._tick_task = asyncio.create_task(self._game_loop()) - if self.config.get("web-admin-enabled", True): - try: - self.web_admin = WebAdminServer( - self, - self.config.get("web-admin-host", "127.0.0.1"), - self.config.get("web-admin-port", 25568), - self.config.get("web-admin-allow-remote", False), - ) - self.web_admin.start() - except Exception as e: - logger.error(f"启动 Web 管理台失败: {e}") - self.web_admin = None - if self.config.get("enable-rcon", False): from network.rcon import RconServer password = str(self.config.get("rcon.password", "") or "") @@ -973,10 +955,6 @@ async def stop(self): self.world_storage.close() mc_logger.info(f"ThreadedAnvilChunkStorage ({self.level_name}): All chunks are saved") - if self.web_admin: - self.web_admin.stop() - self.web_admin = None - if self._chunk_executor: self._chunk_executor.shutdown(wait=False, cancel_futures=True) self._chunk_executor = None @@ -1152,6 +1130,15 @@ async def _run_tick(self, tick_count: int, keepalive_interval: int, # Process active furnace-like containers. from world.block_behavior import container_manager container_manager.tick_furnaces(self) + from world.block_behavior import tick_brewing_stands + from handlers.play.blocks import _broadcast_block_changes + brew_changes = tick_brewing_stands(self) + if brew_changes: + await _broadcast_block_changes(self, brew_changes) + + # 进度: 背包里已有的物品授予对应的进度 + from world.advancements import tick as tick_advancements + await tick_advancements(self, tick_count) # 发送 KeepAlive 心跳 if tick_count % keepalive_interval == 0: @@ -1181,8 +1168,10 @@ async def _run_tick(self, tick_count: int, keepalive_interval: int, from handlers.play.entities import sync_minecarts await sync_minecarts(self) await self._process_world_effects() - if self.gamerules.get("doMobSpawning", True) and tick_count % 200 == 0: - self.entity_manager.spawn_natural_mobs() + if self.gamerules.get("doMobSpawning", True): + from world.spawning import run_despawning, run_spawning + run_spawning(self, tick_count) + run_despawning(self, tick_count) await self._tick_entity_interactions() if tick_count % 10 == 0: await self._tick_entity_sync() @@ -1476,7 +1465,6 @@ async def _tick_entity_interactions(self): _add_player_experience, _damage_player, _send_collect_entity, - send_system_message, ) players = self.get_online_players() diff --git a/plugins/__init__.py b/plugins/__init__.py index 68536c9..1e1651e 100755 --- a/plugins/__init__.py +++ b/plugins/__init__.py @@ -180,13 +180,6 @@ class PluginInfo: package_path: str = "" extra: Dict[str, Any] = field(default_factory=dict) - def has_hard_dep(self, plugin_id: str) -> bool: - return plugin_id in self.depend - - def has_soft_dep(self, plugin_id: str) -> bool: - return plugin_id in self.softdepend - - # =========================================================== # PyMCServer - Server interface available to plugins # =========================================================== @@ -232,10 +225,6 @@ def get_tps(self) -> float: """Get current server TPS (ticks per second). 20.0 = ideal.""" return self._tps - def get_world(self, name: str) -> Optional[Dict]: - """Get world info by name.""" - return self._worlds.get(name) - def get_world_names(self) -> List[str]: """Get names of loaded worlds.""" return list(self._worlds.keys()) @@ -310,10 +299,6 @@ def __init__(self): self._event_handlers: List[tuple] = [] # (event_name, handler, priority) self._commands: Dict[str, Callable] = {} - @property - def plugin_info(self) -> PluginInfo: - return self._plugin_info - # --- Lifecycle methods (override in subclass) --- def on_load(self): @@ -340,10 +325,6 @@ def get_logger(self) -> logging.Logger: return logging.getLogger(f"pymc.plugins.{self._plugin_info.plugin_id}") return logger - def get_config(self) -> Dict[str, Any]: - """Get this plugin's configuration.""" - return self._config - # --- Registration API --- def register_command(self, name: str, handler: Callable[[str], None]): @@ -363,12 +344,6 @@ def register_event_handler(self, event_name: str, event_name, handler, priority, self._plugin_info.plugin_id ) - def register_listener(self, event_name: str, - handler: Callable[[PluginEvent], None]): - """Convenience: register at NORMAL priority.""" - self.register_event_handler(event_name, handler, EventPriority.NORMAL) - - # =========================================================== # Plugin Instance (internal) # =========================================================== @@ -466,12 +441,6 @@ def discover_plugins(self, plugins_dir: Optional[str] = None) -> List[PluginInfo # --- Loading --- - def load_plugins_from_dir(self, plugins_dir: str) -> int: - """Compatibility method: discover + load all from a directory. - Returns count of plugins loaded.""" - self.discover_plugins(plugins_dir) - return self.load_all() - def load_all(self) -> int: """Load all discovered plugins in dependency order. Returns count loaded.""" order = self._resolve_dependency_order() @@ -661,20 +630,10 @@ def dispatch_command(self, command: str, args: str = "") -> bool: # --- Query --- - def is_plugin_loaded(self, plugin_id: str) -> bool: - return plugin_id in self._plugins and self._plugins[plugin_id].is_active - def get_plugin(self, plugin_id: str) -> Optional[PyMCPlugin]: instance = self._plugins.get(plugin_id) return instance.plugin_obj if instance else None - def get_plugin_state(self, plugin_id: str) -> Optional[PluginState]: - instance = self._plugins.get(plugin_id) - return instance.state if instance else None - - def get_loaded_plugins(self) -> List[str]: - return [pid for pid, inst in self._plugins.items() if inst.is_active] - @property def plugin_count(self) -> int: return len([i for i in self._plugins.values() if i.is_active]) diff --git a/plugins/bridge.py b/plugins/bridge.py index dd105d4..a122232 100755 --- a/plugins/bridge.py +++ b/plugins/bridge.py @@ -16,7 +16,7 @@ import asyncio import logging -from typing import Optional, Any, Dict, List, Callable +from typing import Optional, List logger = logging.getLogger("pymc.plugins.bridge") @@ -201,11 +201,6 @@ def entity_id(self) -> int: def protocol_version(self) -> int: return self._conn.protocol_version - async def send_message(self, text: str): - """Send a system chat message to this player.""" - from handlers.play.chat import send_system_message - await send_system_message(self._conn, text) - def kick(self, reason: str = "Kicked by plugin"): """Disconnect this player.""" self._conn.alive = False @@ -428,67 +423,6 @@ def hook_player_kick(server, conn, reason: str = ""): pm.fire_event(event) -def hook_player_move(server, conn, from_x: float, from_y: float, from_z: float, - to_x: float, to_y: float, to_z: float): - """Fire the PlayerMoveEvent.""" - pm = server.plugin_manager - if pm is None: - return - from plugins import PluginEvents, PluginEvent - event = PluginEvent( - PluginEvents.PLAYER_MOVE, - { - "player_name": conn.username or "", - "from_x": from_x, "from_y": from_y, "from_z": from_z, - "to_x": to_x, "to_y": to_y, "to_z": to_z, - "player": PlayerBridge(conn), - }, - cancellable=False, - ) - pm.fire_event(event) - - -def hook_player_teleport(server, conn, from_x: float, from_y: float, from_z: float, - to_x: float, to_y: float, to_z: float) -> bool: - """Fire the PlayerTeleportEvent. Returns True if teleport should proceed.""" - pm = server.plugin_manager - if pm is None: - return True - from plugins import PluginEvents, PluginEvent - event = PluginEvent( - PluginEvents.PLAYER_TELEPORT, - { - "player_name": conn.username or "", - "from_x": from_x, "from_y": from_y, "from_z": from_z, - "to_x": to_x, "to_y": to_y, "to_z": to_z, - "player": PlayerBridge(conn), - }, - cancellable=True, - ) - return pm.fire_event(event) - - -def hook_player_interact(server, conn, x: int, y: int, z: int, - action: str = "right_click", hand: str = "main") -> bool: - """Fire the PlayerInteractEvent. Returns True if interaction should proceed.""" - pm = server.plugin_manager - if pm is None: - return True - from plugins import PluginEvents, PluginEvent - event = PluginEvent( - PluginEvents.PLAYER_INTERACT, - { - "player_name": conn.username or "", - "x": x, "y": y, "z": z, - "action": action, - "hand": hand, - "player": PlayerBridge(conn), - }, - cancellable=True, - ) - return pm.fire_event(event) - - def hook_player_respawn(server, conn): """Fire the PlayerRespawnEvent.""" pm = server.plugin_manager @@ -562,79 +496,6 @@ def hook_entity_death(server, entity_id: int, cause: str = ""): pm.fire_event(event) -def hook_projectile_hit(server, entity_id: int, x: int, y: int, z: int): - """Fire the ProjectileHitEvent.""" - pm = server.plugin_manager - if pm is None: - return - from plugins import PluginEvents, PluginEvent - event = PluginEvent( - PluginEvents.PROJECTILE_HIT, - { - "entity_id": entity_id, - "x": x, "y": y, "z": z, - }, - cancellable=False, - ) - pm.fire_event(event) - - -def hook_block_burn(server, x: int, y: int, z: int, block_state: int): - """Fire the BlockBurnEvent.""" - pm = server.plugin_manager - if pm is None: - return - from plugins import PluginEvents, PluginEvent - event = PluginEvent( - PluginEvents.BLOCK_BURN, - { - "x": x, "y": y, "z": z, - "block_state": block_state, - }, - cancellable=False, - ) - pm.fire_event(event) - - -def hook_block_redstone(server, x: int, y: int, z: int, - old_power: int, new_power: int): - """Fire the BlockRedstoneEvent.""" - pm = server.plugin_manager - if pm is None: - return - from plugins import PluginEvents, PluginEvent - event = PluginEvent( - PluginEvents.BLOCK_REDSTONE, - { - "x": x, "y": y, "z": z, - "old_power": old_power, - "new_power": new_power, - }, - cancellable=False, - ) - pm.fire_event(event) - - -def hook_sign_change(server, conn, x: int, y: int, z: int, - lines: list) -> bool: - """Fire the SignChangeEvent. Returns True if change should proceed.""" - pm = server.plugin_manager - if pm is None: - return True - from plugins import PluginEvents, PluginEvent - event = PluginEvent( - PluginEvents.SIGN_CHANGE, - { - "player_name": conn.username or "", - "x": x, "y": y, "z": z, - "lines": lines, - "player": PlayerBridge(conn), - }, - cancellable=True, - ) - return pm.fire_event(event) - - def hook_chunk_load(server, cx: int, cz: int): """Fire the ChunkLoadEvent.""" pm = server.plugin_manager @@ -691,81 +552,6 @@ def hook_time_change(server, old_time: int, new_time: int) -> bool: return pm.fire_event(event) -def hook_inventory_click(server, conn, slot: int, item_id: str = "", - click_type: str = "left") -> bool: - """Fire the InventoryClickEvent. Returns True if click should proceed.""" - pm = server.plugin_manager - if pm is None: - return True - from plugins import PluginEvents, PluginEvent - event = PluginEvent( - PluginEvents.INVENTORY_CLICK, - { - "player_name": conn.username or "", - "slot": slot, - "item_id": item_id, - "click_type": click_type, - "player": PlayerBridge(conn), - }, - cancellable=True, - ) - return pm.fire_event(event) - - -def hook_craft_item(server, conn, result_item: str, recipe_id: str = "") -> bool: - """Fire the CraftItemEvent. Returns True if craft should proceed.""" - pm = server.plugin_manager - if pm is None: - return True - from plugins import PluginEvents, PluginEvent - event = PluginEvent( - PluginEvents.CRAFT_ITEM, - { - "player_name": conn.username or "", - "result_item": result_item, - "recipe_id": recipe_id, - "player": PlayerBridge(conn), - }, - cancellable=True, - ) - return pm.fire_event(event) - - -def hook_fluid_place(server, x: int, y: int, z: int, - fluid_type: str = "water") -> bool: - """Fire the FluidPlaceEvent. Returns True if placement should proceed.""" - pm = server.plugin_manager - if pm is None: - return True - from plugins import PluginEvents, PluginEvent - event = PluginEvent( - PluginEvents.FLUID_PLACE, - {"x": x, "y": y, "z": z, "fluid_type": fluid_type}, - cancellable=True, - ) - return pm.fire_event(event) - - -def hook_fluid_flow(server, from_x: int, from_y: int, from_z: int, - to_x: int, to_y: int, to_z: int, - fluid_type: str = "water") -> bool: - """Fire the FluidFlowEvent. Returns True if flow should proceed.""" - pm = server.plugin_manager - if pm is None: - return True - from plugins import PluginEvents, PluginEvent - event = PluginEvent( - PluginEvents.FLUID_FLOW, - { - "from_x": from_x, "from_y": from_y, "from_z": from_z, - "to_x": to_x, "to_y": to_y, "to_z": to_z, - "fluid_type": fluid_type, - }, - cancellable=True, - ) - return pm.fire_event(event) - - def hook_gamerule_change(server, rule_name: str, old_value, new_value) -> bool: """Fire the GameRuleChangeEvent. Returns True if change should proceed.""" pm = server.plugin_manager @@ -830,18 +616,6 @@ def register_plugin_commands(server): handler, plugin_id = entry # Create a Command object that wraps the plugin's handler - async def _make_executor(h, pid): - async def _exec(ctx: CommandContext) -> int: - try: - # Plugin handlers are sync — call them with the arg string - args = ctx.remaining_input - h(args) - return SUCCESS - except Exception as e: - logger.exception(f"Plugin {pid} command error: {e}") - return FAILURE - return _exec - # We can't use async closure directly in a loop, so bind via default arg cmd = Command( name=cmd_name, diff --git a/plugins/config.py b/plugins/config.py index 1452017..67ed131 100755 --- a/plugins/config.py +++ b/plugins/config.py @@ -10,7 +10,7 @@ import os import tempfile from pathlib import Path -from typing import Any, Dict, List, Optional +from typing import Any, Dict, List logger = logging.getLogger(__name__) @@ -125,13 +125,6 @@ def get_int(self, key: str, default: int = 0) -> int: except (TypeError, ValueError): return default - def get_float(self, key: str, default: float = 0.0) -> float: - val = self._data.get(key, default) - try: - return float(val) - except (TypeError, ValueError): - return default - def get_bool(self, key: str, default: bool = False) -> bool: val = self._data.get(key, default) if isinstance(val, bool): @@ -144,15 +137,6 @@ def get_str(self, key: str, default: str = "") -> str: val = self._data.get(key, default) return str(val) if val is not None else default - def get_list(self, key: str, default: Optional[list] = None) -> list: - val = self._data.get(key, default if default is not None else []) - return list(val) if isinstance(val, (list, tuple)) else (default if default is not None else []) - - def get_section(self, key: str) -> Dict[str, Any]: - """Get a nested dict section. Returns an empty dict if missing or not a dict.""" - val = self._data.get(key, {}) - return val if isinstance(val, dict) else {} - # -- metadata helpers ----------------------------------------------- def has(self, key: str) -> bool: @@ -174,10 +158,6 @@ def keys(self) -> List[str]: def plugin_id(self) -> str: return self._plugin_id - @property - def file_path(self) -> str: - return str(self._file) - # ------------------------------------------------------------------ # Internal helpers # ------------------------------------------------------------------ diff --git a/plugins/java_plugin.py b/plugins/java_plugin.py index 8f0f180..0be30fb 100644 --- a/plugins/java_plugin.py +++ b/plugins/java_plugin.py @@ -29,7 +29,7 @@ import time import zipfile from pathlib import Path -from typing import Callable, Optional +from typing import Callable logger = logging.getLogger("pymc.plugins.java") diff --git a/plugins/scheduler.py b/plugins/scheduler.py index 5e2fe04..9164e55 100755 --- a/plugins/scheduler.py +++ b/plugins/scheduler.py @@ -7,9 +7,9 @@ import asyncio import logging -from dataclasses import dataclass, field +from dataclasses import dataclass from enum import Enum, auto -from typing import Any, Callable, Dict, Optional +from typing import Any, Callable, Dict logger = logging.getLogger(__name__) diff --git a/protocol/data_types.py b/protocol/data_types.py index 9c7e302..54a18d1 100755 --- a/protocol/data_types.py +++ b/protocol/data_types.py @@ -86,26 +86,6 @@ def write_varlong(value: int) -> bytes: return bytes(result) -def read_varlong(data: bytes, offset: int = 0) -> tuple[int, int]: - """从字节流中读取 VarLong。返回 (值, 新偏移量)。""" - result = 0 - num_read = 0 - while True: - if offset >= len(data): - raise ValueError("VarLong 数据不足") - byte = data[offset] - offset += 1 - result |= (byte & 0x7F) << (7 * num_read) - num_read += 1 - if num_read > 10: - raise ValueError("VarLong 超过最大长度 (10 字节)") - if (byte & 0x80) == 0: - break - if result >= (1 << 63): - result -= (1 << 64) - return result, offset - - # -------------------------------------------------- # 基础类型编码 (大端序) # -------------------------------------------------- @@ -150,11 +130,6 @@ def read_short(data: bytes, offset: int = 0) -> tuple[int, int]: return struct.unpack_from('>h', data, offset)[0], offset + 2 -def write_ushort(value: int) -> bytes: - """编码无符号 Short (16位)。""" - return struct.pack('>H', value) - - def read_ushort(data: bytes, offset: int = 0) -> tuple[int, int]: """读取无符号 Short。""" return struct.unpack_from('>H', data, offset)[0], offset + 2 @@ -175,21 +150,6 @@ def write_long(value: int) -> bytes: return struct.pack('>q', value) -def read_long(data: bytes, offset: int = 0) -> tuple[int, int]: - """读取有符号 Long。""" - return struct.unpack_from('>q', data, offset)[0], offset + 8 - - -def write_ulong(value: int) -> bytes: - """编码无符号 Long (64位)。""" - return struct.pack('>Q', value) - - -def read_ulong(data: bytes, offset: int = 0) -> tuple[int, int]: - """读取无符号 Long。""" - return struct.unpack_from('>Q', data, offset)[0], offset + 8 - - def write_float(value: float) -> bytes: """编码 Float (32位浮点)。""" return struct.pack('>f', value) @@ -290,28 +250,10 @@ def write_angle(degrees: float) -> bytes: return struct.pack('>B', int((degrees / 360.0) * 256) & 0xFF) -def read_angle(data: bytes, offset: int = 0) -> tuple[float, int]: - """读取 Angle,返回角度值。""" - raw = data[offset] - return (raw / 256.0) * 360.0, offset + 1 - - # -------------------------------------------------- # 字节数组 # -------------------------------------------------- -def write_byte_array(data_bytes: bytes) -> bytes: - """编码字节数组 (VarInt 长度前缀 + 数据)。""" - return write_varint(len(data_bytes)) + data_bytes - - -def read_byte_array(data: bytes, offset: int = 0) -> tuple[bytes, int]: - """读取字节数组。""" - length, offset = read_varint(data, offset) - end = offset + length - return data[offset:end], end - - # -------------------------------------------------- # 标识符 (Identifier / Namespace:Path) # -------------------------------------------------- @@ -326,6 +268,3 @@ def write_identifier(namespace: str, path: str = None) -> bytes: return write_string(f"{namespace}:{path}") -def read_identifier(data: bytes, offset: int = 0) -> tuple[str, int]: - """读取标识符。""" - return read_string(data, offset) diff --git a/protocol/packet.py b/protocol/packet.py index 8c5d1bc..fa45283 100755 --- a/protocol/packet.py +++ b/protocol/packet.py @@ -7,48 +7,6 @@ from .data_types import write_varint, read_varint, read_varint_async -class PacketBuffer: - """ - 数据包缓冲区,用于方便地构建和读取数据包内容。 - """ - - def __init__(self, data: bytes = b''): - self._data = bytearray(data) - self._offset = 0 - - @property - def data(self) -> bytes: - """获取缓冲区中的所有数据。""" - return bytes(self._data) - - @property - def remaining(self) -> int: - """剩余可读字节数。""" - return len(self._data) - self._offset - - def write(self, data: bytes): - """向缓冲区写入原始字节。""" - self._data.extend(data) - - def read(self, length: int) -> bytes: - """从缓冲区读取指定长度的字节。""" - if self._offset + length > len(self._data): - raise ValueError(f"缓冲区数据不足: 需要 {length} 字节, 剩余 {self.remaining} 字节") - result = bytes(self._data[self._offset:self._offset + length]) - self._offset += length - return result - - def read_all(self) -> bytes: - """读取剩余所有字节。""" - result = bytes(self._data[self._offset:]) - self._offset = len(self._data) - return result - - def reset(self): - """重置读取位置到开头。""" - self._offset = 0 - - def pack_packet(packet_id: int, payload: bytes, compression_threshold: int = -1) -> bytes: """ 将数据包 ID 和负载打包为可发送的帧。 diff --git a/protocol/packet_map.py b/protocol/packet_map.py index 76772b1..6b2ce2d 100755 --- a/protocol/packet_map.py +++ b/protocol/packet_map.py @@ -456,6 +456,7 @@ "update_time": 0x64, "update_health": 0x5D, "set_experience": 0x5C, # experience + "craft_progress_bar": 0x14, # container property (enchanting table, anvil) "entity_teleport": 0x70, "remove_entities": 0x42, # entity_destroy "multi_block_change": 0x49, @@ -821,6 +822,7 @@ "block_dig": 0x24, "entity_action": 0x25, "steer_vehicle": 0x26, + "enchant_item": 0x0D, "pong": 0x27, "held_item_slot": 0x2F, "set_creative_mode_slot": 0x32, @@ -891,11 +893,6 @@ def get_serverbound_packet(protocol_version: int, packet_name: str) -> int | Non return version_packets.get(packet_name) -def get_clientbound_map(protocol_version: int) -> dict: - """Get the full clientbound packet map for a protocol version.""" - return CLIENTBOUND_PACKETS.get(protocol_version, CLIENTBOUND_PACKETS.get(767, {})) - - def get_serverbound_map(protocol_version: int) -> dict: """Get the full serverbound packet map for a protocol version.""" return SERVERBOUND_PACKETS.get(protocol_version, SERVERBOUND_PACKETS.get(767, {})) diff --git a/protocol/versions.py b/protocol/versions.py index 23df70e..f96b054 100755 --- a/protocol/versions.py +++ b/protocol/versions.py @@ -54,11 +54,6 @@ HAS_DIMENSION_REGISTRY.add(pv) -def get_version_info(protocol_version: int) -> dict | None: - """Get version info for a protocol version, or None if not supported.""" - return PROTOCOL_VERSIONS.get(protocol_version) - - def is_supported(protocol_version: int) -> bool: """Check if a protocol version is supported.""" return protocol_version in PROTOCOL_VERSIONS @@ -72,47 +67,11 @@ def get_version_name(protocol_version: int) -> str: return f"Unknown ({protocol_version})" -def get_major_version(protocol_version: int) -> str: - """Get major version string (e.g. '1.21') for a protocol version.""" - info = PROTOCOL_VERSIONS.get(protocol_version) - if info: - return info["major"] - return "unknown" - - def has_configuration_phase(protocol_version: int) -> bool: """Check if this protocol version uses the configuration phase (1.20.2+).""" return protocol_version in HAS_CONFIGURATION_PHASE -def has_world_height_384(protocol_version: int) -> bool: - """Check if this protocol version supports 384-height world (1.17+).""" - return protocol_version in HAS_WORLD_HEIGHT_384 - - -def has_flattening(protocol_version: int) -> bool: - """Check if this protocol version uses the flattened block state IDs (1.13+).""" - return protocol_version in HAS_FLATTENING - - -def get_closest_supported_version(protocol_version: int) -> int | None: - """ - Find the closest supported protocol version for an unsupported version. - Returns the nearest supported version, or None if completely out of range. - """ - if protocol_version in PROTOCOL_VERSIONS: - return protocol_version - - # Find the closest lower supported version - best = None - for pv in SUPPORTED_VERSIONS: - if pv <= protocol_version: - best = pv - else: - break - return best - - def get_handler_version(protocol_version: int) -> str: """ Get the version handler identifier for a given protocol version. diff --git a/python/worldgen_client.py b/python/worldgen_client.py deleted file mode 100755 index 51a0f7d..0000000 --- a/python/worldgen_client.py +++ /dev/null @@ -1,174 +0,0 @@ -import struct -import subprocess -from dataclasses import dataclass - - -MAGIC = 0x4E475752 -VERSION = 1 - -REQ_INIT = 1 -REQ_COLUMN = 2 -REQ_REGION = 3 -REQ_PING = 4 -REQ_SHUTDOWN = 5 - -RESP_ERROR = 0xFFFF -RESP_FLAG = 0x8000 - - -@dataclass -class ColumnSample: - x: int - z: int - height: int - biome_id: int - temperature: float - humidity: float - continentalness: float - erosion: float - weirdness: float - peaks_valleys: float - - -class WorldgenClient: - def __init__(self, exe_path: str): - self.proc = subprocess.Popen( - [exe_path], - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - ) - - def close(self): - try: - self.shutdown() - except Exception: - pass - if self.proc.poll() is None: - self.proc.terminate() - - def _read_exact(self, n: int) -> bytes: - data = self.proc.stdout.read(n) - if data is None or len(data) != n: - raise RuntimeError(f"unexpected EOF while reading {n} bytes") - return data - - def _send(self, req_type: int, payload: bytes) -> tuple[int, bytes]: - if self.proc.stdin is None or self.proc.stdout is None: - raise RuntimeError("process pipes are not available") - header = struct.pack(" bytes: - resp_type, body = self._send(REQ_PING, token) - expected = RESP_FLAG | REQ_PING - if resp_type != expected: - raise RuntimeError(f"unexpected response type {resp_type:#x}") - return body - - def sample_column(self, x: int, z: int) -> ColumnSample: - resp_type, body = self._send(REQ_COLUMN, struct.pack(" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace worldgen { - -constexpr uint64_t kGoldenRatio64 = 0x9E3779B97F4A7C15ULL; -constexpr uint64_t kSilverRatio64 = 0x6A09E667F3BCC909ULL; -constexpr uint32_t kProtocolMagic = 0x4E475752U; // "RWGN" little-endian -constexpr uint16_t kProtocolVersion = 1; - -constexpr uint16_t kReqInit = 1; -constexpr uint16_t kReqSampleColumn = 2; -constexpr uint16_t kReqSampleRegion = 3; -constexpr uint16_t kReqPing = 4; -constexpr uint16_t kReqShutdown = 5; - -constexpr uint16_t kRespFlag = 0x8000U; -constexpr uint16_t kRespError = 0xFFFFU; - -inline uint64_t mixStafford13(uint64_t x) { - x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ULL; - x = (x ^ (x >> 27)) * 0x94D049BB133111EBULL; - return x ^ (x >> 31); -} - -inline std::pair upgradeSeedTo128(uint64_t seed) { - uint64_t lo = seed ^ kSilverRatio64; - uint64_t hi = lo + kGoldenRatio64; - return {mixStafford13(lo), mixStafford13(hi)}; -} - -inline uint64_t fnv1a64(std::string_view s, uint64_t basis) { - constexpr uint64_t prime = 1099511628211ULL; - uint64_t h = basis; - for (unsigned char c : s) { - h ^= static_cast(c); - h *= prime; - } - return h; -} - -class Xoroshiro128PlusPlus { -public: - Xoroshiro128PlusPlus(uint64_t seedLo, uint64_t seedHi) - : seedLo_(seedLo), seedHi_(seedHi) { - if ((seedLo_ | seedHi_) == 0ULL) { - seedLo_ = kGoldenRatio64; - seedHi_ = kSilverRatio64; - } - } - - uint64_t nextU64() { - const uint64_t s0 = seedLo_; - uint64_t s1 = seedHi_; - const uint64_t out = std::rotl(s0 + s1, 17) + s0; - s1 ^= s0; - seedLo_ = std::rotl(s0, 49) ^ s1 ^ (s1 << 21); - seedHi_ = std::rotl(s1, 28); - return out; - } - - int nextInt(int bound) { - if (bound <= 0) { - return 0; - } - uint64_t u = static_cast(nextU64()); - uint64_t m = u * static_cast(bound); - uint64_t l = m & 0xFFFFFFFFULL; - if (l < static_cast(bound)) { - const uint32_t threshold = - static_cast((0U - static_cast(bound)) % - static_cast(bound)); - while (l < threshold) { - u = static_cast(nextU64()); - m = u * static_cast(bound); - l = m & 0xFFFFFFFFULL; - } - } - return static_cast(m >> 32); - } - - double nextDouble() { - return static_cast(nextU64() >> 11) * - (1.0 / 9007199254740992.0); - } - -private: - uint64_t seedLo_; - uint64_t seedHi_; -}; - -class HashRandomFactory { -public: - explicit HashRandomFactory(int64_t worldSeed) { - auto [lo, hi] = upgradeSeedTo128(static_cast(worldSeed)); - seedLo_ = lo; - seedHi_ = hi; - } - - HashRandomFactory(uint64_t lo, uint64_t hi) : seedLo_(lo), seedHi_(hi) {} - - HashRandomFactory child(std::string_view key) const { - auto [h0, h1] = hash2x64(key); - return HashRandomFactory(seedLo_ ^ h0, seedHi_ ^ h1); - } - - Xoroshiro128PlusPlus fromHash(std::string_view key) const { - auto [h0, h1] = hash2x64(key); - return Xoroshiro128PlusPlus(seedLo_ ^ h0, seedHi_ ^ h1); - } - -private: - static std::pair hash2x64(std::string_view key) { - uint64_t h0 = fnv1a64(key, 1469598103934665603ULL); - uint64_t h1 = fnv1a64(key, 7809847782465536322ULL); - h0 = mixStafford13(h0); - h1 = mixStafford13(h1 ^ (h0 + kGoldenRatio64)); - return {h0, h1}; - } - - uint64_t seedLo_; - uint64_t seedHi_; -}; - -inline int fastFloor(double v) { - int i = static_cast(v); - return (v < static_cast(i)) ? (i - 1) : i; -} - -inline double smoothstep(double t) { - return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); -} - -inline double lerp(double t, double a, double b) { return a + t * (b - a); } - -inline double clampedLerp(double a, double b, double t) { - if (t < 0.0) { - return a; - } - if (t > 1.0) { - return b; - } - return lerp(t, a, b); -} - -class ImprovedNoise { -public: - explicit ImprovedNoise(Xoroshiro128PlusPlus& rng) { - xo_ = rng.nextDouble() * 256.0; - yo_ = rng.nextDouble() * 256.0; - zo_ = rng.nextDouble() * 256.0; - for (int i = 0; i < 256; ++i) { - p_[i] = static_cast(i); - } - for (int i = 0; i < 256; ++i) { - int j = i + rng.nextInt(256 - i); - std::swap(p_[i], p_[j]); - } - } - - double noise(double x, double y, double z) const { - return noise(x, y, z, 0.0, 0.0); - } - - double noise(double x, double y, double z, double yScale, double yMax) const { - const double xs = x + xo_; - const double ys = y + yo_; - const double zs = z + zo_; - - const int xFloor = fastFloor(xs); - const int yFloor = fastFloor(ys); - const int zFloor = fastFloor(zs); - - const double xFrac = xs - static_cast(xFloor); - double yFrac = ys - static_cast(yFloor); - const double zFrac = zs - static_cast(zFloor); - - double yQuantizedOffset = 0.0; - if (yScale != 0.0) { - double yAnchor = yFrac; - if (yMax >= 0.0 && yMax < yFrac) { - yAnchor = yMax; - } - yQuantizedOffset = std::floor(yAnchor / yScale + 1.0e-7) * yScale; - } - - yFrac -= yQuantizedOffset; - return sampleAndLerp(xFloor, yFloor, zFloor, xFrac, yFrac, zFrac, ys - static_cast(yFloor)); - } - -private: - static constexpr std::array, 16> kGradient = {{ - {{1, 1, 0}}, {{-1, 1, 0}}, {{1, -1, 0}}, {{-1, -1, 0}}, - {{1, 0, 1}}, {{-1, 0, 1}}, {{1, 0, -1}}, {{-1, 0, -1}}, - {{0, 1, 1}}, {{0, -1, 1}}, {{0, 1, -1}}, {{0, -1, -1}}, - {{1, 1, 0}}, {{0, -1, 1}}, {{-1, 1, 0}}, {{0, -1, -1}}, - }}; - - int p(int idx) const { return static_cast(p_[idx & 0xFF]); } - - static double gradDot(int h, double x, double y, double z) { - const auto& g = kGradient[h & 0x0F]; - return static_cast(g[0]) * x + static_cast(g[1]) * y + - static_cast(g[2]) * z; - } - - double sampleAndLerp(int xFloor, - int yFloor, - int zFloor, - double xFrac, - double yFrac, - double zFrac, - double ySmoothInput) const { - const int x0 = p(xFloor); - const int x1 = p(xFloor + 1); - const int a = p(x0 + yFloor); - const int b = p(x0 + yFloor + 1); - const int c = p(x1 + yFloor); - const int d = p(x1 + yFloor + 1); - - const double n000 = gradDot(p(a + zFloor), xFrac, yFrac, zFrac); - const double n100 = gradDot(p(c + zFloor), xFrac - 1.0, yFrac, zFrac); - const double n010 = gradDot(p(b + zFloor), xFrac, yFrac - 1.0, zFrac); - const double n110 = gradDot(p(d + zFloor), xFrac - 1.0, yFrac - 1.0, zFrac); - const double n001 = gradDot(p(a + zFloor + 1), xFrac, yFrac, zFrac - 1.0); - const double n101 = gradDot(p(c + zFloor + 1), xFrac - 1.0, yFrac, zFrac - 1.0); - const double n011 = gradDot(p(b + zFloor + 1), xFrac, yFrac - 1.0, zFrac - 1.0); - const double n111 = gradDot(p(d + zFloor + 1), xFrac - 1.0, yFrac - 1.0, zFrac - 1.0); - - const double u = smoothstep(xFrac); - const double v = smoothstep(ySmoothInput); - const double w = smoothstep(zFrac); - - const double x00 = lerp(u, n000, n100); - const double x10 = lerp(u, n010, n110); - const double x01 = lerp(u, n001, n101); - const double x11 = lerp(u, n011, n111); - const double y0 = lerp(v, x00, x10); - const double y1 = lerp(v, x01, x11); - return lerp(w, y0, y1); - } - - std::array p_{}; - double xo_{0.0}; - double yo_{0.0}; - double zo_{0.0}; -}; - -struct NoiseParameters { - int firstOctave; - std::vector amplitudes; -}; - -class PerlinNoise { -public: - PerlinNoise(const HashRandomFactory& seedFactory, - int firstOctave, - const std::vector& amplitudes, - std::string_view label) - : firstOctave_(firstOctave), amplitudes_(amplitudes) { - const int count = static_cast(amplitudes_.size()); - levels_.reserve(count); - hasLevel_.assign(count, false); - for (int i = 0; i < count; ++i) { - levels_.emplace_back(nullptr); - } - - const HashRandomFactory octaveFactory = seedFactory.child(label); - for (int i = 0; i < count; ++i) { - if (amplitudes_[i] == 0.0) { - continue; - } - const int octave = firstOctave_ + i; - Xoroshiro128PlusPlus rng = - octaveFactory.fromHash("octave_" + std::to_string(octave)); - levels_[i] = std::make_unique(rng); - hasLevel_[i] = true; - } - - const int octaveShift = -firstOctave_; - lowestFreqInputFactor_ = std::pow(2.0, -octaveShift); - lowestFreqValueFactor_ = - std::pow(2.0, count - 1) / (std::pow(2.0, count) - 1.0); - } - - double getValue(double x, double y, double z) const { - double value = 0.0; - double freq = lowestFreqInputFactor_; - double amp = lowestFreqValueFactor_; - for (size_t i = 0; i < levels_.size(); ++i) { - if (hasLevel_[i]) { - value += amplitudes_[i] * - levels_[i]->noise(wrap(x * freq), wrap(y * freq), wrap(z * freq)) * amp; - } - freq *= 2.0; - amp /= 2.0; - } - return value; - } - - const ImprovedNoise* getOctaveNoise(int octaveFromTop) const { - const int idx = static_cast(levels_.size()) - 1 - octaveFromTop; - if (idx < 0 || idx >= static_cast(levels_.size())) { - return nullptr; - } - return hasLevel_[idx] ? levels_[idx].get() : nullptr; - } - - static double wrap(double v) { - constexpr double wrapRange = 33554432.0; - return v - std::floor(v / wrapRange + 0.5) * wrapRange; - } - -private: - int firstOctave_; - std::vector amplitudes_; - std::vector> levels_; - std::vector hasLevel_; - double lowestFreqInputFactor_{1.0}; - double lowestFreqValueFactor_{1.0}; -}; - -class NormalNoise { -public: - NormalNoise(const HashRandomFactory& baseFactory, - std::string_view noiseKey, - const NoiseParameters& params) - : first_(baseFactory.child(std::string(noiseKey) + ":a"), - params.firstOctave, - params.amplitudes, - "first"), - second_(baseFactory.child(std::string(noiseKey) + ":b"), - params.firstOctave, - params.amplitudes, - "second") { - int minIdx = std::numeric_limits::max(); - int maxIdx = std::numeric_limits::min(); - for (int i = 0; i < static_cast(params.amplitudes.size()); ++i) { - if (params.amplitudes[i] == 0.0) { - continue; - } - minIdx = std::min(minIdx, i); - maxIdx = std::max(maxIdx, i); - } - if (minIdx == std::numeric_limits::max()) { - minIdx = 0; - maxIdx = 0; - } - const double expectedDeviation = - 0.1 * (1.0 + 1.0 / static_cast((maxIdx - minIdx) + 1)); - valueFactor_ = (1.0 / 6.0) / expectedDeviation; - } - - double getValue(double x, double y, double z) const { - constexpr double inputFactor = 1.0181268882175227; - const double sx = x * inputFactor; - const double sy = y * inputFactor; - const double sz = z * inputFactor; - return (first_.getValue(x, y, z) + second_.getValue(sx, sy, sz)) * valueFactor_; - } - -private: - PerlinNoise first_; - PerlinNoise second_; - double valueFactor_{1.0}; -}; - -class OctaveNoise5 { -public: - OctaveNoise5(const HashRandomFactory& factory, std::string_view key) { - layers_.reserve(5); - HashRandomFactory sub = factory.child(key); - for (int i = 0; i < 5; ++i) { - Xoroshiro128PlusPlus rng = - sub.fromHash("layer_" + std::to_string(i)); - layers_.emplace_back(rng); - } - } - - double noise3D(double x, double y, double z) const { - double out = 0.0; - double freq = 1.0; - double amp = 1.0; - for (const auto& n : layers_) { - out += n.noise(x * freq, y * freq, z * freq) * amp; - freq *= 2.0; - amp *= 0.5; - } - return out; - } - -private: - std::vector layers_; -}; - -enum class BiomeId : int16_t { - None = 0, - Plains, - SunflowerPlains, - SnowyPlains, - IceSpikes, - Desert, - Swamp, - MangroveSwamp, - Forest, - FlowerForest, - BirchForest, - DarkForest, - OldGrowthBirchForest, - OldGrowthPineTaiga, - OldGrowthSpruceTaiga, - Taiga, - SnowyTaiga, - Savanna, - SavannaPlateau, - WindsweptHills, - WindsweptGravellyHills, - WindsweptForest, - WindsweptSavanna, - Jungle, - SparseJungle, - BambooJungle, - Badlands, - ErodedBadlands, - WoodedBadlands, - Meadow, - CherryGrove, - Grove, - SnowySlopes, - FrozenPeaks, - JaggedPeaks, - StonyPeaks, - River, - FrozenRiver, - Beach, - SnowyBeach, - StonyShore, - WarmOcean, - LukewarmOcean, - DeepLukewarmOcean, - Ocean, - DeepOcean, - ColdOcean, - DeepColdOcean, - FrozenOcean, - DeepFrozenOcean, - MushroomFields, - DripstoneCaves, - LushCaves, - DeepDark, -}; - -const char* biomeName(BiomeId id) { - switch (id) { - case BiomeId::Plains: - return "plains"; - case BiomeId::SunflowerPlains: - return "sunflower_plains"; - case BiomeId::SnowyPlains: - return "snowy_plains"; - case BiomeId::IceSpikes: - return "ice_spikes"; - case BiomeId::Desert: - return "desert"; - case BiomeId::Swamp: - return "swamp"; - case BiomeId::MangroveSwamp: - return "mangrove_swamp"; - case BiomeId::Forest: - return "forest"; - case BiomeId::FlowerForest: - return "flower_forest"; - case BiomeId::BirchForest: - return "birch_forest"; - case BiomeId::DarkForest: - return "dark_forest"; - case BiomeId::OldGrowthBirchForest: - return "old_growth_birch_forest"; - case BiomeId::OldGrowthPineTaiga: - return "old_growth_pine_taiga"; - case BiomeId::OldGrowthSpruceTaiga: - return "old_growth_spruce_taiga"; - case BiomeId::Taiga: - return "taiga"; - case BiomeId::SnowyTaiga: - return "snowy_taiga"; - case BiomeId::Savanna: - return "savanna"; - case BiomeId::SavannaPlateau: - return "savanna_plateau"; - case BiomeId::WindsweptHills: - return "windswept_hills"; - case BiomeId::WindsweptGravellyHills: - return "windswept_gravelly_hills"; - case BiomeId::WindsweptForest: - return "windswept_forest"; - case BiomeId::WindsweptSavanna: - return "windswept_savanna"; - case BiomeId::Jungle: - return "jungle"; - case BiomeId::SparseJungle: - return "sparse_jungle"; - case BiomeId::BambooJungle: - return "bamboo_jungle"; - case BiomeId::Badlands: - return "badlands"; - case BiomeId::ErodedBadlands: - return "eroded_badlands"; - case BiomeId::WoodedBadlands: - return "wooded_badlands"; - case BiomeId::Meadow: - return "meadow"; - case BiomeId::CherryGrove: - return "cherry_grove"; - case BiomeId::Grove: - return "grove"; - case BiomeId::SnowySlopes: - return "snowy_slopes"; - case BiomeId::FrozenPeaks: - return "frozen_peaks"; - case BiomeId::JaggedPeaks: - return "jagged_peaks"; - case BiomeId::StonyPeaks: - return "stony_peaks"; - case BiomeId::River: - return "river"; - case BiomeId::FrozenRiver: - return "frozen_river"; - case BiomeId::Beach: - return "beach"; - case BiomeId::SnowyBeach: - return "snowy_beach"; - case BiomeId::StonyShore: - return "stony_shore"; - case BiomeId::WarmOcean: - return "warm_ocean"; - case BiomeId::LukewarmOcean: - return "lukewarm_ocean"; - case BiomeId::DeepLukewarmOcean: - return "deep_lukewarm_ocean"; - case BiomeId::Ocean: - return "ocean"; - case BiomeId::DeepOcean: - return "deep_ocean"; - case BiomeId::ColdOcean: - return "cold_ocean"; - case BiomeId::DeepColdOcean: - return "deep_cold_ocean"; - case BiomeId::FrozenOcean: - return "frozen_ocean"; - case BiomeId::DeepFrozenOcean: - return "deep_frozen_ocean"; - case BiomeId::MushroomFields: - return "mushroom_fields"; - case BiomeId::DripstoneCaves: - return "dripstone_caves"; - case BiomeId::LushCaves: - return "lush_caves"; - case BiomeId::DeepDark: - return "deep_dark"; - default: - return "plains"; - } -} - -std::pair biomeHeightParams(BiomeId biome) { - switch (biome) { - case BiomeId::DeepOcean: - case BiomeId::DeepColdOcean: - case BiomeId::DeepFrozenOcean: - case BiomeId::DeepLukewarmOcean: - return {-1.8, 0.10}; - case BiomeId::Ocean: - case BiomeId::ColdOcean: - case BiomeId::FrozenOcean: - case BiomeId::LukewarmOcean: - case BiomeId::WarmOcean: - return {-1.0, 0.10}; - case BiomeId::Beach: - case BiomeId::SnowyBeach: - return {0.0, 0.02}; - case BiomeId::River: - case BiomeId::FrozenRiver: - return {-0.35, 0.05}; - case BiomeId::MushroomFields: - return {0.20, 0.30}; - case BiomeId::Swamp: - case BiomeId::MangroveSwamp: - return {-0.20, 0.08}; - case BiomeId::SnowySlopes: - case BiomeId::FrozenPeaks: - case BiomeId::JaggedPeaks: - case BiomeId::StonyPeaks: - return {1.30, 0.70}; - case BiomeId::Meadow: - case BiomeId::Grove: - case BiomeId::CherryGrove: - return {0.55, 0.30}; - case BiomeId::WindsweptHills: - case BiomeId::WindsweptForest: - case BiomeId::WindsweptGravellyHills: - case BiomeId::WindsweptSavanna: - return {1.00, 0.50}; - case BiomeId::Badlands: - case BiomeId::ErodedBadlands: - case BiomeId::WoodedBadlands: - return {0.30, 0.20}; - case BiomeId::SavannaPlateau: - return {0.35, 0.20}; - case BiomeId::Desert: - case BiomeId::Plains: - case BiomeId::SunflowerPlains: - case BiomeId::SnowyPlains: - return {0.125, 0.05}; - case BiomeId::Forest: - case BiomeId::FlowerForest: - case BiomeId::BirchForest: - case BiomeId::DarkForest: - case BiomeId::Jungle: - case BiomeId::SparseJungle: - case BiomeId::BambooJungle: - return {0.10, 0.20}; - case BiomeId::Taiga: - case BiomeId::SnowyTaiga: - case BiomeId::OldGrowthBirchForest: - case BiomeId::OldGrowthPineTaiga: - case BiomeId::OldGrowthSpruceTaiga: - return {0.20, 0.20}; - case BiomeId::IceSpikes: - return {0.45, 0.50}; - default: - return {0.125, 0.05}; - } -} - -struct ClimateRange { - float min; - float max; -}; - -ClimateRange span(float a, float b) { - return (a <= b) ? ClimateRange{a, b} : ClimateRange{b, a}; -} - -ClimateRange span(const ClimateRange& a, const ClimateRange& b) { - return {std::min(a.min, b.min), std::max(a.max, b.max)}; -} - -ClimateRange point(float v) { return {v, v}; } - -struct ClimatePoint { - ClimateRange temperature; - ClimateRange humidity; - ClimateRange continentalness; - ClimateRange erosion; - ClimateRange depth; - ClimateRange weirdness; - float offset; - BiomeId biome; -}; - -inline float rangeDistance(const ClimateRange& r, float value) { - if (value < r.min) { - return r.min - value; - } - if (value > r.max) { - return value - r.max; - } - return 0.0f; -} - -class OverworldBiomeTable { -public: - OverworldBiomeTable() { - initRanges(); - initBiomeTables(); - points_.reserve(8192); - addBiomes(); - } - - BiomeId resolve(float temperature, - float humidity, - float continentalness, - float erosion, - float depth, - float weirdness) const { - float best = std::numeric_limits::infinity(); - BiomeId result = BiomeId::Plains; - for (const auto& p : points_) { - float d = 0.0f; - d += square(rangeDistance(p.temperature, temperature)); - d += square(rangeDistance(p.humidity, humidity)); - d += square(rangeDistance(p.continentalness, continentalness)); - d += square(rangeDistance(p.erosion, erosion)); - d += square(rangeDistance(p.depth, depth)); - d += square(rangeDistance(p.weirdness, weirdness)); - d += square(p.offset); - if (d < best) { - best = d; - result = p.biome; - } - } - return result; - } - -private: - static float square(float v) { return v * v; } - - void initRanges() { - fullRange_ = span(-1.0f, 1.0f); - temperatures_ = { - span(-1.0f, -0.45f), - span(-0.45f, -0.15f), - span(-0.15f, 0.2f), - span(0.2f, 0.55f), - span(0.55f, 1.0f), - }; - humidities_ = { - span(-1.0f, -0.35f), - span(-0.35f, -0.1f), - span(-0.1f, 0.1f), - span(0.1f, 0.3f), - span(0.3f, 1.0f), - }; - erosions_ = { - span(-1.0f, -0.78f), - span(-0.78f, -0.375f), - span(-0.375f, -0.2225f), - span(-0.2225f, 0.05f), - span(0.05f, 0.45f), - span(0.45f, 0.55f), - span(0.55f, 1.0f), - }; - frozenRange_ = temperatures_[0]; - unfrozenRange_ = span(temperatures_[1], temperatures_[4]); - mushroomFieldsContinentalness_ = span(-1.2f, -1.05f); - deepOceanContinentalness_ = span(-1.05f, -0.455f); - oceanContinentalness_ = span(-0.455f, -0.19f); - coastContinentalness_ = span(-0.19f, -0.11f); - inlandContinentalness_ = span(-0.11f, 0.55f); - nearInlandContinentalness_ = span(-0.11f, 0.03f); - midInlandContinentalness_ = span(0.03f, 0.3f); - farInlandContinentalness_ = span(0.3f, 1.0f); - } - - void initBiomeTables() { - oceans_ = {{ - {BiomeId::DeepFrozenOcean, BiomeId::DeepColdOcean, BiomeId::DeepOcean, - BiomeId::DeepLukewarmOcean, BiomeId::WarmOcean}, - {BiomeId::FrozenOcean, BiomeId::ColdOcean, BiomeId::Ocean, - BiomeId::LukewarmOcean, BiomeId::WarmOcean}, - }}; - - middleBiomes_ = {{ - {BiomeId::SnowyPlains, BiomeId::SnowyPlains, BiomeId::SnowyPlains, - BiomeId::SnowyTaiga, BiomeId::Taiga}, - {BiomeId::Plains, BiomeId::Plains, BiomeId::Forest, BiomeId::Taiga, - BiomeId::OldGrowthSpruceTaiga}, - {BiomeId::FlowerForest, BiomeId::Plains, BiomeId::Forest, - BiomeId::BirchForest, BiomeId::DarkForest}, - {BiomeId::Savanna, BiomeId::Savanna, BiomeId::Forest, BiomeId::Jungle, - BiomeId::Jungle}, - {BiomeId::Desert, BiomeId::Desert, BiomeId::Desert, BiomeId::Desert, - BiomeId::Desert}, - }}; - - middleBiomesVariant_ = {{ - {BiomeId::IceSpikes, BiomeId::None, BiomeId::SnowyTaiga, BiomeId::None, - BiomeId::None}, - {BiomeId::None, BiomeId::None, BiomeId::None, BiomeId::None, - BiomeId::OldGrowthPineTaiga}, - {BiomeId::SunflowerPlains, BiomeId::None, BiomeId::None, - BiomeId::OldGrowthBirchForest, BiomeId::None}, - {BiomeId::None, BiomeId::None, BiomeId::Plains, BiomeId::SparseJungle, - BiomeId::BambooJungle}, - {BiomeId::None, BiomeId::None, BiomeId::None, BiomeId::None, - BiomeId::None}, - }}; - - plateauBiomes_ = {{ - {BiomeId::SnowyPlains, BiomeId::SnowyPlains, BiomeId::SnowyPlains, - BiomeId::SnowyTaiga, BiomeId::SnowyTaiga}, - {BiomeId::Meadow, BiomeId::Meadow, BiomeId::Forest, BiomeId::Taiga, - BiomeId::OldGrowthSpruceTaiga}, - {BiomeId::Meadow, BiomeId::Meadow, BiomeId::Meadow, BiomeId::Meadow, - BiomeId::DarkForest}, - {BiomeId::SavannaPlateau, BiomeId::SavannaPlateau, BiomeId::Forest, - BiomeId::Forest, BiomeId::Jungle}, - {BiomeId::Badlands, BiomeId::Badlands, BiomeId::Badlands, - BiomeId::WoodedBadlands, BiomeId::WoodedBadlands}, - }}; - - plateauBiomesVariant_ = {{ - {BiomeId::IceSpikes, BiomeId::None, BiomeId::None, BiomeId::None, - BiomeId::None}, - {BiomeId::CherryGrove, BiomeId::None, BiomeId::Meadow, BiomeId::Meadow, - BiomeId::OldGrowthPineTaiga}, - {BiomeId::CherryGrove, BiomeId::CherryGrove, BiomeId::Forest, - BiomeId::BirchForest, BiomeId::None}, - {BiomeId::None, BiomeId::None, BiomeId::None, BiomeId::None, - BiomeId::None}, - {BiomeId::ErodedBadlands, BiomeId::ErodedBadlands, BiomeId::None, - BiomeId::None, BiomeId::None}, - }}; - - shatteredBiomes_ = {{ - {BiomeId::WindsweptGravellyHills, BiomeId::WindsweptGravellyHills, - BiomeId::WindsweptHills, BiomeId::WindsweptForest, - BiomeId::WindsweptForest}, - {BiomeId::WindsweptGravellyHills, BiomeId::WindsweptGravellyHills, - BiomeId::WindsweptHills, BiomeId::WindsweptForest, - BiomeId::WindsweptForest}, - {BiomeId::WindsweptHills, BiomeId::WindsweptHills, BiomeId::WindsweptHills, - BiomeId::WindsweptForest, BiomeId::WindsweptForest}, - {BiomeId::None, BiomeId::None, BiomeId::None, BiomeId::None, - BiomeId::None}, - {BiomeId::None, BiomeId::None, BiomeId::None, BiomeId::None, - BiomeId::None}, - }}; - } - - void addBiomes() { - addOffCoastBiomes(); - addInlandBiomes(); - addUndergroundBiomes(); - } - - void addOffCoastBiomes() { - addSurfaceBiome(fullRange_, - fullRange_, - mushroomFieldsContinentalness_, - fullRange_, - fullRange_, - 0.0f, - BiomeId::MushroomFields); - for (int i = 0; i < 5; ++i) { - const ClimateRange t = temperatures_[i]; - addSurfaceBiome(t, - fullRange_, - deepOceanContinentalness_, - fullRange_, - fullRange_, - 0.0f, - oceans_[0][i]); - addSurfaceBiome(t, - fullRange_, - oceanContinentalness_, - fullRange_, - fullRange_, - 0.0f, - oceans_[1][i]); - } - } - - void addInlandBiomes() { - addMidSlice(span(-1.0f, -0.93333334f)); - addHighSlice(span(-0.93333334f, -0.7666667f)); - addPeaks(span(-0.7666667f, -0.56666666f)); - addHighSlice(span(-0.56666666f, -0.4f)); - addMidSlice(span(-0.4f, -0.26666668f)); - addLowSlice(span(-0.26666668f, -0.05f)); - addValleys(span(-0.05f, 0.05f)); - addLowSlice(span(0.05f, 0.26666668f)); - addMidSlice(span(0.26666668f, 0.4f)); - addHighSlice(span(0.4f, 0.56666666f)); - addPeaks(span(0.56666666f, 0.7666667f)); - addHighSlice(span(0.7666667f, 0.93333334f)); - addMidSlice(span(0.93333334f, 1.0f)); - } - - void addPeaks(const ClimateRange& weird) { - for (int ti = 0; ti < 5; ++ti) { - const ClimateRange t = temperatures_[ti]; - for (int hi = 0; hi < 5; ++hi) { - const ClimateRange h = humidities_[hi]; - const BiomeId middle = pickMiddleBiome(ti, hi, weird); - const BiomeId middleOrBadlands = pickMiddleBiomeOrBadlandsIfHot(ti, hi, weird); - const BiomeId middleOrBadlandsOrSlope = - pickMiddleBiomeOrBadlandsIfHotOrSlopeIfCold(ti, hi, weird); - const BiomeId plateau = pickPlateauBiome(ti, hi, weird); - const BiomeId shattered = pickShatteredBiome(ti, hi, weird); - const BiomeId windsweptSavanna = - maybePickWindsweptSavannaBiome(ti, hi, weird, shattered); - const BiomeId peak = pickPeakBiome(ti, hi, weird); - - addSurfaceBiome(t, - h, - span(coastContinentalness_, farInlandContinentalness_), - erosions_[0], - weird, - 0.0f, - peak); - addSurfaceBiome(t, - h, - span(coastContinentalness_, nearInlandContinentalness_), - erosions_[1], - weird, - 0.0f, - middleOrBadlandsOrSlope); - addSurfaceBiome(t, - h, - span(midInlandContinentalness_, farInlandContinentalness_), - erosions_[1], - weird, - 0.0f, - peak); - addSurfaceBiome(t, - h, - span(coastContinentalness_, nearInlandContinentalness_), - span(erosions_[2], erosions_[3]), - weird, - 0.0f, - middle); - addSurfaceBiome(t, - h, - span(midInlandContinentalness_, farInlandContinentalness_), - erosions_[2], - weird, - 0.0f, - plateau); - addSurfaceBiome(t, - h, - midInlandContinentalness_, - erosions_[3], - weird, - 0.0f, - middleOrBadlands); - addSurfaceBiome(t, - h, - farInlandContinentalness_, - erosions_[3], - weird, - 0.0f, - plateau); - addSurfaceBiome(t, - h, - span(coastContinentalness_, farInlandContinentalness_), - erosions_[4], - weird, - 0.0f, - middle); - addSurfaceBiome(t, - h, - span(coastContinentalness_, nearInlandContinentalness_), - erosions_[5], - weird, - 0.0f, - windsweptSavanna); - addSurfaceBiome(t, - h, - span(midInlandContinentalness_, farInlandContinentalness_), - erosions_[5], - weird, - 0.0f, - shattered); - addSurfaceBiome(t, - h, - span(coastContinentalness_, farInlandContinentalness_), - erosions_[6], - weird, - 0.0f, - middle); - } - } - } - - void addHighSlice(const ClimateRange& weird) { - for (int ti = 0; ti < 5; ++ti) { - const ClimateRange t = temperatures_[ti]; - for (int hi = 0; hi < 5; ++hi) { - const ClimateRange h = humidities_[hi]; - const BiomeId middle = pickMiddleBiome(ti, hi, weird); - const BiomeId middleOrBadlands = pickMiddleBiomeOrBadlandsIfHot(ti, hi, weird); - const BiomeId middleOrBadlandsOrSlope = - pickMiddleBiomeOrBadlandsIfHotOrSlopeIfCold(ti, hi, weird); - const BiomeId plateau = pickPlateauBiome(ti, hi, weird); - const BiomeId shattered = pickShatteredBiome(ti, hi, weird); - const BiomeId windsweptSavanna = - maybePickWindsweptSavannaBiome(ti, hi, weird, middle); - const BiomeId slope = pickSlopeBiome(ti, hi, weird); - const BiomeId peak = pickPeakBiome(ti, hi, weird); - - addSurfaceBiome(t, h, coastContinentalness_, span(erosions_[0], erosions_[1]), weird, 0.0f, middle); - addSurfaceBiome(t, h, nearInlandContinentalness_, erosions_[0], weird, 0.0f, slope); - addSurfaceBiome(t, h, span(midInlandContinentalness_, farInlandContinentalness_), erosions_[0], weird, 0.0f, peak); - addSurfaceBiome(t, h, nearInlandContinentalness_, erosions_[1], weird, 0.0f, middleOrBadlandsOrSlope); - addSurfaceBiome(t, h, span(midInlandContinentalness_, farInlandContinentalness_), erosions_[1], weird, 0.0f, slope); - addSurfaceBiome(t, h, span(coastContinentalness_, nearInlandContinentalness_), span(erosions_[2], erosions_[3]), weird, 0.0f, middle); - addSurfaceBiome(t, h, span(midInlandContinentalness_, farInlandContinentalness_), erosions_[2], weird, 0.0f, plateau); - addSurfaceBiome(t, h, midInlandContinentalness_, erosions_[3], weird, 0.0f, middleOrBadlands); - addSurfaceBiome(t, h, farInlandContinentalness_, erosions_[3], weird, 0.0f, plateau); - addSurfaceBiome(t, h, span(coastContinentalness_, farInlandContinentalness_), erosions_[4], weird, 0.0f, middle); - addSurfaceBiome(t, h, span(coastContinentalness_, nearInlandContinentalness_), erosions_[5], weird, 0.0f, windsweptSavanna); - addSurfaceBiome(t, h, span(midInlandContinentalness_, farInlandContinentalness_), erosions_[5], weird, 0.0f, shattered); - addSurfaceBiome(t, h, span(coastContinentalness_, farInlandContinentalness_), erosions_[6], weird, 0.0f, middle); - } - } - } - - void addMidSlice(const ClimateRange& weird) { - addSurfaceBiome(fullRange_, fullRange_, coastContinentalness_, span(erosions_[0], erosions_[2]), weird, 0.0f, BiomeId::StonyShore); - addSurfaceBiome(span(temperatures_[1], temperatures_[2]), fullRange_, span(nearInlandContinentalness_, farInlandContinentalness_), erosions_[6], weird, 0.0f, BiomeId::Swamp); - addSurfaceBiome(span(temperatures_[3], temperatures_[4]), fullRange_, span(nearInlandContinentalness_, farInlandContinentalness_), erosions_[6], weird, 0.0f, BiomeId::MangroveSwamp); - - for (int ti = 0; ti < 5; ++ti) { - const ClimateRange t = temperatures_[ti]; - for (int hi = 0; hi < 5; ++hi) { - const ClimateRange h = humidities_[hi]; - const BiomeId middle = pickMiddleBiome(ti, hi, weird); - const BiomeId middleOrBadlands = pickMiddleBiomeOrBadlandsIfHot(ti, hi, weird); - const BiomeId middleOrBadlandsOrSlope = - pickMiddleBiomeOrBadlandsIfHotOrSlopeIfCold(ti, hi, weird); - const BiomeId shattered = pickShatteredBiome(ti, hi, weird); - const BiomeId plateau = pickPlateauBiome(ti, hi, weird); - const BiomeId beach = pickBeachBiome(ti, hi); - const BiomeId windsweptSavanna = - maybePickWindsweptSavannaBiome(ti, hi, weird, middle); - const BiomeId shatteredCoast = pickShatteredCoastBiome(ti, hi, weird); - const BiomeId slope = pickSlopeBiome(ti, hi, weird); - - addSurfaceBiome(t, h, span(nearInlandContinentalness_, farInlandContinentalness_), erosions_[0], weird, 0.0f, slope); - addSurfaceBiome(t, h, span(nearInlandContinentalness_, midInlandContinentalness_), erosions_[1], weird, 0.0f, middleOrBadlandsOrSlope); - addSurfaceBiome(t, h, farInlandContinentalness_, erosions_[1], weird, 0.0f, (ti == 0) ? slope : plateau); - addSurfaceBiome(t, h, nearInlandContinentalness_, erosions_[2], weird, 0.0f, middle); - addSurfaceBiome(t, h, midInlandContinentalness_, erosions_[2], weird, 0.0f, middleOrBadlands); - addSurfaceBiome(t, h, farInlandContinentalness_, erosions_[2], weird, 0.0f, plateau); - addSurfaceBiome(t, h, span(coastContinentalness_, nearInlandContinentalness_), erosions_[3], weird, 0.0f, middle); - addSurfaceBiome(t, h, span(midInlandContinentalness_, farInlandContinentalness_), erosions_[3], weird, 0.0f, middleOrBadlands); - - if (weird.max < 0.0f) { - addSurfaceBiome(t, h, coastContinentalness_, erosions_[4], weird, 0.0f, beach); - addSurfaceBiome(t, h, span(nearInlandContinentalness_, farInlandContinentalness_), erosions_[4], weird, 0.0f, middle); - } else { - addSurfaceBiome(t, h, span(coastContinentalness_, farInlandContinentalness_), erosions_[4], weird, 0.0f, middle); - } - - addSurfaceBiome(t, h, coastContinentalness_, erosions_[5], weird, 0.0f, shatteredCoast); - addSurfaceBiome(t, h, nearInlandContinentalness_, erosions_[5], weird, 0.0f, windsweptSavanna); - addSurfaceBiome(t, h, span(midInlandContinentalness_, farInlandContinentalness_), erosions_[5], weird, 0.0f, shattered); - - if (weird.max < 0.0f) { - addSurfaceBiome(t, h, coastContinentalness_, erosions_[6], weird, 0.0f, beach); - } else { - addSurfaceBiome(t, h, coastContinentalness_, erosions_[6], weird, 0.0f, middle); - } - - if (ti == 0) { - addSurfaceBiome(t, h, span(nearInlandContinentalness_, farInlandContinentalness_), erosions_[6], weird, 0.0f, middle); - } - } - } - } - - void addLowSlice(const ClimateRange& weird) { - addSurfaceBiome(fullRange_, fullRange_, coastContinentalness_, span(erosions_[0], erosions_[2]), weird, 0.0f, BiomeId::StonyShore); - addSurfaceBiome(span(temperatures_[1], temperatures_[2]), fullRange_, span(nearInlandContinentalness_, farInlandContinentalness_), erosions_[6], weird, 0.0f, BiomeId::Swamp); - addSurfaceBiome(span(temperatures_[3], temperatures_[4]), fullRange_, span(nearInlandContinentalness_, farInlandContinentalness_), erosions_[6], weird, 0.0f, BiomeId::MangroveSwamp); - - for (int ti = 0; ti < 5; ++ti) { - const ClimateRange t = temperatures_[ti]; - for (int hi = 0; hi < 5; ++hi) { - const ClimateRange h = humidities_[hi]; - const BiomeId middle = pickMiddleBiome(ti, hi, weird); - const BiomeId middleOrBadlands = pickMiddleBiomeOrBadlandsIfHot(ti, hi, weird); - const BiomeId middleOrBadlandsOrSlope = - pickMiddleBiomeOrBadlandsIfHotOrSlopeIfCold(ti, hi, weird); - const BiomeId beach = pickBeachBiome(ti, hi); - const BiomeId windsweptSavanna = - maybePickWindsweptSavannaBiome(ti, hi, weird, middle); - const BiomeId shatteredCoast = pickShatteredCoastBiome(ti, hi, weird); - - addSurfaceBiome(t, h, nearInlandContinentalness_, span(erosions_[0], erosions_[1]), weird, 0.0f, middleOrBadlands); - addSurfaceBiome(t, h, span(midInlandContinentalness_, farInlandContinentalness_), span(erosions_[0], erosions_[1]), weird, 0.0f, middleOrBadlandsOrSlope); - addSurfaceBiome(t, h, nearInlandContinentalness_, span(erosions_[2], erosions_[3]), weird, 0.0f, middle); - addSurfaceBiome(t, h, span(midInlandContinentalness_, farInlandContinentalness_), span(erosions_[2], erosions_[3]), weird, 0.0f, middleOrBadlands); - addSurfaceBiome(t, h, coastContinentalness_, span(erosions_[3], erosions_[4]), weird, 0.0f, beach); - addSurfaceBiome(t, h, span(nearInlandContinentalness_, farInlandContinentalness_), erosions_[4], weird, 0.0f, middle); - addSurfaceBiome(t, h, coastContinentalness_, erosions_[5], weird, 0.0f, shatteredCoast); - addSurfaceBiome(t, h, nearInlandContinentalness_, erosions_[5], weird, 0.0f, windsweptSavanna); - addSurfaceBiome(t, h, span(midInlandContinentalness_, farInlandContinentalness_), erosions_[5], weird, 0.0f, middle); - addSurfaceBiome(t, h, coastContinentalness_, erosions_[6], weird, 0.0f, beach); - if (ti == 0) { - addSurfaceBiome(t, h, span(nearInlandContinentalness_, farInlandContinentalness_), erosions_[6], weird, 0.0f, middle); - } - } - } - } - - void addValleys(const ClimateRange& weird) { - addSurfaceBiome(frozenRange_, fullRange_, coastContinentalness_, span(erosions_[0], erosions_[1]), weird, 0.0f, weird.max < 0.0f ? BiomeId::StonyShore : BiomeId::FrozenRiver); - addSurfaceBiome(unfrozenRange_, fullRange_, coastContinentalness_, span(erosions_[0], erosions_[1]), weird, 0.0f, weird.max < 0.0f ? BiomeId::StonyShore : BiomeId::River); - addSurfaceBiome(frozenRange_, fullRange_, nearInlandContinentalness_, span(erosions_[0], erosions_[1]), weird, 0.0f, BiomeId::FrozenRiver); - addSurfaceBiome(unfrozenRange_, fullRange_, nearInlandContinentalness_, span(erosions_[0], erosions_[1]), weird, 0.0f, BiomeId::River); - addSurfaceBiome(frozenRange_, fullRange_, span(coastContinentalness_, farInlandContinentalness_), span(erosions_[2], erosions_[5]), weird, 0.0f, BiomeId::FrozenRiver); - addSurfaceBiome(unfrozenRange_, fullRange_, span(coastContinentalness_, farInlandContinentalness_), span(erosions_[2], erosions_[5]), weird, 0.0f, BiomeId::River); - addSurfaceBiome(frozenRange_, fullRange_, coastContinentalness_, erosions_[6], weird, 0.0f, BiomeId::FrozenRiver); - addSurfaceBiome(unfrozenRange_, fullRange_, coastContinentalness_, erosions_[6], weird, 0.0f, BiomeId::River); - addSurfaceBiome(span(temperatures_[1], temperatures_[2]), fullRange_, span(inlandContinentalness_, farInlandContinentalness_), erosions_[6], weird, 0.0f, BiomeId::Swamp); - addSurfaceBiome(span(temperatures_[3], temperatures_[4]), fullRange_, span(inlandContinentalness_, farInlandContinentalness_), erosions_[6], weird, 0.0f, BiomeId::MangroveSwamp); - addSurfaceBiome(frozenRange_, fullRange_, span(inlandContinentalness_, farInlandContinentalness_), erosions_[6], weird, 0.0f, BiomeId::FrozenRiver); - - for (int ti = 0; ti < 5; ++ti) { - const ClimateRange t = temperatures_[ti]; - for (int hi = 0; hi < 5; ++hi) { - const ClimateRange h = humidities_[hi]; - const BiomeId middleOrBadlands = pickMiddleBiomeOrBadlandsIfHot(ti, hi, weird); - addSurfaceBiome(t, h, span(midInlandContinentalness_, farInlandContinentalness_), span(erosions_[0], erosions_[1]), weird, 0.0f, middleOrBadlands); - } - } - } - - void addUndergroundBiomes() { - addUndergroundBiome(fullRange_, fullRange_, span(0.8f, 1.0f), fullRange_, fullRange_, 0.0f, BiomeId::DripstoneCaves); - addUndergroundBiome(fullRange_, span(0.7f, 1.0f), fullRange_, fullRange_, fullRange_, 0.0f, BiomeId::LushCaves); - addBottomBiome(fullRange_, fullRange_, fullRange_, span(erosions_[0], erosions_[1]), fullRange_, 0.0f, BiomeId::DeepDark); - } - - BiomeId pickMiddleBiome(int ti, int hi, const ClimateRange& weird) const { - if (weird.max < 0.0f) { - return middleBiomes_[ti][hi]; - } - const BiomeId v = middleBiomesVariant_[ti][hi]; - return v == BiomeId::None ? middleBiomes_[ti][hi] : v; - } - - BiomeId pickMiddleBiomeOrBadlandsIfHot(int ti, int hi, const ClimateRange& weird) const { - return (ti == 4) ? pickBadlandsBiome(hi, weird) : pickMiddleBiome(ti, hi, weird); - } - - BiomeId pickMiddleBiomeOrBadlandsIfHotOrSlopeIfCold(int ti, - int hi, - const ClimateRange& weird) const { - return (ti == 0) ? pickSlopeBiome(ti, hi, weird) - : pickMiddleBiomeOrBadlandsIfHot(ti, hi, weird); - } - - BiomeId maybePickWindsweptSavannaBiome(int ti, - int hi, - const ClimateRange& weird, - BiomeId fallback) const { - if (ti > 1 && hi < 4 && weird.max >= 0.0f) { - return BiomeId::WindsweptSavanna; - } - return fallback; - } - - BiomeId pickShatteredCoastBiome(int ti, int hi, const ClimateRange& weird) const { - const BiomeId base = - (weird.max >= 0.0f) ? pickMiddleBiome(ti, hi, weird) : pickBeachBiome(ti, hi); - return maybePickWindsweptSavannaBiome(ti, hi, weird, base); - } - - BiomeId pickBeachBiome(int ti, int /*hi*/) const { - if (ti == 0) { - return BiomeId::SnowyBeach; - } - if (ti == 4) { - return BiomeId::Desert; - } - return BiomeId::Beach; - } - - BiomeId pickBadlandsBiome(int hi, const ClimateRange& weird) const { - if (hi < 2) { - return (weird.max < 0.0f) ? BiomeId::Badlands : BiomeId::ErodedBadlands; - } - if (hi < 3) { - return BiomeId::Badlands; - } - return BiomeId::WoodedBadlands; - } - - BiomeId pickPlateauBiome(int ti, int hi, const ClimateRange& weird) const { - if (weird.max >= 0.0f) { - const BiomeId v = plateauBiomesVariant_[ti][hi]; - if (v != BiomeId::None) { - return v; - } - } - return plateauBiomes_[ti][hi]; - } - - BiomeId pickPeakBiome(int ti, int hi, const ClimateRange& weird) const { - if (ti <= 2) { - return weird.max < 0.0f ? BiomeId::JaggedPeaks : BiomeId::FrozenPeaks; - } - if (ti == 3) { - return BiomeId::StonyPeaks; - } - return pickBadlandsBiome(hi, weird); - } - - BiomeId pickSlopeBiome(int ti, int hi, const ClimateRange& weird) const { - if (ti >= 3) { - return pickPlateauBiome(ti, hi, weird); - } - if (hi <= 1) { - return BiomeId::SnowySlopes; - } - return BiomeId::Grove; - } - - BiomeId pickShatteredBiome(int ti, int hi, const ClimateRange& weird) const { - const BiomeId candidate = shatteredBiomes_[ti][hi]; - return candidate == BiomeId::None ? pickMiddleBiome(ti, hi, weird) : candidate; - } - - void addSurfaceBiome(const ClimateRange& t, - const ClimateRange& h, - const ClimateRange& c, - const ClimateRange& e, - const ClimateRange& w, - float offset, - BiomeId biome) { - points_.push_back({t, h, c, e, point(0.0f), w, offset, biome}); - points_.push_back({t, h, c, e, point(1.0f), w, offset, biome}); - } - - void addUndergroundBiome(const ClimateRange& t, - const ClimateRange& h, - const ClimateRange& c, - const ClimateRange& e, - const ClimateRange& w, - float offset, - BiomeId biome) { - points_.push_back({t, h, c, e, span(0.2f, 0.9f), w, offset, biome}); - } - - void addBottomBiome(const ClimateRange& t, - const ClimateRange& h, - const ClimateRange& c, - const ClimateRange& e, - const ClimateRange& w, - float offset, - BiomeId biome) { - points_.push_back({t, h, c, e, point(1.1f), w, offset, biome}); - } - - ClimateRange fullRange_{}; - std::array temperatures_{}; - std::array humidities_{}; - std::array erosions_{}; - ClimateRange frozenRange_{}; - ClimateRange unfrozenRange_{}; - ClimateRange mushroomFieldsContinentalness_{}; - ClimateRange deepOceanContinentalness_{}; - ClimateRange oceanContinentalness_{}; - ClimateRange coastContinentalness_{}; - ClimateRange inlandContinentalness_{}; - ClimateRange nearInlandContinentalness_{}; - ClimateRange midInlandContinentalness_{}; - ClimateRange farInlandContinentalness_{}; - - std::array, 2> oceans_{}; - std::array, 5> middleBiomes_{}; - std::array, 5> middleBiomesVariant_{}; - std::array, 5> plateauBiomes_{}; - std::array, 5> plateauBiomesVariant_{}; - std::array, 5> shatteredBiomes_{}; - - std::vector points_; -}; - -inline float peaksAndValleys(float weirdness) { - return -(std::abs(std::abs(weirdness) - 0.6666667f) - 0.33333334f) * 3.0f; -} - -struct ClimateSample { - float temperature; - float humidity; - float continentalness; - float erosion; - float weirdness; - float peaksValleys; -}; - -struct ColumnSample { - int32_t x; - int32_t z; - int32_t height; - BiomeId biome; - ClimateSample climate; -}; - -class WorldGenerator { -public: - explicit WorldGenerator(int64_t seed) - : seed_(seed), - rootFactory_(seed), - noiseLow_(rootFactory_.child("terrain"), "low"), - noiseHigh_(rootFactory_.child("terrain"), "high"), - noiseSelector_(rootFactory_.child("terrain"), "selector"), - noiseDetail_(rootFactory_.child("terrain"), "detail"), - tempNoise_(rootFactory_, "temperature", makeTemperatureParams()), - humidityNoise_(rootFactory_, "vegetation", makeHumidityParams()), - continentalNoise_(rootFactory_, "continentalness", makeContinentalParams()), - erosionNoise_(rootFactory_, "erosion", makeErosionParams()), - ridgeNoise_(rootFactory_, "ridge", makeRidgeParams()) {} - - ColumnSample sampleColumn(int32_t x, int32_t z) const { - const ClimateSample climate = sampleClimate(x, z); - const BiomeId biome = biomeTable_.resolve(climate.temperature, - climate.humidity, - climate.continentalness, - climate.erosion, - 0.0f, - climate.weirdness); - - const double wx = static_cast(x); - const double wz = static_cast(z); - const double low = noiseLow_.noise3D(wx / 80.0, 0.0, wz / 80.0) * 1.6; - const double high = noiseHigh_.noise3D(wx / 60.0, 0.0, wz / 60.0) * 1.6; - const double selectorRaw = noiseSelector_.noise3D(wx / 500.0, 0.0, wz / 500.0); - const double selector = std::clamp((selectorRaw + 1.0) * 0.5, 0.0, 1.0); - const double blended = low * (1.0 - selector) + high * selector; - const double detail = noiseDetail_.noise3D(wx / 25.0, 0.0, wz / 25.0); - - const auto [baseHeight, variation] = biomeHeightParams(biome); - - double h = 63.0 + 2.0 + baseHeight * 20.0 + blended * 16.0 + - (selector - 0.5) * 6.0; - h += detail * (variation * 8.0 + 3.0); - h = std::clamp(h, 5.0, 250.0); - - ColumnSample out{}; - out.x = x; - out.z = z; - out.height = static_cast(std::lround(h)); - out.biome = biome; - out.climate = climate; - return out; - } - - int64_t seed() const { return seed_; } - -private: - static NoiseParameters makeTemperatureParams() { - return NoiseParameters{-10, {1.5, 0.0, 1.0, 0.0, 0.0, 0.0}}; - } - - static NoiseParameters makeHumidityParams() { - return NoiseParameters{-8, {1.0, 1.0, 0.0, 0.0, 0.0, 0.0}}; - } - - static NoiseParameters makeContinentalParams() { - return NoiseParameters{-9, {1.0, 1.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0}}; - } - - static NoiseParameters makeErosionParams() { - return NoiseParameters{-9, {1.0, 1.0, 0.0, 1.0, 1.0}}; - } - - static NoiseParameters makeRidgeParams() { - return NoiseParameters{-7, {1.0, 2.0, 1.0, 0.0, 0.0, 0.0}}; - } - - ClimateSample sampleClimate(int32_t x, int32_t z) const { - // Java biome noise is sampled in quart space + extra scale. - const double qx = static_cast(x) / 16.0; - const double qz = static_cast(z) / 16.0; - - ClimateSample c{}; - c.temperature = static_cast(tempNoise_.getValue(qx, 0.0, qz)); - c.humidity = static_cast(humidityNoise_.getValue(qx, 0.0, qz)); - c.continentalness = static_cast(continentalNoise_.getValue(qx, 0.0, qz)); - c.erosion = static_cast(erosionNoise_.getValue(qx, 0.0, qz)); - c.weirdness = static_cast(ridgeNoise_.getValue(qx, 0.0, qz)); - c.peaksValleys = peaksAndValleys(c.weirdness); - return c; - } - - int64_t seed_; - HashRandomFactory rootFactory_; - OverworldBiomeTable biomeTable_; - - OctaveNoise5 noiseLow_; - OctaveNoise5 noiseHigh_; - OctaveNoise5 noiseSelector_; - OctaveNoise5 noiseDetail_; - - NormalNoise tempNoise_; - NormalNoise humidityNoise_; - NormalNoise continentalNoise_; - NormalNoise erosionNoise_; - NormalNoise ridgeNoise_; -}; - -bool readExact(std::istream& in, uint8_t* dst, size_t n) { - in.read(reinterpret_cast(dst), static_cast(n)); - return in.good() || in.gcount() == static_cast(n); -} - -bool writeExact(std::ostream& out, const uint8_t* src, size_t n) { - out.write(reinterpret_cast(src), static_cast(n)); - return out.good(); -} - -uint16_t loadU16(const uint8_t* p) { - return static_cast(p[0]) | - (static_cast(p[1]) << 8); -} - -uint32_t loadU32(const uint8_t* p) { - return static_cast(p[0]) | - (static_cast(p[1]) << 8) | - (static_cast(p[2]) << 16) | - (static_cast(p[3]) << 24); -} - -uint64_t loadU64(const uint8_t* p) { - return static_cast(loadU32(p)) | - (static_cast(loadU32(p + 4)) << 32); -} - -int32_t loadI32(const uint8_t* p) { return static_cast(loadU32(p)); } -int64_t loadI64(const uint8_t* p) { return static_cast(loadU64(p)); } - -void appendU16(std::vector& out, uint16_t v) { - out.push_back(static_cast(v & 0xFF)); - out.push_back(static_cast((v >> 8) & 0xFF)); -} - -void appendU32(std::vector& out, uint32_t v) { - out.push_back(static_cast(v & 0xFF)); - out.push_back(static_cast((v >> 8) & 0xFF)); - out.push_back(static_cast((v >> 16) & 0xFF)); - out.push_back(static_cast((v >> 24) & 0xFF)); -} - -void appendU64(std::vector& out, uint64_t v) { - appendU32(out, static_cast(v & 0xFFFFFFFFULL)); - appendU32(out, static_cast((v >> 32) & 0xFFFFFFFFULL)); -} - -void appendI32(std::vector& out, int32_t v) { - appendU32(out, static_cast(v)); -} - -void appendI64(std::vector& out, int64_t v) { - appendU64(out, static_cast(v)); -} - -void appendF32(std::vector& out, float v) { - uint32_t bits = 0; - std::memcpy(&bits, &v, sizeof(float)); - appendU32(out, bits); -} - -void writeFrame(std::ostream& out, - uint16_t type, - const std::vector& payload) { - std::vector header; - header.reserve(12); - appendU32(header, kProtocolMagic); - appendU16(header, kProtocolVersion); - appendU16(header, type); - appendU32(header, static_cast(payload.size())); - writeExact(out, header.data(), header.size()); - if (!payload.empty()) { - writeExact(out, payload.data(), payload.size()); - } - out.flush(); -} - -void writeError(std::ostream& out, int32_t code, std::string_view message) { - std::vector payload; - appendI32(payload, code); - appendU32(payload, static_cast(message.size())); - payload.insert(payload.end(), message.begin(), message.end()); - writeFrame(out, kRespError, payload); -} - -} // namespace worldgen - -int main() { - using namespace worldgen; - - std::ios::sync_with_stdio(false); - std::cin.tie(nullptr); - - std::unique_ptr generator; - - while (true) { - uint8_t headerBuf[12]; - if (!readExact(std::cin, headerBuf, sizeof(headerBuf))) { - break; - } - - const uint32_t magic = loadU32(headerBuf); - const uint16_t version = loadU16(headerBuf + 4); - const uint16_t reqType = loadU16(headerBuf + 6); - const uint32_t payloadLen = loadU32(headerBuf + 8); - - if (magic != kProtocolMagic) { - writeError(std::cout, 1001, "bad magic"); - break; - } - if (version != kProtocolVersion) { - writeError(std::cout, 1002, "unsupported protocol version"); - break; - } - - std::vector payload(payloadLen); - if (payloadLen > 0 && !readExact(std::cin, payload.data(), payloadLen)) { - writeError(std::cout, 1003, "truncated payload"); - break; - } - - if (reqType == kReqInit) { - if (payload.size() != 8) { - writeError(std::cout, 2001, "init payload must be 8 bytes"); - continue; - } - const int64_t seed = loadI64(payload.data()); - generator = std::make_unique(seed); - - std::vector out; - appendI32(out, 0); - appendI64(out, seed); - writeFrame(std::cout, static_cast(kRespFlag | kReqInit), out); - continue; - } - - if (reqType == kReqPing) { - std::vector out = payload; - writeFrame(std::cout, static_cast(kRespFlag | kReqPing), out); - continue; - } - - if (reqType == kReqShutdown) { - std::vector out; - appendI32(out, 0); - writeFrame(std::cout, static_cast(kRespFlag | kReqShutdown), out); - break; - } - - if (!generator) { - writeError(std::cout, 2002, "generator not initialized"); - continue; - } - - if (reqType == kReqSampleColumn) { - if (payload.size() != 8) { - writeError(std::cout, 3001, "column payload must be 8 bytes"); - continue; - } - const int32_t x = loadI32(payload.data()); - const int32_t z = loadI32(payload.data() + 4); - const ColumnSample s = generator->sampleColumn(x, z); - - std::vector out; - appendI32(out, s.x); - appendI32(out, s.z); - appendI32(out, s.height); - appendU16(out, static_cast(s.biome)); - appendU16(out, 0); - appendF32(out, s.climate.temperature); - appendF32(out, s.climate.humidity); - appendF32(out, s.climate.continentalness); - appendF32(out, s.climate.erosion); - appendF32(out, s.climate.weirdness); - appendF32(out, s.climate.peaksValleys); - writeFrame(std::cout, static_cast(kRespFlag | kReqSampleColumn), out); - continue; - } - - if (reqType == kReqSampleRegion) { - if (payload.size() != 16) { - writeError(std::cout, 3002, "region payload must be 16 bytes"); - continue; - } - const int32_t x0 = loadI32(payload.data()); - const int32_t z0 = loadI32(payload.data() + 4); - const int32_t width = loadI32(payload.data() + 8); - const int32_t depth = loadI32(payload.data() + 12); - - if (width <= 0 || depth <= 0 || width > 1024 || depth > 1024) { - writeError(std::cout, 3003, "region width/depth out of range"); - continue; - } - - std::vector out; - out.reserve(static_cast(16 + width * depth * 4)); - appendI32(out, x0); - appendI32(out, z0); - appendI32(out, width); - appendI32(out, depth); - - for (int32_t dz = 0; dz < depth; ++dz) { - for (int32_t dx = 0; dx < width; ++dx) { - const ColumnSample s = generator->sampleColumn(x0 + dx, z0 + dz); - appendU16(out, static_cast(s.biome)); - appendU16(out, static_cast(std::clamp(s.height, 0, 65535))); - } - } - - writeFrame(std::cout, static_cast(kRespFlag | kReqSampleRegion), out); - continue; - } - - writeError(std::cout, 4001, "unknown request type"); - } - - return 0; -} - diff --git a/tests/rs_harness.py b/tests/rs_harness.py index 2a11237..0777f21 100644 --- a/tests/rs_harness.py +++ b/tests/rs_harness.py @@ -60,6 +60,9 @@ def create_item(x, y, z, item_name="minecraft:stone", count=1, *a, **k): get_entity=lambda eid: next((e for e in self.entities if getattr(e, "entity_id", None) == eid), None), add_entity=lambda e: self.entities.append(e), + of_kind=lambda kind: [e for e in self.entities + if getattr(e, "kind", None) == kind and getattr(e, "alive", True)], + tick_stamp=0, create_tnt=lambda x, y, z, *a, **k: self.entities.append( SimpleNamespace(kind="tnt", x=x, y=y, z=z, metadata={})), create_item=create_item) @@ -102,5 +105,7 @@ def use(self, x, y, z): return self.engine.on_player_interact(x, y, z, None) def tick(self, n=1): + from world.block_behavior import tick_brewing_stands for _ in range(n): self.engine.tick() + tick_brewing_stands(self.server) diff --git a/tests/test_advancements.py b/tests/test_advancements.py new file mode 100644 index 0000000..a7d9ca8 --- /dev/null +++ b/tests/test_advancements.py @@ -0,0 +1,289 @@ +"""Advancements (1.12+): progress from the inventory, commands, saving, and the 1.21.1 packet layout.""" + +import asyncio +import json +import tempfile +import types +import unittest +from pathlib import Path + +from protocol.data_types import read_varint +from world import advancements as adv +from world.inventory import ItemStack + + +class _FakeConn(types.SimpleNamespace): + async def send_packet(self, packet_id, payload): + self.sent.append((packet_id, payload)) + + +def _conn(items=(), uuid="0f0e0d0c-0b0a-0908-0706-050403020100", pv=767): + slots = [None] * 36 + for i, item in enumerate(items): + slots[i] = ItemStack(item, 1) + return _FakeConn( + username="Steve", uuid=uuid, protocol_version=pv, + inventory_obj=types.SimpleNamespace(slots=slots), + advancement_progress=None, sent=[], + ) + + +def _server(world_dir: Path): + async def _noop(*a, **k): + return None + return types.SimpleNamespace( + world_storage=types.SimpleNamespace(world_dir=world_dir), + broadcast_system_message=lambda *a, **k: None, + ) + + +class ProgressTests(unittest.TestCase): + + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.server = _server(Path(self._tmp.name)) + + def tearDown(self): + self._tmp.cleanup() + + def test_tree_is_connected(self): + self.assertEqual(adv.BY_KEY["story/root"].parent, None) + for a in adv.ADVANCEMENTS: + if a.parent is not None: + self.assertIn(a.parent, adv.BY_KEY) + + def test_inventory_grants_criteria_and_completes(self): + conn = _conn(["minecraft:cobblestone"]) + conn.advancement_progress = {} + changed, completed = adv.check_inventory(conn) + self.assertEqual([a.key for a in changed], ["story/mine_stone"]) + self.assertEqual([a.key for a in completed], ["story/mine_stone"]) + self.assertIn("get_stone", conn.advancement_progress["story/mine_stone"]) + # nothing new the second time + self.assertEqual(adv.check_inventory(conn), ([], [])) + + def test_diamond_branch(self): + conn = _conn(["minecraft:diamond"]) + conn.advancement_progress = {} + _, completed = adv.check_inventory(conn) + keys = {a.key for a in completed} + self.assertIn("story/mine_diamond", keys) + self.assertNotIn("story/shiny_gear", keys) + + def test_obtain_armor_needs_one_piece(self): + conn = _conn(["minecraft:iron_boots"]) + conn.advancement_progress = {} + _, completed = adv.check_inventory(conn) + self.assertIn("story/obtain_armor", [a.key for a in completed]) + + def test_from_until_through(self): + conn = _conn() + conn.advancement_progress = {} + n = asyncio.run(adv.apply(self.server, conn, "grant", "from", "story/upgrade_tools")) + expected = {"story/upgrade_tools"} | {a.key for a in adv.descendants("story/upgrade_tools")} + self.assertEqual(set(conn.advancement_progress), expected) + self.assertIn("story/shiny_gear", expected) + self.assertEqual(n, len(expected)) + conn.advancement_progress = {} + asyncio.run(adv.apply(self.server, conn, "grant", "through", "story/upgrade_tools")) + self.assertEqual(set(conn.advancement_progress), {"story/root", "story/mine_stone", + "story/upgrade_tools"}) + asyncio.run(adv.apply(self.server, conn, "revoke", "everything")) + self.assertEqual(conn.advancement_progress, {}) + + def test_only_criterion_and_revoke(self): + conn = _conn() + conn.advancement_progress = {} + asyncio.run(adv.apply(self.server, conn, "grant", "only", "story/obtain_armor", "iron_boots")) + self.assertEqual(list(conn.advancement_progress["story/obtain_armor"]), ["iron_boots"]) + # one piece of armour is enough (the requirement is an OR of the four pieces) + self.assertTrue(adv.is_complete(conn, "story/obtain_armor")) + asyncio.run(adv.apply(self.server, conn, "revoke", "only", "story/obtain_armor")) + self.assertNotIn("story/obtain_armor", conn.advancement_progress) + + def test_unknown_advancement_is_rejected(self): + conn = _conn() + conn.advancement_progress = {} + with self.assertRaises(ValueError): + asyncio.run(adv.apply(self.server, conn, "grant", "only", "story/nope")) + + def test_save_and_load_round_trip(self): + conn = _conn(["minecraft:stone_pickaxe"]) + conn.advancement_progress = {} + adv.check_inventory(conn) + adv.save(self.server, conn) + path = Path(self._tmp.name) / "advancements" / f"{conn.uuid}.json" + data = json.loads(path.read_text(encoding="utf-8")) + self.assertIn("minecraft:story/upgrade_tools", data) + self.assertTrue(data["minecraft:story/upgrade_tools"]["done"]) + + fresh = _conn(uuid=conn.uuid) + adv.load(self.server, fresh) + self.assertEqual(fresh.advancement_progress, conn.advancement_progress) + + def test_unknown_entries_in_saved_file_are_dropped(self): + cleaned = adv._clean({"minecraft:story/root": {"criteria": {"crafting_table": 5, "bogus": 1}}, + "minecraft:nope/x": {"criteria": {"a": 1}}, "story/mine_stone": "bad"}) + self.assertEqual(cleaned, {"story/root": {"crafting_table": 5}}) + + +def _decode_update(data: bytes) -> dict: + """Read an advancements packet with the 1.21.1 layout; fails if the layout is off.""" + import struct + from protocol.nbt import decode_nbt + from world.inventory import decode_slot_entry + + def string(pos): + n, pos = read_varint(data, pos) + return data[pos:pos + n].decode("utf-8"), pos + n + + def boolean(pos): + return data[pos] != 0, pos + 1 + + reset, pos = boolean(0) + count, pos = read_varint(data, pos) + entries = [] + for _ in range(count): + ident, pos = string(pos) + has_parent, pos = boolean(pos) + parent = None + if has_parent: + parent, pos = string(pos) + has_display, pos = boolean(pos) + display = None + if has_display: + title, pos = decode_nbt(data, pos, with_type=True, with_name=False) + desc, pos = decode_nbt(data, pos, with_type=True, with_name=False) + icon, pos = decode_slot_entry(data, pos) + frame, pos = read_varint(data, pos) + flags, = struct.unpack_from(">i", data, pos) + pos += 4 + background = None + if flags & 1: + background, pos = string(pos) + x, y = struct.unpack_from(">ff", data, pos) + pos += 8 + display = {"title": title, "desc": desc, "icon": icon.item_id, "frame": frame, + "flags": flags, "background": background, "x": x, "y": y} + groups, pos = read_varint(data, pos) + requirements = [] + for _ in range(groups): + k, pos = read_varint(data, pos) + group = [] + for _ in range(k): + name, pos = string(pos) + group.append(name) + requirements.append(group) + telemetry, pos = boolean(pos) + entries.append({"id": ident, "parent": parent, "display": display, + "requirements": requirements, "telemetry": telemetry}) + removed, pos = read_varint(data, pos) + removed_ids = [] + for _ in range(removed): + name, pos = string(pos) + removed_ids.append(name) + progress_count, pos = read_varint(data, pos) + progress = {} + for _ in range(progress_count): + ident, pos = string(pos) + criteria_count, pos = read_varint(data, pos) + criteria = {} + for _ in range(criteria_count): + name, pos = string(pos) + obtained, pos = boolean(pos) + when = None + if obtained: + when, = struct.unpack_from(">q", data, pos) + pos += 8 + criteria[name] = when + progress[ident] = criteria + return {"reset": reset, "entries": entries, "removed": removed_ids, + "progress": progress, "end": pos} + + +class EventTests(unittest.TestCase): + + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.announced = [] + self.server = types.SimpleNamespace( + world_storage=types.SimpleNamespace(world_dir=Path(self._tmp.name)), + broadcast_system_message=lambda text, **k: self.announced.append(text), + ) + adv._pending.clear() + + def tearDown(self): + self._tmp.cleanup() + adv._pending.clear() + + def test_hostile_kill_grants_both(self): + conn = _conn() + conn.advancement_progress = {} + adv.on_mob_killed(conn, types.SimpleNamespace(profile={"category": "hostile"})) + self.assertTrue(adv.is_complete(conn, "adventure/root")) + self.assertTrue(adv.is_complete(conn, "adventure/kill_a_mob")) + + def test_passive_kill_grants_only_the_root(self): + conn = _conn() + conn.advancement_progress = {} + adv.on_mob_killed(conn, types.SimpleNamespace(profile={"category": "passive"})) + self.assertTrue(adv.is_complete(conn, "adventure/root")) + self.assertNotIn("adventure/kill_a_mob", conn.advancement_progress) + + def test_event_before_join_is_ignored(self): + conn = _conn() # no progress loaded yet + adv.trigger(conn, "adventure/root", "killed_something") + self.assertEqual(adv._pending, []) + + def test_flush_sends_once_and_announces_completions(self): + conn = _conn() + conn.advancement_progress = {} + adv.on_mob_killed(conn, types.SimpleNamespace(profile={"category": "hostile"})) + asyncio.run(adv.flush(self.server)) + self.assertEqual(adv._pending, []) + self.assertEqual(len(conn.sent), 1) # one update for both advancements + self.assertEqual(len(self.announced), 2) # both completed now + asyncio.run(adv.flush(self.server)) # nothing pending: nothing sent + self.assertEqual(len(conn.sent), 1) + + def test_enchant_event(self): + conn = _conn() + conn.advancement_progress = {} + adv.trigger(conn, "adventure/enchant_item", "enchanted_item") + self.assertTrue(adv.is_complete(conn, "adventure/enchant_item")) + adv.trigger(conn, "adventure/enchant_item", "enchanted_item") # already done: no new event + self.assertEqual(len(adv._pending), 1) + + +class PacketTests(unittest.TestCase): + + def test_full_packet_round_trips_with_the_1_21_1_layout(self): + conn = _conn() + conn.advancement_progress = {"story/root": {"crafting_table": 1700000000000}} + payload = adv._encode(conn, True, adv.ADVANCEMENTS, [a.key for a in adv.ADVANCEMENTS], + conn.advancement_progress) + got = _decode_update(payload) + self.assertEqual(got["end"], len(payload)) # the layout consumes every byte + self.assertTrue(got["reset"]) + self.assertEqual([e["id"] for e in got["entries"]], [a.id for a in adv.ADVANCEMENTS]) + root = got["entries"][0] + self.assertIsNone(root["parent"]) + self.assertEqual(root["display"]["icon"], "minecraft:grass_block") + self.assertEqual(root["display"]["title"], {"translate": "advancements.story.root.title"}) + self.assertEqual(root["requirements"], [["crafting_table"]]) + self.assertEqual(got["entries"][1]["parent"], "minecraft:story/root") + self.assertEqual(got["progress"]["minecraft:story/root"], {"crafting_table": 1700000000000}) + self.assertEqual(got["progress"]["minecraft:story/mine_stone"], {"get_stone": None}) + + def test_partial_update_is_not_a_reset(self): + conn = _conn() + conn.advancement_progress = {} + payload = adv._encode(conn, False, [adv.BY_KEY["story/mine_stone"]], ["story/mine_stone"], {}) + got = _decode_update(payload) + self.assertFalse(got["reset"]) + self.assertEqual(got["end"], len(payload)) + self.assertEqual(len(got["entries"]), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_biome_native.py b/tests/test_biome_native.py new file mode 100644 index 0000000..aad7901 --- /dev/null +++ b/tests/test_biome_native.py @@ -0,0 +1,70 @@ +"""The native biome sampler (native/vanilla/biome.h) must pick exactly the Python biomes.""" + +import random +import unittest + +from world.biomes import BiomeSampler + + +def _native_or_skip(sampler: BiomeSampler): + if sampler._native_handle() is None: + raise unittest.SkipTest("native engine not available") + + +def _random_terrain(rng: random.Random): + """Columns with random tops (-64..300) so every surface branch is reached.""" + blocks = [[[0] * 16 for _ in range(16)] for _ in range(384)] + for z in range(16): + for x in range(16): + top = rng.randint(-64, 300) + 64 # index of the top block + for y in range(min(top, 384)): + blocks[y][z][x] = 1 + return blocks + + +class NativeBiomesMatchPython(unittest.TestCase): + + def assertSameBiomes(self, sampler, cx, cz, blocks): + native = sampler.build_chunk_biome_sections(cx, cz, blocks) + python = sampler._build_python(cx, cz, blocks) + self.assertEqual(len(native), len(python)) + for section, (a, b) in enumerate(zip(native, python)): + self.assertEqual(a, b, f"section {section} differs") + + def test_random_surfaces_many_seeds(self): + for seed in range(6): + sampler = BiomeSampler(seed) + _native_or_skip(sampler) + rng = random.Random(seed) + for _ in range(3): + cx, cz = rng.randint(-400, 400), rng.randint(-400, 400) + with self.subTest(seed=seed, chunk=(cx, cz)): + self.assertSameBiomes(sampler, cx, cz, _random_terrain(rng)) + + def test_generated_terrain(self): + from world.terrain import TerrainGenerator + for seed in (3, 7): + sampler = BiomeSampler(seed) + _native_or_skip(sampler) + gen = TerrainGenerator(seed) + for cx, cz in ((0, 0), (-5, 9), (40, -33)): + with self.subTest(seed=seed, chunk=(cx, cz)): + self.assertSameBiomes(sampler, cx, cz, gen.generate_chunk(cx, cz)) + + def test_biome_variety(self): + """Across seeds and places the random terrain must reach many biomes, or the + comparison above proves little.""" + seen = set() + for seed in range(4): + sampler = BiomeSampler(seed) + _native_or_skip(sampler) + rng = random.Random(seed) + for _ in range(6): + cx, cz = rng.randint(-2000, 2000), rng.randint(-2000, 2000) + for section in sampler.build_chunk_biome_sections(cx, cz, _random_terrain(rng)): + seen.update(section) + self.assertGreater(len(seen), 10) # the random terrain reaches about a dozen biomes + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_e2e_login.py b/tests/test_e2e_login.py index 6a05b75..f5da9d1 100644 --- a/tests/test_e2e_login.py +++ b/tests/test_e2e_login.py @@ -66,7 +66,7 @@ async def asyncSetUp(self): os.chdir(self.tmp.name) config = dict(DEFAULT_CONFIG) config.update({ - "server-ip": "127.0.0.1", "server-port": 0, "web-admin-enabled": False, + "server-ip": "127.0.0.1", "server-port": 0, "level-seed": "12345", "view-distance": 2, "join-immediate-radius": 1, "motd": "E2E", "plugins-directory": "no-plugins", "mods-directory": "no-mods", "permissions-file": os.path.join(self.tmp.name, "permissions.json"), @@ -208,7 +208,7 @@ async def session_server(reader, writer): os.chdir(self.tmp.name) config = dict(DEFAULT_CONFIG) config.update({ - "server-ip": "127.0.0.1", "server-port": 0, "web-admin-enabled": False, + "server-ip": "127.0.0.1", "server-port": 0, "online-mode": True, "level-seed": "1", "view-distance": 2, "join-immediate-radius": 1, "plugins-directory": "no-plugins", "mods-directory": "no-mods", diff --git a/tests/test_enchanting.py b/tests/test_enchanting.py new file mode 100644 index 0000000..4e0124b --- /dev/null +++ b/tests/test_enchanting.py @@ -0,0 +1,332 @@ +"""Enchanting table, anvil, enchanted books and their slot encoding (1.21.1 rules).""" + +import random +import unittest +from types import SimpleNamespace + +from handlers.play import _handle_click_container +from protocol.data_types import write_byte, write_short, write_varint +from world import enchanting +from world.block_behavior import container_manager +from world.inventory import ItemStack, PlayerInventory, decode_slot_entry, encode_slot_entry + + +class FakeConnection(SimpleNamespace): + async def send_packet(self, packet_id, payload=b""): + self.sent_packets.append((packet_id, payload)) + + +def make_conn(window_id=1, **overrides): + fields = dict(protocol_version=767, inventory_obj=PlayerInventory(), inventory_state_id=0, + sent_packets=[], x=0.0, y=64.0, z=0.0, yaw=0.0, entity_id=1, gamemode="survival", + experience_level=30, experience_total=0, experience_progress=0.0, version_handler=None, + _open_window_id=window_id, _open_container_pos=(0, 64, 0), _open_container_type="block") + fields.update(overrides) + return FakeConnection(**fields) + + +def click(slot, button=0, mode=0): + return b"".join((write_varint(1), write_varint(0), write_short(slot), write_byte(button), + write_varint(mode), write_varint(0), encode_slot_entry(None))) + + +class SlotEncodingTests(unittest.TestCase): + def test_enchanted_sword_round_trips(self): + sword = ItemStack("minecraft:diamond_sword", 1, 0, {"enchantments": {"sharpness": 5, "unbreaking": 3}}) + data = encode_slot_entry(sword) + b"\x00" + item, offset = decode_slot_entry(data, 0) + self.assertEqual(item.nbt, {"enchantments": {"sharpness": 5, "unbreaking": 3}}) + self.assertEqual(offset, len(data) - 1) + + def test_enchanted_book_round_trips_with_damage_first(self): + book = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"mending": 1}}) + item, _ = decode_slot_entry(encode_slot_entry(book), 0) + self.assertEqual(item.item_id, "minecraft:enchanted_book") + self.assertEqual(item.nbt, {"stored_enchantments": {"mending": 1}}) + + def test_plain_items_are_unchanged(self): + self.assertEqual(encode_slot_entry(ItemStack("minecraft:stone", 3)), + enchanting_bytes_without_components(ItemStack("minecraft:stone", 3))) + + +def enchanting_bytes_without_components(item): + from protocol.data_types import write_varint as wv + from world.inventory import item_name_to_protocol_id + return wv(item.count) + wv(item_name_to_protocol_id(item.item_id)) + wv(0) + wv(0) + + +class DataTests(unittest.TestCase): + def test_registry_ids_follow_the_synced_order(self): + self.assertEqual(enchanting.protocol_id("sharpness"), 32) + self.assertEqual(enchanting.name_of_protocol_id(32), "sharpness") + self.assertEqual(enchanting.protocol_id("minecraft:sharpness"), 32) + + def test_levels_and_exclusive_sets(self): + sharp = enchanting.enchantment("sharpness") + self.assertEqual(enchanting.level_cost(sharp, 3, "min_cost"), 23) + self.assertFalse(enchanting.compatible("smite", ["sharpness"])) # damage exclusive set + self.assertTrue(enchanting.compatible("unbreaking", ["sharpness"])) + self.assertFalse(enchanting.compatible("bane_of_arthropods", ["sharpness"])) + + def test_enchantability(self): + self.assertEqual(enchanting.item_enchantability("minecraft:golden_sword"), 22) + self.assertEqual(enchanting.item_enchantability("minecraft:stone"), 0) + self.assertEqual(enchanting.item_enchantability("minecraft:book"), 1) + + def test_accepts_by_item(self): + self.assertTrue(enchanting.accepts("minecraft:diamond_sword", "sharpness")) + self.assertFalse(enchanting.accepts("minecraft:diamond_pickaxe", "sharpness")) + self.assertTrue(enchanting.accepts("minecraft:book", "sharpness")) + + +class OfferTests(unittest.TestCase): + def test_offers_need_items_and_power(self): + self.assertEqual(enchanting.offer_costs(1, "minecraft:stone", 15), [0, 0, 0]) + costs = enchanting.offer_costs(99, "minecraft:diamond_sword", 0) + self.assertEqual(costs[0], max(1, costs[0])) + self.assertLessEqual(costs[0], costs[1]) # first offer is the cheapest + + def test_offers_are_reproducible_and_only_valid_enchantments(self): + first = enchanting.enchanting_offers(12345, "minecraft:diamond_sword", 15) + self.assertEqual(first, enchanting.enchanting_offers(12345, "minecraft:diamond_sword", 15)) + for offer in first: + if offer is None: + continue + for name, level in offer["enchants"]: + entry = enchanting.enchantment(name) + self.assertTrue(entry["in_enchanting_table"] and not entry["treasure"]) + self.assertTrue(enchanting.accepts("minecraft:diamond_sword", name)) + self.assertLessEqual(level, entry["max_level"]) + + def test_books_get_stored_enchantments(self): + item_id, nbt = enchanting.with_enchantments("minecraft:book", {}, [("sharpness", 2)]) + self.assertEqual((item_id, nbt), ("minecraft:enchanted_book", {"stored_enchantments": {"sharpness": 2}})) + item_id, nbt = enchanting.with_enchantments("minecraft:iron_pickaxe", {}, [("efficiency", 3)]) + self.assertEqual((item_id, nbt), ("minecraft:iron_pickaxe", {"enchantments": {"efficiency": 3}})) + + def test_power_counts_bookshelves_with_air_between(self): + shelves = enchanting.bookshelf_states() + shelf = next(iter(shelves)) + blocks = {} + for dx in range(-2, 3): + for dz in range(-2, 3): + if abs(dx) < 2 and abs(dz) < 2: + continue + blocks[(10 + dx, 64, 10 + dz)] = shelf + self.assertEqual(enchanting.bookshelf_power(lambda x, y, z: blocks.get((x, y, z), 0), 10, 64, 10), 15) + blocks[(12, 64, 10)] = 1 # a shelf that is not there any more + blocks[(12, 64, 11)] = 1 + self.assertEqual(enchanting.bookshelf_power(lambda x, y, z: blocks.get((x, y, z), 0), 10, 64, 10), 14) + + +class AnvilTests(unittest.TestCase): + def test_book_adds_enchantment_and_costs_levels(self): + sword = ItemStack("minecraft:diamond_sword", 1, 0, {}) + book = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"sharpness": 3}}) + result, cost = enchanting.anvil_merge(sword, book) + self.assertEqual(result.nbt["enchantments"], {"sharpness": 3}) + self.assertEqual(cost, enchanting.enchantment("sharpness")["anvil_cost"] * 3) + + def test_same_level_books_raise_the_level(self): + sword = ItemStack("minecraft:diamond_sword", 1, 0, {"enchantments": {"sharpness": 2}}) + book = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"sharpness": 2}}) + result, _ = enchanting.anvil_merge(sword, book) + self.assertEqual(result.nbt["enchantments"], {"sharpness": 3}) + + def test_exclusive_enchantments_are_refused(self): + sword = ItemStack("minecraft:diamond_sword", 1, 0, {"enchantments": {"sharpness": 1}}) + book = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"smite": 1}}) + self.assertEqual(enchanting.anvil_merge(sword, book), (None, 0)) + + def test_book_onto_book_stays_a_book(self): + left = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"unbreaking": 1}}) + right = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"mending": 1}}) + result, _ = enchanting.anvil_merge(left, right) + self.assertEqual(result.item_id, "minecraft:enchanted_book") + self.assertEqual(result.nbt["stored_enchantments"], {"unbreaking": 1, "mending": 1}) + + +class WindowTests(unittest.IsolatedAsyncioTestCase): + def setUp(self): + container_manager.containers.clear() + container_manager.block_reader = lambda x, y, z: 0 + + def tearDown(self): + container_manager.containers.clear() + container_manager.block_reader = None + + async def test_enchanting_table_applies_an_offer(self): + from world.enchanting_window import handle_enchant_button + table = container_manager.get_or_create(0, 64, 0, "enchanting_table") + table.items[0] = ItemStack("minecraft:diamond_sword", 1) + table.items[1] = ItemStack("minecraft:lapis_lazuli", 3) + table.enchant_seed = 12345 + conn = make_conn(window_id=1) + from world.enchanting_window import refresh + offers = refresh(conn, table, (0, 64, 0)) and table.enchant_offers + choice = next(i for i, o in enumerate(offers) if o is not None) + expected = offers[choice] + await handle_enchant_button(conn, bytes([1]) + write_varint(choice), None) + result = table.items[0] + self.assertIn(result.item_id, ("minecraft:diamond_sword",)) + for name, level in expected["enchants"]: + self.assertEqual(result.nbt["enchantments"][name.split(":")[-1]], level) + self.assertEqual(table.items[1].count, 3 - expected["lapis"]) + self.assertEqual(conn.experience_level, 30 - expected["levels"]) + self.assertNotEqual(table.enchant_seed, 12345) + + async def test_enchanting_refuses_without_lapis_or_levels(self): + from world.enchanting_window import handle_enchant_button, refresh + table = container_manager.get_or_create(0, 64, 0, "enchanting_table") + table.items[0] = ItemStack("minecraft:diamond_sword", 1) + table.enchant_seed = 12345 + refresh(make_conn(), table, (0, 64, 0)) + choice = next(i for i, o in enumerate(table.enchant_offers) if o is not None) + conn = make_conn(window_id=1, experience_level=0) + await handle_enchant_button(conn, bytes([1]) + write_varint(choice), None) + self.assertEqual(table.items[0].nbt, {}) # no lapis: nothing happens + table.items[1] = ItemStack("minecraft:lapis_lazuli", 3) + await handle_enchant_button(conn, bytes([1]) + write_varint(choice), None) + self.assertEqual(table.items[0].nbt, {}) # no levels: nothing happens + + async def test_anvil_result_is_taken_with_its_inputs_and_levels(self): + anvil = container_manager.get_or_create(0, 64, 0, "anvil") + anvil.items[0] = ItemStack("minecraft:diamond_sword", 1) + anvil.items[1] = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"sharpness": 2}}) + from world.enchanting_window import refresh + refresh(make_conn(), anvil, (0, 64, 0)) + self.assertIsNotNone(anvil.items[2]) + cost = anvil.anvil_cost + conn = make_conn(window_id=1, container_type="block") + await _handle_click_container(conn, click(2, button=0, mode=0), None) # take the result + self.assertEqual(conn.inventory_obj.carried_item.nbt, + {"enchantments": {"sharpness": 2}, "repair_cost": 1}) + self.assertIsNone(anvil.items[0]) + self.assertIsNone(anvil.items[1]) + self.assertEqual(conn.experience_level, 30 - cost) + + async def test_anvil_result_cannot_be_taken_without_levels(self): + anvil = container_manager.get_or_create(0, 64, 0, "anvil") + anvil.items[0] = ItemStack("minecraft:diamond_sword", 1) + anvil.items[1] = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"sharpness": 5}}) + from world.enchanting_window import refresh + refresh(make_conn(), anvil, (0, 64, 0)) + conn = make_conn(window_id=1, experience_level=0) + await _handle_click_container(conn, click(2, button=0, mode=0), None) + self.assertIsNotNone(anvil.items[2]) + self.assertIsNone(conn.inventory_obj.carried_item) + + async def test_number_key_cannot_swap_into_the_anvil_result(self): + anvil = container_manager.get_or_create(0, 64, 0, "anvil") + anvil.items[0] = ItemStack("minecraft:diamond_sword", 1) + anvil.items[1] = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"sharpness": 2}}) + from world.enchanting_window import refresh + refresh(make_conn(), anvil, (0, 64, 0)) + result = anvil.items[2] + conn = make_conn(window_id=1) + conn.inventory_obj.set_slot(0, ItemStack("minecraft:dirt", 4)) + await _handle_click_container(conn, click(2, button=0, mode=2), None) + self.assertIs(anvil.items[2], result) + self.assertEqual(conn.inventory_obj.get_slot(0).item_id, "minecraft:dirt") + + async def test_closing_returns_the_inputs(self): + from world.enchanting_window import return_inputs + table = container_manager.get_or_create(0, 64, 0, "enchanting_table") + table.items[0] = ItemStack("minecraft:diamond_sword", 1) + table.items[1] = ItemStack("minecraft:lapis_lazuli", 2) + conn = make_conn(window_id=1) + return_inputs(conn, 1) + self.assertEqual(table.items[0], None) + self.assertEqual(table.items[1], None) + slots = [conn.inventory_obj.get_slot(i) for i in range(36)] + self.assertTrue(any(s is not None and s.item_id == "minecraft:diamond_sword" for s in slots)) + self.assertTrue(any(s is not None and s.item_id == "minecraft:lapis_lazuli" for s in slots)) + + +if __name__ == "__main__": + unittest.main() + + +class AnvilCostTests(unittest.IsolatedAsyncioTestCase): + """Prior work penalty and the too-expensive switch.""" + + def tearDown(self): + from world.enchanting_window import set_too_expensive_limit + set_too_expensive_limit(True) + container_manager.containers.clear() + + def test_prior_work_penalty_grows_with_each_use(self): + sword = ItemStack("minecraft:diamond_sword", 1, 0, {"enchantments": {"sharpness": 1}}) + book = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"unbreaking": 1}}) + first, cost1 = enchanting.anvil_merge(sword, book) + self.assertEqual(enchanting.repair_cost(first), 1) # max(0, 0) * 2 + 1 + book2 = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"mending": 1}}) + second, cost2 = enchanting.anvil_merge(first, book2) + self.assertEqual(enchanting.repair_cost(second), 3) # max(1, 0) * 2 + 1 + self.assertEqual(cost2, enchanting.enchantment("mending")["anvil_cost"] + 1) # the penalty is added + self.assertEqual(cost1, enchanting.enchantment("unbreaking")["anvil_cost"]) + + def test_limit_refuses_results_from_forty_levels(self): + from world.enchanting_window import refresh, set_too_expensive_limit + anvil = container_manager.get_or_create(0, 64, 0, "anvil") + anvil.items[0] = ItemStack("minecraft:diamond_sword", 1, 0, {"enchantments": {"sharpness": 5}, "repair_cost": 39}) + anvil.items[1] = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"unbreaking": 3}}) + set_too_expensive_limit(True) + refresh(make_conn(), anvil, (0, 64, 0)) + self.assertIsNone(anvil.items[2]) # cost >= 40: refused + set_too_expensive_limit(False) + refresh(make_conn(), anvil, (0, 64, 0)) + self.assertIsNotNone(anvil.items[2]) + self.assertGreaterEqual(anvil.anvil_cost, 40) + + async def test_without_the_limit_the_expensive_result_can_be_taken(self): + from world.enchanting_window import refresh, set_too_expensive_limit + set_too_expensive_limit(False) + anvil = container_manager.get_or_create(0, 64, 0, "anvil") + anvil.items[0] = ItemStack("minecraft:diamond_sword", 1, 0, {"enchantments": {"sharpness": 5}, "repair_cost": 39}) + anvil.items[1] = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"unbreaking": 3}}) + refresh(make_conn(), anvil, (0, 64, 0)) + cost = anvil.anvil_cost + conn = make_conn(window_id=1, experience_level=cost) + await _handle_click_container(conn, click(2, button=0, mode=0), None) + self.assertIsNotNone(conn.inventory_obj.carried_item) + self.assertEqual(conn.experience_level, 0) + + async def test_creative_ignores_the_limit_anyway(self): + from world.enchanting_window import refresh + anvil = container_manager.get_or_create(0, 64, 0, "anvil") + anvil.items[0] = ItemStack("minecraft:diamond_sword", 1, 0, {"enchantments": {"sharpness": 5}, "repair_cost": 39}) + anvil.items[1] = ItemStack("minecraft:enchanted_book", 1, 0, {"stored_enchantments": {"unbreaking": 3}}) + refresh(make_conn(gamemode="creative"), anvil, (0, 64, 0)) + self.assertIsNotNone(anvil.items[2]) + + def test_config_switch_is_read_from_server_properties(self): + import tempfile + from config import load_config + with tempfile.TemporaryDirectory() as d: + path = f"{d}/server.properties" + with open(path, "w", encoding="utf-8") as f: + f.write("anvil-too-expensive-limit=false\n") + self.assertFalse(load_config(path)["anvil-too-expensive-limit"]) + self.assertTrue(load_config(f"{d}/missing.properties")["anvil-too-expensive-limit"]) + + +class PotionContentsTests(unittest.TestCase): + def test_potion_round_trips_with_its_registry_id(self): + from world.potions import protocol_id + bottle = ItemStack("minecraft:splash_potion", 1, 0, {"potion": "long_turtle_master"}) + data = encode_slot_entry(bottle) + b"\x00" + item, offset = decode_slot_entry(data, 0) + self.assertEqual(item.item_id, "minecraft:splash_potion") + self.assertEqual(item.nbt, {"potion": "long_turtle_master"}) + self.assertEqual(offset, len(data) - 1) + self.assertEqual(protocol_id("long_turtle_master"), 20) + + def test_water_bottle_has_the_water_potion(self): + water = ItemStack("minecraft:potion", 1, 0, {"potion": "water"}) + item, _ = decode_slot_entry(encode_slot_entry(water), 0) + self.assertEqual(item.nbt, {"potion": "water"}) + + def test_potions_without_a_known_name_are_plain_items(self): + item, _ = decode_slot_entry(encode_slot_entry(ItemStack("minecraft:potion", 1, 0, {})), 0) + self.assertEqual(item.nbt, {}) diff --git a/tests/test_light_native.py b/tests/test_light_native.py new file mode 100644 index 0000000..33049e8 --- /dev/null +++ b/tests/test_light_native.py @@ -0,0 +1,88 @@ +"""The native chunk light (native/vanilla/light.h) must give exactly the Python result.""" + +import random +import unittest +from array import array +from itertools import chain + +from world import lighting + + +def _native(): + lib = lighting._native_lib() + if lib is None: + raise unittest.SkipTest("native engine not available") + return lib + + +def _random_chunk(rng: random.Random, size: int, height: int = 384): + """A [y][z][x] array with a mix of air, solid, and every kind of state id.""" + air_share = rng.uniform(0.3, 0.9) + chunk = [] + for y in range(height): + layer_air = air_share if y > height // 3 else 0.05 + layer = [] + for _z in range(16): + row = [] + for _x in range(16): + if rng.random() < layer_air: + row.append(0) + elif rng.random() < 0.5: + row.append(rng.randrange(1, min(size, 400))) # common blocks + else: + row.append(rng.randrange(size)) # any state id + layer.append(row) + chunk.append(layer) + return chunk + + +class NativeLightMatchesPython(unittest.TestCase): + + @classmethod + def setUpClass(cls): + _native() + cls.size = len(lighting._light_tables()[0]) + + def assertSameLight(self, blocks): + native = lighting._compute_native(_native(), blocks) + python = lighting._compute_python(blocks) + self.assertEqual(bytes(native[0]), bytes(python[0]), "sky light differs") + self.assertEqual(bytes(native[1]), bytes(python[1]), "block light differs") + + def test_random_chunks(self): + for seed in range(12): + with self.subTest(seed=seed): + self.assertSameLight(_random_chunk(random.Random(seed), self.size)) + + def test_all_air_and_all_solid(self): + self.assertSameLight([[[0] * 16 for _ in range(16)] for _ in range(384)]) + stone = [[[1] * 16 for _ in range(16)] for _ in range(64)] + self.assertSameLight(stone) + + def test_generated_terrain_chunks(self): + from world.terrain import TerrainGenerator + for seed in (1, 2): + gen = TerrainGenerator(seed) + for cx, cz in ((0, 0), (3, -2)): + with self.subTest(seed=seed, chunk=(cx, cz)): + self.assertSameLight(gen.generate_chunk(cx, cz)) + + def test_public_entry_point_matches_python(self): + blocks = _random_chunk(random.Random(99), self.size, height=64) + sky, block_light = lighting.compute_light(blocks) + ref_sky, ref_block = lighting._compute_python(blocks) + self.assertEqual(bytes(sky), bytes(ref_sky)) + self.assertEqual(bytes(block_light), bytes(ref_block)) + + + def test_flat_entry_point_matches(self): + blocks = _random_chunk(random.Random(7), self.size, height=96) + flat = array("H", chain.from_iterable(chain.from_iterable(blocks))) + sky, block_light = lighting.compute_light_flat(flat, 96) + ref_sky, ref_block = lighting._compute_python(blocks) + self.assertEqual(bytes(sky), bytes(ref_sky)) + self.assertEqual(bytes(block_light), bytes(ref_block)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_native_ai.py b/tests/test_native_ai.py index a6e14fe..d95e03d 100755 --- a/tests/test_native_ai.py +++ b/tests/test_native_ai.py @@ -57,5 +57,38 @@ def test_skeleton_keeps_distance_from_close_player(self): ai.shutdown() + def test_batch_gives_the_same_decisions_as_single_requests(self): + import copy + import random + rng = random.Random(3) + players = [DummyPlayer(f"P{i}", rng.uniform(-12, 12), 64.0, rng.uniform(-12, 12)) for i in range(3)] + server = DummyServer(players) + kinds = ["zombie", "skeleton", "pig", "cow", "creeper", "spider"] + mobs = [] + for i in range(24): + mob = MobEntity(500 + i, rng.uniform(-12, 12), 64.0, rng.uniform(-12, 12), + mob_type=kinds[i % len(kinds)]) + mob.age_ticks = 40 + i + mobs.append(mob) + singles = [copy.deepcopy(m) for m in mobs] + batch = copy.deepcopy(mobs) + + ai_single = NativeMobAiEngine() + ai_batch = NativeMobAiEngine() + try: + for mob in singles: + self.assertTrue(ai_single.tick_mob(mob, server)) + done = ai_batch.tick_batch(batch, server) + self.assertEqual(len(done), len(batch)) + for a, b in zip(singles, batch): + self.assertEqual((a.vx, a.vz, a.yaw, a.pitch, a.wander_cooldown, a.aggressive_ticks, a.look_time, + a.target_x, a.target_z, a.target_username), + (b.vx, b.vz, b.yaw, b.pitch, b.wander_cooldown, b.aggressive_ticks, b.look_time, + b.target_x, b.target_z, b.target_username)) + finally: + ai_single.shutdown() + ai_batch.shutdown() + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_native_engine.py b/tests/test_native_engine.py index f6b3a46..f55d016 100644 --- a/tests/test_native_engine.py +++ b/tests/test_native_engine.py @@ -440,16 +440,63 @@ def test_brewing_stand_faces(self): top.items[0] = ItemStack("minecraft:dirt", 1) # not an ingredient: stays top.items[1] = ItemStack("minecraft:nether_wart", 2) side = self.place(-1, 1, 0, "hopper", "hopper", facing="east") - side.items[0] = ItemStack("minecraft:glass_bottle", 4) + side.items[0] = ItemStack("minecraft:potion", 3, 0, {"potion": "water"}) side.items[1] = ItemStack("minecraft:blaze_powder", 1) stand = self.place(0, 1, 0, "brewing_stand", "brewing_stand") self.w.tick(80) - # from above only the ingredient slot; from the side one bottle per empty bottle slot and the fuel + # from above only the ingredient slot; from the side the bottles and the fuel self.assertEqual((stand.items[3].item_id, stand.items[3].count), ("minecraft:nether_wart", 2)) self.assertEqual([stand.items[i].count for i in range(3)], [1, 1, 1]) - self.assertEqual(stand.items[4].item_id, "minecraft:blaze_powder") + self.assertEqual(stand.items[4], None) self.assertEqual(self.count(top, "minecraft:dirt"), 1) - self.assertEqual(self.count(side, "minecraft:glass_bottle"), 1) + self.assertEqual(self.count(side, "minecraft:potion"), 0) + + def test_brewing_makes_awkward_potions_and_state(self): + from world.inventory import ItemStack + from world.block_behavior import BREW_TIME + stand = self.place(0, 1, 0, "brewing_stand", "brewing_stand") + for i in range(3): + stand.items[i] = ItemStack("minecraft:potion", 1, 0, {"potion": "water"}) + stand.items[3] = ItemStack("minecraft:nether_wart", 2) + stand.items[4] = ItemStack("minecraft:blaze_powder", 1) + self.w.tick(BREW_TIME - 1) + self.assertEqual(stand.items[0].nbt, {"potion": "water"}) # not finished yet + self.assertEqual(self.w.props(self.BASE[0], self.BASE[1] + 1, self.BASE[2])["has_bottle_0"], "true") + self.w.tick(2) + self.assertEqual([stand.items[i].nbt["potion"] for i in range(3)], ["awkward"] * 3) + self.assertEqual(stand.items[3].count, 1) # one ingredient per brew + self.assertIsNone(stand.items[4]) # the blaze powder went into the fuel + self.assertEqual(stand.brew_fuel, 19) + self.w.tick(BREW_TIME * 2) # awkward + wart: nothing to brew + self.assertEqual(stand.items[3].count, 1) + self.assertEqual(stand.brew_time, 0) + + def test_brewing_needs_fuel_and_a_valid_mix(self): + from world.inventory import ItemStack + from world.block_behavior import BREW_TIME + stand = self.place(0, 1, 0, "brewing_stand", "brewing_stand") + stand.items[0] = ItemStack("minecraft:potion", 1, 0, {"potion": "awkward"}) + stand.items[3] = ItemStack("minecraft:glowstone_dust", 1) + self.w.tick(5) + self.assertEqual(stand.brew_time, 0) # no fuel: no brew + stand.items[4] = ItemStack("minecraft:blaze_powder", 1) + self.w.tick(BREW_TIME + 1) + self.assertEqual(stand.items[0].nbt["potion"], "awkward") # glowstone does not mix awkward potions + self.assertEqual(stand.items[3].count, 1) # and nothing was used up + self.assertEqual(stand.brew_fuel, 20) # fuel is only spent when a brew starts + stand.items[3] = ItemStack("minecraft:glistering_melon_slice", 1) + self.w.tick(BREW_TIME + 1) + self.assertEqual(stand.items[0].nbt["potion"], "healing") + self.assertIsNone(stand.items[3]) + + def test_brewing_stand_survives_save_and_load(self): + from world.block_behavior import ContainerData + from world.inventory import ItemStack + data = ContainerData(type="brewing_stand") + data.brew_time, data.brew_fuel = 123, 7 + data.items[3] = ItemStack("minecraft:nether_wart", 1) + loaded = ContainerData.from_dict(data.to_dict()) + self.assertEqual((loaded.brew_time, loaded.brew_fuel, loaded.items[3].item_id), (123, 7, "minecraft:nether_wart")) def test_detector_rail_sees_minecarts_in_both_engines(self): from world.inventory import ItemStack @@ -569,3 +616,24 @@ def test_save_and_load(self): loaded = w2.entities[0] self.assertEqual((loaded.variant, loaded.x, loaded.container.items[2].item_id, loaded.container.items[2].count), ("hopper_minecart", 3.5, "minecraft:diamond", 5)) + + +@unittest.skipUnless(HAVE_NATIVE, "native engine not built") +class NativeChunkLimit(unittest.TestCase): + """A tiny chunk mirror (evicted every tick) gives the same circuit results.""" + + def test_wire_across_chunks_with_a_one_chunk_mirror(self): + from world.rs.native import load_library + results = [] + for limit in (256, 1): + w = World(native=True) + load_library().vrs_set_chunk_limit(limit) + for x in range(0, 80, 2): + w.set(x, 64, 0, S("redstone_wire")) + w.set(-1, 64, 0, S("lever", face="floor", facing="north")) + w.set(1, 64, 0, S("redstone_wire")) + w.use(-1, 64, 0) + w.tick(3) + results.append([w.get(x, 64, 0) for x in range(-1, 80)] + [w.get(x, 65, 0) for x in range(-1, 80)]) + load_library().vrs_set_chunk_limit(256) + self.assertEqual(results[0], results[1]) diff --git a/tests/test_spawning.py b/tests/test_spawning.py new file mode 100644 index 0000000..7c18f6c --- /dev/null +++ b/tests/test_spawning.py @@ -0,0 +1,170 @@ +"""Natural spawning and despawning: the light and ground rules and the cycle.""" + +import types +import unittest + +from world import spawning as sp +from world.blocks import AIR, GRASS_BLOCK, STONE, WATER + + +def _passable(block_id): + from world.entities import _is_passable + return _is_passable(block_id) + + +class RuleTests(unittest.TestCase): + + def test_sky_darkness_by_time(self): + self.assertEqual(sp.sky_darkness(6000), 0) + self.assertEqual(sp.sky_darkness(18000), 11) + self.assertEqual(sp.sky_darkness(24000 + 18000), 11) # the day wraps + + def test_brightness_takes_the_larger(self): + self.assertEqual(sp.brightness(3, 15, 0), 15) + self.assertEqual(sp.brightness(3, 15, 11), 4) + self.assertEqual(sp.brightness(9, 2, 11), 9) + + def test_hostile_needs_darkness(self): + ok = lambda light, mob="zombie": sp.can_spawn("hostile", mob, AIR, AIR, STONE, light, 0, 0, _passable) + self.assertTrue(ok(0)) + self.assertTrue(ok(7)) + self.assertFalse(ok(8)) + self.assertFalse(ok(0, mob="pig")) + + def test_passive_needs_grass_and_light(self): + ok = lambda ground, raw: sp.can_spawn("passive", "pig", AIR, AIR, ground, 0, 12, 0, _passable) if raw is None \ + else sp.can_spawn("passive", "pig", AIR, AIR, ground, 0, raw, 0, _passable) + self.assertTrue(ok(GRASS_BLOCK, 9)) + self.assertFalse(ok(GRASS_BLOCK, 8)) + self.assertFalse(ok(STONE, 15)) + + def test_never_in_liquid_or_without_ground(self): + self.assertFalse(sp.can_spawn("hostile", "zombie", WATER, AIR, STONE, 0, 0, 0, _passable)) + self.assertFalse(sp.can_spawn("hostile", "zombie", AIR, AIR, AIR, 0, 0, 0, _passable)) + self.assertFalse(sp.can_spawn("hostile", "zombie", AIR, AIR, None, 0, 0, 0, _passable)) + + +class FlatWorld: + """Stone below y=63, grass at y=63, air above; the same chunk everywhere.""" + + def __init__(self): + self.chunk = [[[STONE] * 16 for _ in range(16)] if y < 127 else + ([[GRASS_BLOCK] * 16 for _ in range(16)] if y == 127 else + [[AIR] * 16 for _ in range(16)]) + for y in range(384)] + + def get_block_at(self, x, y, z): + if y < -64 or y >= 320: + return None + if y < 63: + return STONE + return GRASS_BLOCK if y == 63 else AIR + + def load_generated_chunk(self, cx, cz): + return self.chunk + + +class _Manager: + def __init__(self): + self.created = [] + self.removed = [] + self.mobs = [] + + def of_kind(self, kind): + return list(self.mobs) if kind == "mob" else [] + + def create_mob(self, x, y, z, mob_type="pig"): + mob = types.SimpleNamespace(x=x, y=y, z=z, mob_type=mob_type, entity_id=len(self.created) + 1000, + profile={"category": "hostile" if mob_type in sp.HOSTILE else "passive"}) + self.created.append(mob) + self.mobs.append(mob) + return mob + + def remove_entity(self, entity_id): + self.removed.append(entity_id) + self.mobs = [m for m in self.mobs if m.entity_id != entity_id] + + +def _server(world_time=6000, players=None, difficulty="easy"): + world = FlatWorld() + players = players if players is not None else [ + types.SimpleNamespace(x=0.5, y=64.0, z=0.5, gamemode="survival")] + return types.SimpleNamespace( + world_storage=world, get_block_at=world.get_block_at, + get_online_players=lambda: players, world_time=world_time, + config={"difficulty": difficulty, "spawn-monsters": True, "spawn-animals": True}, + entity_manager=_Manager(), next_entity_id=1, + ) + + +class CycleTests(unittest.TestCase): + + def run_cycles(self, server, cycles=30): + for i in range(cycles): + sp.run_spawning(server, sp.SPAWN_INTERVAL * (i + 1)) + + def test_daytime_spawns_only_animals(self): + server = _server(world_time=6000) + self.run_cycles(server) + kinds = {m.mob_type for m in server.entity_manager.created} + self.assertTrue(kinds, "nothing spawned in daylight") + self.assertTrue(kinds <= set(sp.PASSIVE), kinds) + + def test_night_spawns_hostile_mobs(self): + server = _server(world_time=18000) + self.run_cycles(server) + kinds = {m.mob_type for m in server.entity_manager.created} + self.assertTrue(kinds, "nothing spawned at night") + self.assertTrue(kinds <= set(sp.HOSTILE) | set(sp.PASSIVE)) + self.assertTrue(kinds & set(sp.HOSTILE)) + + def test_peaceful_has_no_hostile_mobs(self): + server = _server(world_time=18000, difficulty="peaceful") + self.run_cycles(server) + self.assertFalse([m for m in server.entity_manager.created if m.mob_type in sp.HOSTILE]) + + def test_nothing_spawns_within_24_blocks(self): + server = _server(world_time=6000) + self.run_cycles(server, cycles=40) + for mob in server.entity_manager.created: + self.assertGreaterEqual(((mob.x - 0.5) ** 2 + (mob.z - 0.5) ** 2) ** 0.5, sp.MIN_DISTANCE - 1) + + def test_caps_per_player(self): + server = _server(world_time=6000) + self.run_cycles(server, cycles=200) + self.assertLessEqual(len(server.entity_manager.created), sp.PASSIVE_CAP) + + def test_spawn_turned_off_by_config(self): + server = _server(world_time=6000) + server.config["spawn-animals"] = False + self.run_cycles(server) + self.assertEqual(server.entity_manager.created, []) + + +class DespawnTests(unittest.TestCase): + + def test_far_mobs_are_removed_near_ones_kept(self): + server = _server() + manager = server.entity_manager + far = manager.create_mob(500.0, 64.0, 500.0, mob_type="pig") + near = manager.create_mob(3.0, 64.0, 3.0, mob_type="pig") + sp.run_despawning(server, sp.DESPAWN_INTERVAL) + self.assertIn(far.entity_id, manager.removed) + self.assertNotIn(near.entity_id, manager.removed) + + def test_hostile_beyond_32_may_go_but_not_always(self): + import random as _random + removed_any = kept_any = False + for seed in range(40): + server = _server() + server.entity_manager.create_mob(60.0, 64.0, 0.0, mob_type="zombie") + sp.run_despawning(server, sp.DESPAWN_INTERVAL + seed * sp.DESPAWN_INTERVAL) + if server.entity_manager.removed: + removed_any = True + else: + kept_any = True + self.assertTrue(removed_any and kept_any) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_web_admin_security.py b/tests/test_web_admin_security.py deleted file mode 100644 index a424d24..0000000 --- a/tests/test_web_admin_security.py +++ /dev/null @@ -1,26 +0,0 @@ -import unittest -from types import SimpleNamespace - -from admin.web import WebAdminServer - - -class WebAdminSecurityTests(unittest.TestCase): - def test_loopback_hosts_are_allowed_by_default(self): - self.assertTrue(WebAdminServer._is_loopback_host("127.0.0.1")) - self.assertTrue(WebAdminServer._is_loopback_host("::1")) - self.assertTrue(WebAdminServer._is_loopback_host("localhost")) - - def test_wildcard_and_remote_hosts_are_rejected(self): - self.assertFalse(WebAdminServer._is_loopback_host("0.0.0.0")) - self.assertFalse(WebAdminServer._is_loopback_host("::")) - self.assertFalse(WebAdminServer._is_loopback_host("192.168.1.20")) - self.assertFalse(WebAdminServer._is_loopback_host("admin.example.com")) - - def test_public_bind_requires_explicit_opt_in(self): - admin = WebAdminServer(SimpleNamespace(), "0.0.0.0", 0) - with self.assertRaisesRegex(ValueError, "web-admin-allow-remote"): - admin.start() - - -if __name__ == "__main__": - unittest.main() \ No newline at end of file diff --git a/tools/gen_enchantment_data.py b/tools/gen_enchantment_data.py new file mode 100644 index 0000000..dbd2b1a --- /dev/null +++ b/tools/gen_enchantment_data.py @@ -0,0 +1,71 @@ +""" +Generate world/data/enchantments.json from the 1.21.1 data the server already ships +(protocol/data/registries_767.json, tags_767.json, items_767.json). + +Each enchantment keeps its registry order (= the numeric id the client assigns), its +cost formulas (cost(level) = base + per_level_above_first * (level - 1)), weight, anvil +cost, the item tags that accept it, and its exclusive set. + +Usage: python3 tools/gen_enchantment_data.py +""" + +import json +from pathlib import Path + +DATA = Path(__file__).resolve().parent.parent / "protocol" / "data" +OUT = Path(__file__).resolve().parent.parent / "world" / "data" / "enchantments.json" + + +def _value(node): + return node["value"] if isinstance(node, dict) and "value" in node else node + + +def main(): + registry = json.loads((DATA / "registries_767.json").read_text(encoding="utf-8"))["minecraft:enchantment"] + tags = json.loads((DATA / "tags_767.json").read_text(encoding="utf-8")) + items = json.loads((DATA / "items_767.json").read_text(encoding="utf-8"))["names"] + ench_tags = tags["minecraft:enchantment"] + item_tags = tags["minecraft:item"] + names = [key.split(":", 1)[1] for key in registry] + + def tag_items(ref: str) -> list[str]: + tag = ref.lstrip("#") + return [items[i].split(":")[-1] if ":" in items[i] else items[i] for i in item_tags.get(tag, [])] + + def tag_enchants(ref: str) -> list[str]: + return [e.split(":", 1)[-1] for e in ench_tags.get(ref.lstrip("#"), [])] + + def cost(node): + value = _value(node) + return [int(value["base"]["value"]), int(value["per_level_above_first"]["value"])] + + out = [] + for index, (key, entry) in enumerate(registry.items()): + v = _value(entry) + name = key.split(":", 1)[1] + supported = _value(v["supported_items"]) + primary = _value(v.get("primary_items", v["supported_items"])) + exclusive = _value(v["exclusive_set"]) if "exclusive_set" in v else None + out.append({ + "id": index, + "name": name, + "max_level": int(_value(v["max_level"])), + "min_cost": cost(v["min_cost"]), + "max_cost": cost(v["max_cost"]), + "weight": int(_value(v["weight"])), + "anvil_cost": int(_value(v["anvil_cost"])), + "supported": tag_items(supported), + "primary": tag_items(primary), + "exclusive": tag_enchants(exclusive) if exclusive else [], + "treasure": name in tag_enchants("#minecraft:treasure"), + "curse": name in tag_enchants("#minecraft:curse"), + "tradeable": name in tag_enchants("#minecraft:tradeable"), + "in_enchanting_table": name in tag_enchants("#minecraft:in_enchanting_table"), + }) + OUT.parent.mkdir(parents=True, exist_ok=True) + OUT.write_text(json.dumps(out, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") + print(f"wrote {len(out)} enchantments to {OUT}") + + +if __name__ == "__main__": + main() diff --git a/watchdog/health_check.py b/watchdog/health_check.py deleted file mode 100755 index 2a6554a..0000000 --- a/watchdog/health_check.py +++ /dev/null @@ -1,177 +0,0 @@ -# ============================================================ -# PyMC - Health Check System -# UDP-based health checking for the watchdog system -# ============================================================ - -from __future__ import annotations - -import asyncio -import json -import logging -import time -from typing import Any - -logger = logging.getLogger("PyMC.健康检查") - - -class HealthCheckServer: - """UDP server for health checking.""" - - def __init__(self, watchdog_manager, port: int): - self.watchdog = watchdog_manager - self.port = port - self._transport: asyncio.DatagramTransport | None = None - self._running = False - - async def start(self): - """Start the health check UDP server.""" - self._running = True - loop = asyncio.get_running_loop() - - class _Protocol(asyncio.DatagramProtocol): - def __init__(self, health_server: HealthCheckServer): - self.health_server = health_server - self.transport = None - - def connection_made(self, transport): - self.transport = transport - - def datagram_received(self, data, addr): - try: - message = data.decode('utf-8', errors='replace') - self.health_server._handle_request(message, addr) - except Exception as e: - logger.debug(f"Health check request error: {e}") - - def error_received(self, exc): - logger.debug(f"Health check protocol error: {exc}") - - try: - transport, protocol = await loop.create_datagram_endpoint( - lambda: _Protocol(self), - local_addr=('0.0.0.0', self.port), - ) - self._transport = transport - logger.info(f"健康检查服务器已启动于 UDP 端口 {self.port}") - except OSError as e: - logger.warning(f"无法启动健康检查服务器于端口 {self.port}: {e}") - - async def stop(self): - """Stop the health check server.""" - self._running = False - if self._transport: - self._transport.close() - self._transport = None - - def _handle_request(self, message: str, addr: tuple): - """Handle an incoming health check request.""" - if message == "PYMC_PING": - # Respond with health status - status = self.watchdog.get_health_status() - response = f"PYMC_HEALTH|{json.dumps(status)}" - if self._transport: - self._transport.sendto(response.encode('utf-8'), addr) - elif message.startswith("PYMC_HB|"): - # Forward to watchdog manager - self.watchdog._handle_incoming_message(message, addr) - - -class HealthCheckClient: - """Client for checking health of partner process.""" - - def __init__(self, port: int, timeout: float = 2.0): - self.port = port - self.timeout = timeout - - async def check_health(self) -> dict | None: - """Send a health check ping and return the response.""" - try: - loop = asyncio.get_running_loop() - - # Create a temporary UDP socket - import socket - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - sock.settimeout(self.timeout) - - # Send ping - await loop.run_in_executor( - None, - lambda: sock.sendto(b"PYMC_PING", ('127.0.0.1', self.port)) - ) - - # Wait for response - try: - data, addr = await asyncio.wait_for( - loop.run_in_executor(None, sock.recvfrom, 4096), - timeout=self.timeout, - ) - message = data.decode('utf-8', errors='replace') - if message.startswith("PYMC_HEALTH|"): - json_str = message[len("PYMC_HEALTH|"):] - return json.loads(json_str) - except asyncio.TimeoutError: - return None - finally: - sock.close() - - except Exception as e: - logger.debug(f"Health check failed: {e}") - return None - - -class HealthMetrics: - """Track health metrics over time.""" - - def __init__(self, max_history: int = 60): - self.max_history = max_history - self.tps_history: list[tuple[float, float]] = [] # (timestamp, tps) - self.player_history: list[tuple[float, int]] = [] # (timestamp, players) - self.memory_history: list[tuple[float, float]] = [] # (timestamp, memory_mb) - self.heartbeat_history: list[tuple[float, bool]] = [] # (timestamp, received) - - def record_tps(self, tps: float): - """Record a TPS measurement.""" - self.tps_history.append((time.time(), tps)) - self._trim(self.tps_history) - - def record_players(self, count: int): - """Record player count.""" - self.player_history.append((time.time(), count)) - self._trim(self.player_history) - - def record_memory(self, mb: float): - """Record memory usage.""" - self.memory_history.append((time.time(), mb)) - self._trim(self.memory_history) - - def record_heartbeat(self, received: bool): - """Record a heartbeat check result.""" - self.heartbeat_history.append((time.time(), received)) - self._trim(self.heartbeat_history) - - def get_average_tps(self, window_seconds: float = 60.0) -> float: - """Get average TPS over the last N seconds.""" - cutoff = time.time() - window_seconds - recent = [(t, v) for t, v in self.tps_history if t >= cutoff] - if not recent: - return 20.0 - return sum(v for _, v in recent) / len(recent) - - def get_tps_trend(self) -> str: - """Get TPS trend (improving/stable/declining).""" - if len(self.tps_history) < 6: - return "stable" - recent = self.tps_history[-6:] - first_half = sum(v for _, v in recent[:3]) / 3 - second_half = sum(v for _, v in recent[3:]) / 3 - diff = second_half - first_half - if diff > 2: - return "improving" - elif diff < -2: - return "declining" - return "stable" - - def _trim(self, history: list): - """Trim history to max length.""" - while len(history) > self.max_history: - history.pop(0) diff --git a/watchdog/network_optimizer.py b/watchdog/network_optimizer.py index 9fdd953..062dafc 100755 --- a/watchdog/network_optimizer.py +++ b/watchdog/network_optimizer.py @@ -7,10 +7,8 @@ import asyncio import logging -import math import time from collections import defaultdict -from typing import Any logger = logging.getLogger("PyMC.network_optimizer") @@ -147,50 +145,6 @@ async def flush_all(self): # Clear the queue for this player self.packet_queues[key] = [] - def optimize_chunk_order(self, conn, chunks: list) -> list: - """ - Sort chunks by distance from player for smoother loading. - - Prioritizes chunks that are: - 1. Closer to the player (Manhattan distance) - 2. In the direction the player is facing - - Args: - conn: Player connection (must have x, z, yaw attributes) - chunks: List of (cx, cz) chunk coordinate tuples - - Returns: - Sorted list of chunk coordinates - """ - if not chunks: - return chunks - - player_cx = int(conn.x) >> 4 - player_cz = int(conn.z) >> 4 - - # Calculate facing direction (normalized) - yaw_rad = math.radians(conn.yaw) - facing_dx = -math.sin(yaw_rad) - facing_dz = math.cos(yaw_rad) - - def chunk_priority(chunk_coord) -> float: - cx, cz = chunk_coord - # Manhattan distance - dist = abs(cx - player_cx) + abs(cz - player_cz) - - # Direction bonus: chunks in the facing direction get priority - dx = cx - player_cx - dz = cz - player_cz - if dx != 0 or dz != 0: - length = math.sqrt(dx * dx + dz * dz) - ndx, ndz = dx / length, dz / length - facing_bonus = ndx * facing_dx + ndz * facing_dz - dist -= facing_bonus * 2.0 - - return dist - - return sorted(chunks, key=chunk_priority) - def should_send_movement(self, conn) -> bool: """ Rate-limit movement updates to other players. @@ -211,36 +165,6 @@ def should_send_movement(self, conn) -> bool: self._last_movement_send[key] = now return True - def get_chunk_send_delay(self, conn) -> float: - """Get the delay between chunk sends for a player.""" - return self.chunk_send_rate - - def should_send_chunk(self, conn) -> bool: - """Check if we should send a chunk to this player now (rate limiting).""" - key = conn.username if conn.username else conn.address - now = time.time() - - last_send = self._last_chunk_send.get(key, 0.0) - if now - last_send < self.chunk_send_rate: - return False - - self._last_chunk_send[key] = now - return True - - def get_stats(self) -> dict: - """Get optimizer statistics.""" - total_queued = sum(len(q) for q in self.packet_queues.values()) - return { - "packets_batched": self._packets_batched, - "packets_sent_directly": self._packets_sent_directly, - "movements_dropped": self._movements_dropped, - "currently_queued": total_queued, - "connections_with_queue": len([q for q in self.packet_queues.values() if q]), - "movement_rate_hz": self._movement_rate_hz, - "batch_interval_ms": self.movement_batch_interval * 1000, - "chunk_send_rate_ms": self.chunk_send_rate * 1000, - } - async def _flush_loop(self): """Periodically flush all queued packets.""" while self._running: @@ -261,71 +185,8 @@ def add(self, conn_key: str, packet_id: int, payload: bytes): """Add a packet to the batch.""" self._batches[conn_key].append((packet_id, payload)) - def get_batch(self, conn_key: str) -> list[tuple[int, bytes]]: - """Get and clear the batch for a connection.""" - return self._batches.pop(conn_key, []) - - def has_batch(self, conn_key: str) -> bool: - """Check if there are queued packets for a connection.""" - return bool(self._batches.get(conn_key)) - def clear(self): """Clear all batches.""" self._batches.clear() -class MovementInterpolator: - """Interpolate between player positions for smooth rendering.""" - - def __init__(self): - self._positions: dict[str, list[tuple[float, float, float, float]]] = {} - # username -> [(x, y, z, timestamp), ...] - - def record_position(self, username: str, x: float, y: float, z: float): - """Record a player position.""" - if username not in self._positions: - self._positions[username] = [] - - self._positions[username].append((x, y, z, time.time())) - - # Keep only recent positions - if len(self._positions[username]) > 10: - self._positions[username] = self._positions[username][-10:] - - def get_interpolated_position(self, username: str, render_time: float) -> tuple[float, float, float] | None: - """ - Get the interpolated position for a given render time. - This helps smooth out movement when updates come at irregular intervals. - """ - positions = self._positions.get(username, []) - if not positions: - return None - - # Find the two positions bracketing the render time - before = None - after = None - - for pos in positions: - if pos[3] <= render_time: - before = pos - elif pos[3] > render_time and after is None: - after = pos - break - - if before is None: - return None - - if after is None: - return (before[0], before[1], before[2]) - - # Linear interpolation - t0 = before[3] - t1 = after[3] - alpha = (render_time - t0) / (t1 - t0) if t1 != t0 else 0.0 - alpha = max(0.0, min(1.0, alpha)) - - x = before[0] + (after[0] - before[0]) * alpha - y = before[1] + (after[1] - before[1]) * alpha - z = before[2] + (after[2] - before[2]) * alpha - - return (x, y, z) diff --git a/watchdog/process_manager.py b/watchdog/process_manager.py index 2bbb6bf..2830791 100755 --- a/watchdog/process_manager.py +++ b/watchdog/process_manager.py @@ -10,7 +10,6 @@ import os import socket import time -from typing import Any logger = logging.getLogger("PyMC.watchdog") @@ -221,38 +220,6 @@ def get_health_status(self) -> dict: "uptime_seconds": time.time() - self.start_time, } - async def graceful_shutdown(self): - """ - Coordinated shutdown - notify partner first. - - Sends PYMC_SHUTDOWN message to partner, waits briefly, - then stops the local watchdog. - """ - logger.info("Initiating coordinated shutdown...") - - # Notify partner to also shut down - try: - loop = asyncio.get_running_loop() - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - message = f"PYMC_SHUTDOWN|{os.getpid()}" - await loop.run_in_executor( - None, - lambda: sock.sendto( - message.encode('utf-8'), - ('127.0.0.1', self._partner_port) - ) - ) - sock.close() - logger.info("Shutdown notification sent to partner") - except Exception as e: - logger.debug(f"Failed to send shutdown notification: {e}") - - # Wait briefly for partner acknowledgment - await asyncio.sleep(2) - - # Both shut down cleanly - await self.stop() - # ============================================================ # Internal implementation # ============================================================ @@ -445,19 +412,3 @@ def _get_memory_usage(self) -> float: pass return 0.0 - def check_partner_health(self) -> dict: - """Check the health of the partner process.""" - if self.partner_pid is None: - return {"status": "no_partner", "alive": False} - - alive = self._is_process_alive(self.partner_pid) - return { - "status": "alive" if alive else "dead", - "pid": self.partner_pid, - "alive": alive, - "missed_heartbeats": self.missed_heartbeats, - "tps": self._partner_tps, - "players": self._partner_players, - "memory_mb": self._partner_memory_mb, - "last_seen": self._partner_last_seen, - } diff --git a/watchdog/restart_handler.py b/watchdog/restart_handler.py deleted file mode 100755 index 39d22c6..0000000 --- a/watchdog/restart_handler.py +++ /dev/null @@ -1,164 +0,0 @@ -# ============================================================ -# PyMC - Restart Handler -# Graceful restart logic for the watchdog system -# ============================================================ - -from __future__ import annotations - -import asyncio -import logging -import os -import signal -import subprocess -import sys -import time -from typing import Any - -logger = logging.getLogger("PyMC.重启处理") - - -class RestartHandler: - """Handles graceful server restart.""" - - def __init__(self, server): - self.server = server - self._restart_pending = False - self._restart_reason = "" - - async def request_restart(self, reason: str = "管理员请求"): - """Request a graceful server restart.""" - if self._restart_pending: - logger.warning("重启已在进行中") - return - - self._restart_pending = True - self._restart_reason = reason - - logger.info(f"正在准备重启: {reason}") - - # 1. Notify all players - self.server.broadcast_system_message(f"[PyMC] 服务器即将重启: {reason}") - - # 2. Save all data - await self._save_all() - - # 3. Wait for pending operations - await asyncio.sleep(3) - - # 4. Disconnect players gracefully - for player in self.server.get_online_players(): - try: - await player.disconnect("服务器重启中...") - except Exception: - pass - - # 5. Start new process - self._start_new_process() - - # 6. Stop current process - await self.server.stop() - - async def _save_all(self): - """Save all world and player data.""" - logger.info("正在保存所有数据...") - try: - self.server.save_all_player_states() - self.server.world_storage.flush() - logger.info("所有数据已保存") - except Exception as e: - logger.error(f"保存数据失败: {e}") - - def _start_new_process(self): - """Start a new server process.""" - try: - main_path = os.path.abspath(os.path.join( - os.path.dirname(__file__), '..', 'main.py' - )) - - cmd = [sys.executable, main_path] - - env = os.environ.copy() - # Preserve watchdog configuration - if hasattr(self.server, 'command_manager'): - env['PYMC_RESTARTED'] = '1' - - process = subprocess.Popen( - cmd, - env=env, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - start_new_session=True, - ) - - logger.info(f"已启动新服务器进程 PID={process.pid}") - - # Notify watchdog about new partner PID - if hasattr(self.server, '_watchdog') and self.server._watchdog: - self.server._watchdog.partner_pid = process.pid - - except Exception as e: - logger.error(f"启动新进程失败: {e}") - - async def emergency_restart(self, reason: str = "紧急重启"): - """Emergency restart without graceful shutdown.""" - logger.critical(f"紧急重启: {reason}") - - try: - # Quick save - self.server.save_all_player_states() - except Exception: - pass - - # Start new process immediately - self._start_new_process() - - # Force stop - os._exit(1) - - -class GracefulShutdown: - """Handles graceful shutdown with timeout.""" - - def __init__(self, server, timeout: float = 30.0): - self.server = server - self.timeout = timeout - self._shutdown_started = False - - async def shutdown(self, reason: str = "正常关闭"): - """Perform graceful shutdown.""" - if self._shutdown_started: - return - self._shutdown_started = True - - logger.info(f"正在关闭服务器: {reason}") - - # Notify players - self.server.broadcast_system_message(f"[PyMC] 服务器正在关闭: {reason}") - - # Save data - try: - self.server.save_all_player_states() - self.server.world_storage.flush() - except Exception as e: - logger.error(f"关闭时保存数据失败: {e}") - - # Disconnect players - for player in list(self.server.get_online_players()): - try: - await player.disconnect("服务器关闭") - except Exception: - pass - - # Stop watchdog - if hasattr(self.server, '_watchdog') and self.server._watchdog: - try: - await self.server._watchdog.graceful_shutdown() - except Exception: - pass - - # Stop server - try: - await asyncio.wait_for(self.server.stop(), timeout=self.timeout) - except asyncio.TimeoutError: - logger.warning("关闭超时,强制退出") - os._exit(0) diff --git a/world/_native_build.py b/world/_native_build.py index 4e2f5f6..903f4a4 100644 --- a/world/_native_build.py +++ b/world/_native_build.py @@ -127,10 +127,10 @@ def build_vanilla_library(force: bool = False) -> str | None: tmp = out_dir / ("tmp_" + str(os.getpid()) + "_" + library.name) for compiler in compilers: if compiler[0] == "cl": - cmd = ["cl", "/nologo", "/O2", "/EHsc", "/std:c++17", "/LD", "/MT", "/DNOMINMAX", + cmd = ["cl", "/nologo", "/O2", "/EHsc", "/std:c++17", "/fp:precise", "/LD", "/MT", "/DNOMINMAX", f"/Fe:{tmp}", str(VANILLA_SOURCE)] else: - cmd = compiler + ["-O2", "-std=c++17", "-shared", "-fPIC", "-fvisibility=hidden", "-o", str(tmp), + cmd = compiler + ["-O2", "-std=c++17", "-ffp-contract=off", "-shared", "-fPIC", "-fvisibility=hidden", "-o", str(tmp), str(VANILLA_SOURCE)] if sys.platform == "win32": cmd[1:1] = ["-static-libgcc", "-static-libstdc++", "-static"] diff --git a/world/_native_downloader.py b/world/_native_downloader.py index 5076e58..4735eb7 100644 --- a/world/_native_downloader.py +++ b/world/_native_downloader.py @@ -15,9 +15,7 @@ import json import logging import os -import platform import stat -import sys import urllib.request import urllib.error from pathlib import Path diff --git a/world/advancements.py b/world/advancements.py new file mode 100644 index 0000000..1efed37 --- /dev/null +++ b/world/advancements.py @@ -0,0 +1,448 @@ +# ============================================================ +# PyMC - advancements (进度, 1.12+) +# +# Since 1.12 the achievements of 1.11 are advancements: a tree of goals +# that each have criteria. A player's progress lives in +# world/advancements/.json (criterion name -> epoch milliseconds when it +# was obtained) and is sent to the client with the "advancements" packet. +# +# Criteria are "inventory_changed": a criterion is obtained when the player's +# inventory holds one of its items. The check runs every few ticks. +# +# The tree is a subset of the vanilla "story" branch. Titles and descriptions +# are vanilla translation keys, so the client shows its own localized text. +# ============================================================ + +from __future__ import annotations + +import json +import logging +from dataclasses import dataclass, field +from pathlib import Path +from time import time + +from protocol.data_types import (write_boolean, write_float, write_int, write_long, + write_string, write_varint) +from protocol.text import encode_component, translate + +logger = logging.getLogger("PyMC.进度") + +NAMESPACE = "minecraft:" +CHECK_INTERVAL = 20 # ticks between inventory checks +PROTOCOL_1_21_1 = 767 # the packet layout below is the 1.21.1 one +FRAME_TASK, FRAME_CHALLENGE, FRAME_GOAL = 0, 1, 2 +_BACKGROUND_STONE = "minecraft:textures/gui/advancements/backgrounds/stone.png" + + +@dataclass(frozen=True) +class Advancement: + key: str # "story/root" (without namespace) + icon: str # item id shown on the tab + criteria: dict # criterion name -> item ids that obtain it + requirements: tuple # AND of OR-groups of criterion names + parent: str | None = None + frame: int = FRAME_TASK + x: float = 0.0 + y: float = 0.0 + background: str | None = None + toast: bool = True + hidden: bool = False + children: list = field(default_factory=list, compare=False) + + @property + def id(self) -> str: + return NAMESPACE + self.key + + @property + def title_key(self) -> str: + return "advancements." + self.key.replace("/", ".") + ".title" + + @property + def description_key(self) -> str: + return "advancements." + self.key.replace("/", ".") + ".description" + + +def _adv(key, icon, criteria, requirements=None, parent=None, **kw) -> Advancement: + if requirements is None: + requirements = tuple((name,) for name in criteria) # every criterion is needed + return Advancement(key, icon, {n: tuple(i) for n, i in criteria.items()}, + tuple(tuple(g) for g in requirements), parent, **kw) + + +ADVANCEMENTS: tuple[Advancement, ...] = ( + _adv("story/root", "minecraft:grass_block", + {"crafting_table": ("minecraft:crafting_table",)}, + parent=None, background=_BACKGROUND_STONE, toast=False, x=0.0, y=0.0), + _adv("story/mine_stone", "minecraft:wooden_pickaxe", + {"get_stone": ("minecraft:cobblestone",)}, + parent="story/root", x=1.0, y=0.0), + _adv("story/upgrade_tools", "minecraft:stone_pickaxe", + {"stone_pickaxe": ("minecraft:stone_pickaxe",)}, + parent="story/mine_stone", x=2.0, y=0.0), + _adv("story/smelt_iron", "minecraft:iron_ingot", + {"iron": ("minecraft:iron_ingot",)}, + parent="story/upgrade_tools", x=3.0, y=0.0), + _adv("story/obtain_armor", "minecraft:iron_chestplate", + {"iron_helmet": ("minecraft:iron_helmet",), + "iron_chestplate": ("minecraft:iron_chestplate",), + "iron_leggings": ("minecraft:iron_leggings",), + "iron_boots": ("minecraft:iron_boots",)}, + requirements=[("iron_helmet", "iron_chestplate", "iron_leggings", "iron_boots")], + parent="story/smelt_iron", x=4.0, y=0.0), + _adv("story/iron_tools", "minecraft:iron_pickaxe", + {"iron_pickaxe": ("minecraft:iron_pickaxe",)}, + parent="story/smelt_iron", x=3.0, y=1.0), + _adv("story/lava_bucket", "minecraft:lava_bucket", + {"lava_bucket": ("minecraft:lava_bucket",)}, + parent="story/smelt_iron", x=3.0, y=-1.0), + _adv("story/mine_diamond", "minecraft:diamond", + {"diamond": ("minecraft:diamond",)}, + parent="story/iron_tools", x=4.0, y=1.0), + _adv("story/shiny_gear", "minecraft:diamond_chestplate", + {"diamond_helmet": ("minecraft:diamond_helmet",), + "diamond_chestplate": ("minecraft:diamond_chestplate",), + "diamond_leggings": ("minecraft:diamond_leggings",), + "diamond_boots": ("minecraft:diamond_boots",)}, + requirements=[("diamond_helmet", "diamond_chestplate", "diamond_leggings", "diamond_boots")], + parent="story/mine_diamond", x=5.0, y=1.0), + # adventure tab: granted by events (see trigger), not by inventory contents + _adv("adventure/root", "minecraft:map", + {"killed_something": ()}, + background="minecraft:textures/gui/advancements/backgrounds/adventure.png", + toast=False, x=0.0, y=0.0), + _adv("adventure/kill_a_mob", "minecraft:iron_sword", + {"killed_mob": ()}, + parent="adventure/root", x=1.0, y=0.0), + _adv("adventure/enchant_item", "minecraft:enchanted_book", + {"enchanted_item": ()}, + parent="adventure/root", x=1.0, y=1.0), +) + +BY_KEY: dict[str, Advancement] = {a.key: a for a in ADVANCEMENTS} +for _a in ADVANCEMENTS: + if _a.parent is not None: + BY_KEY[_a.parent].children.append(_a) + + +def descendants(key: str) -> list[Advancement]: + out, stack = [], list(BY_KEY[key].children) + while stack: + node = stack.pop() + out.append(node) + stack.extend(node.children) + return out + + +def ancestors(key: str) -> list[Advancement]: + out, parent = [], BY_KEY[key].parent + while parent is not None: + out.append(BY_KEY[parent]) + parent = BY_KEY[parent].parent + return out + + +# ------------------------------------------------------------ progress state + +def _clean(raw) -> dict: + """Keep only known advancements and criteria from a saved file.""" + progress: dict[str, dict[str, int]] = {} + if not isinstance(raw, dict): + return progress + for key, entry in raw.items(): + adv = BY_KEY.get(key.removeprefix(NAMESPACE)) + if adv is None or not isinstance(entry, dict): + continue + criteria = entry.get("criteria", {}) + if not isinstance(criteria, dict): + continue + for name, when in criteria.items(): + if name in adv.criteria and isinstance(when, int): + progress.setdefault(adv.key, {})[name] = when + return progress + + +def _path(server, player_uuid) -> Path: + return Path(server.world_storage.world_dir) / "advancements" / f"{player_uuid}.json" + + +def load(server, conn) -> None: + """Read the player's progress into conn.advancement_progress (empty when there is none).""" + progress: dict = {} + try: + path = _path(server, conn.uuid) + if path.exists(): + progress = _clean(json.loads(path.read_text(encoding="utf-8"))) + except (OSError, ValueError) as e: + logger.warning(f"无法读取 {conn.username} 的进度: {e}") + conn.advancement_progress = progress + + +def save(server, conn) -> None: + progress = getattr(conn, "advancement_progress", None) + if progress is None or getattr(conn, "uuid", None) is None: + return + data = {NAMESPACE + key: {"criteria": {name: when for name, when in criteria.items()}, + "done": is_done(BY_KEY[key], criteria)} + for key, criteria in progress.items() if criteria} + path = _path(server, conn.uuid) + try: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8") + tmp.replace(path) + except OSError as e: + logger.warning(f"无法保存 {conn.username} 的进度: {e}") + + +def is_done(adv: Advancement, criteria: dict) -> bool: + return all(any(name in criteria for name in group) for group in adv.requirements) + + +def is_complete(conn, key: str) -> bool: + return is_done(BY_KEY[key], conn.advancement_progress.get(key, {})) + + +def _inventory_items(conn) -> set[str]: + inv = getattr(conn, "inventory_obj", None) + if inv is None: + return set() + return {slot.item_id for slot in inv.slots if slot is not None and not slot.is_empty} + + +def check_inventory(conn) -> tuple[list[Advancement], list[Advancement]]: + """ + Grant the criteria the inventory satisfies. + Returns (advancements whose progress changed, advancements completed now). + """ + progress = conn.advancement_progress + items = _inventory_items(conn) + if not items: + return [], [] + now = int(time() * 1000) + before = {a.key: is_done(a, progress.get(a.key, {})) for a in ADVANCEMENTS} + changed = [] + for adv in ADVANCEMENTS: + criteria = progress.setdefault(adv.key, {}) + added = False + for name, wanted in adv.criteria.items(): + if name not in criteria and any(item in items for item in wanted): + criteria[name] = now + added = True + if added: + changed.append(adv) + for adv in ADVANCEMENTS: + if not progress.get(adv.key): + progress.pop(adv.key, None) + completed = [a for a in changed + if not before[a.key] and is_done(a, progress.get(a.key, {}))] + return changed, completed + + +# ------------------------------------------------------------ packets + +def _encode(conn, reset: bool, advs, progress_keys, progress: dict) -> bytes: + from world.inventory import ItemStack, encode_slot_entry + pv = conn.protocol_version + out = bytearray(write_boolean(reset)) + out += write_varint(len(advs)) + for adv in advs: + out += write_string(adv.id) + if adv.parent is None: + out += write_boolean(False) + else: + out += write_boolean(True) + write_string(NAMESPACE + adv.parent) + out += write_boolean(True) # display info + out += encode_component(translate(adv.title_key), pv) + out += encode_component(translate(adv.description_key), pv) + out += encode_slot_entry(ItemStack(adv.icon, 1)) + out += write_varint(adv.frame) + flags = (1 if adv.background else 0) | (2 if adv.toast else 0) | (4 if adv.hidden else 0) + out += write_int(flags) + if adv.background: + out += write_string(adv.background) + out += write_float(adv.x) + write_float(adv.y) + out += write_varint(len(adv.requirements)) # requirements + for group in adv.requirements: + out += write_varint(len(group)) + for name in group: + out += write_string(name) + out += write_boolean(False) # sendsTelemetryEvent + out += write_varint(0) # removed + out += write_varint(len(progress_keys)) + for key in progress_keys: + adv = BY_KEY[key] + criteria = progress.get(key, {}) + out += write_string(adv.id) + out += write_varint(len(adv.criteria)) + for name in adv.criteria: + out += write_string(name) + when = criteria.get(name) + if when is None: + out += write_boolean(False) + else: + out += write_boolean(True) + write_long(when) + return bytes(out) + + +async def _send(conn, payload: bytes) -> None: + from protocol.packet_map import get_clientbound_packet + pid = get_clientbound_packet(conn.protocol_version, "advancements") + if pid is None or conn.protocol_version != PROTOCOL_1_21_1: + return # other protocol versions are not implemented yet + await conn.send_packet(pid, payload) + + +async def send_full(conn) -> None: + """The whole tree and this player's progress (sent on join).""" + progress = conn.advancement_progress + keys = [a.key for a in ADVANCEMENTS] + await _send(conn, _encode(conn, True, ADVANCEMENTS, keys, progress)) + + +async def send_update(conn, advs) -> None: + """Only the given advancements (after a grant or revoke).""" + if not advs: + return + keys = [a.key for a in advs] + await _send(conn, _encode(conn, False, advs, keys, conn.advancement_progress)) + + +async def on_join(server, conn) -> None: + load(server, conn) + await send_full(conn) + + +def _announce(server, conn, adv: Advancement) -> None: + if adv.hidden: + return + server.broadcast_system_message( + translate("chat.type.advancement.task", conn.username, translate(adv.title_key))) + + +async def tick(server, tick_count: int) -> None: + """Every tick: send the events that happened since the last tick. + Every CHECK_INTERVAL ticks: grant what the inventories already satisfy.""" + await flush(server) + if tick_count % CHECK_INTERVAL: + return + for conn in server.get_online_players(): + if getattr(conn, "advancement_progress", None) is None: + continue + changed, completed = check_inventory(conn) + if not changed: + continue + await send_update(conn, changed) + save(server, conn) + for adv in completed: + _announce(server, conn, adv) + + +# ------------------------------------------------------------ events + +_pending: list[tuple[object, str, bool]] = [] # (conn, advancement key, done before the event) + + +def trigger(conn, key: str, criterion: str) -> None: + """ + An event happened for this player. Safe to call from synchronous game code: + the progress changes now, the client is told by flush() on the next tick. + """ + adv = BY_KEY.get(key) + progress = getattr(conn, "advancement_progress", None) + if adv is None or progress is None or criterion not in adv.criteria: + return + criteria = progress.setdefault(key, {}) + if criterion in criteria: + return + before = is_done(adv, criteria) + criteria[criterion] = int(time() * 1000) + _pending.append((conn, key, before)) + + +async def flush(server) -> None: + """Send the progress changed by trigger() since the last flush, and announce completions.""" + if not _pending: + return + batch = _pending[:] + _pending.clear() + per_conn: dict[int, tuple[object, list[Advancement]]] = {} + completed: list[tuple[object, Advancement]] = [] + for conn, key, before in batch: + if not getattr(conn, "alive", True): + continue + adv = BY_KEY[key] + entry = per_conn.setdefault(id(conn), (conn, [])) + if adv not in entry[1]: + entry[1].append(adv) + if not before and is_done(adv, conn.advancement_progress.get(key, {})): + completed.append((conn, adv)) + for conn, advs in per_conn.values(): + await send_update(conn, advs) + save(server, conn) + for conn, adv in completed: + _announce(server, conn, adv) + + +def on_mob_killed(conn, mob) -> None: + """A player killed a mob (called from the damage code).""" + trigger(conn, "adventure/root", "killed_something") + if getattr(mob, "profile", {}).get("category") == "hostile": + trigger(conn, "adventure/kill_a_mob", "killed_mob") + + +# ------------------------------------------------------------ commands + +def _set(conn, key: str, criteria: list[str] | None, grant: bool) -> None: + """Grant or revoke the criteria (all of the advancement when criteria is None).""" + adv = BY_KEY[key] + progress = conn.advancement_progress + names = list(adv.criteria) if criteria is None else criteria + now = int(time() * 1000) + current = progress.setdefault(key, {}) + for name in names: + if name not in adv.criteria: + continue + if grant: + current.setdefault(name, now) + else: + current.pop(name, None) + if not current: + progress.pop(key, None) + + +async def apply(server, conn, action: str, mode: str, target: str | None = None, + criterion: str | None = None) -> int: + """ + Run one /advancement grant|revoke for one player. Returns how many advancements + changed. Modes: everything, only [criterion], from , until , + through . + """ + grant = action == "grant" + if getattr(conn, "advancement_progress", None) is None: + load(server, conn) + if mode == "everything": + keys = [a.key for a in ADVANCEMENTS] + else: + if target is None or target.removeprefix(NAMESPACE) not in BY_KEY: + raise ValueError(f"未知进度: {target}") + key = target.removeprefix(NAMESPACE) + if mode == "only": + keys = [key] + elif mode == "from": + keys = [key] + [a.key for a in descendants(key)] + elif mode == "until": + keys = [a.key for a in ancestors(key)] + elif mode == "through": + keys = [a.key for a in ancestors(key)] + [key] + else: + raise ValueError(f"未知模式: {mode}") + criteria = [criterion] if criterion and mode == "only" else None + changed = [] + for key in keys: + before = dict(conn.advancement_progress.get(key, {})) + _set(conn, key, criteria if mode == "only" else None, grant) + if conn.advancement_progress.get(key, {}) != before: + changed.append(BY_KEY[key]) + save(server, conn) + await send_update(conn, changed) + return len(changed) diff --git a/world/ai_native.py b/world/ai_native.py index 4cc47b2..4dd01ed 100755 --- a/world/ai_native.py +++ b/world/ai_native.py @@ -16,6 +16,8 @@ logger = logging.getLogger("pymc.ai_native") TICK_COMMAND = b"T" +BATCH_COMMAND = b"B" +MOB_RECORD_FORMAT = "<8i11d" REQUEST_HEADER_FORMAT = "<8i11dI" PLAYER_FORMAT = "<3dB" RESPONSE_HEADER_FORMAT = " bool: - if mob.mob_type not in MOB_TYPE_IDS: - return False - if not self.available: - self._start_process() - if not self.available: - return False - - players, players_payload = self._online_players(server) - has_target = int(mob.target_x is not None and mob.target_z is not None) - target_x = float(mob.target_x) if mob.target_x is not None else 0.0 - target_y = float(mob.target_y) if mob.target_y is not None else 0.0 - target_z = float(mob.target_z) if mob.target_z is not None else 0.0 - - request = bytearray(TICK_COMMAND) - request.extend(struct.pack( - REQUEST_HEADER_FORMAT, + @staticmethod + def _mob_record(mob) -> bytes: + """The fields of one mob (what a single 'T' request sends before the player list).""" + return struct.pack( + MOB_RECORD_FORMAT, MOB_TYPE_IDS[mob.mob_type], int(mob.entity_id), int(mob.age_ticks), @@ -258,7 +248,7 @@ def tick_mob(self, mob, server) -> bool: int(mob.attack_cooldown), int(mob.aggressive_ticks), int(mob.look_time), - has_target, + int(mob.target_x is not None and mob.target_z is not None), float(mob.x), float(mob.y), float(mob.z), @@ -267,64 +257,106 @@ def tick_mob(self, mob, server) -> bool: float(mob.vx), float(mob.vy), float(mob.vz), - target_x, - target_y, - target_z, - len(players), - )) + float(mob.target_x) if mob.target_x is not None else 0.0, + float(mob.target_y) if mob.target_y is not None else 0.0, + float(mob.target_z) if mob.target_z is not None else 0.0, + ) + + def _ready(self, server) -> bool: + if not self.available: + self._start_process() + if not self.available: + return False + return True + + def tick_mob(self, mob, server) -> bool: + """One mob (the 'T' request). Prefer tick_batch(): one round trip for all mobs.""" + if mob.mob_type not in MOB_TYPE_IDS or not self._ready(server): + return False + players, players_payload = self._online_players(server) + request = bytearray(TICK_COMMAND) + request.extend(self._mob_record(mob)) + request.extend(struct.pack(" 0 + + def tick_batch(self, mobs, server) -> set: + """All mobs in one round trip ('B': players once, one reply per mob). + Returns the mobs whose replies were applied; the rest run the Python AI.""" + eligible = [mob for mob in mobs if mob.mob_type in MOB_TYPE_IDS] + if not eligible or not self._ready(server): + return set() + players, players_payload = self._online_players(server) + request = bytearray(BATCH_COMMAND) + request.extend(struct.pack(" int: + """Send a request and apply one reply per mob. Returns how many replies were applied.""" + applied = 0 try: self._process.stdin.write(request) self._process.stdin.flush() - - header = self._read_exact(4) - payload_size = struct.unpack(RESPONSE_HEADER_FORMAT, header)[0] - if payload_size != RESPONSE_SIZE: - raise RuntimeError(f"原生 AI 响应长度异常: {payload_size}") - payload = self._read_exact(payload_size) - ( - ok, - vx, - vz, - yaw, - pitch, - wander_cooldown, - aggressive_ticks, - look_time, - out_has_target, - out_target_x, - out_target_y, - out_target_z, - target_player_index, - ) = struct.unpack(RESPONSE_FORMAT, payload) - if not ok: - return False - - mob.vx = vx - mob.vz = vz - mob.yaw = yaw - mob.pitch = pitch - mob.wander_cooldown = max(0, int(wander_cooldown)) - mob.aggressive_ticks = max(0, int(aggressive_ticks)) - mob.look_time = max(0, int(look_time)) - if out_has_target: - mob.target_x = out_target_x - mob.target_y = out_target_y - mob.target_z = out_target_z - else: - mob.target_x = mob.target_y = mob.target_z = None - if 0 <= target_player_index < len(players): - mob.target_username = players[target_player_index].username - elif mob.profile.get("category") == "hostile": - mob.target_username = None - return True - + for mob in mobs: + header = self._read_exact(4) + payload_size = struct.unpack(RESPONSE_HEADER_FORMAT, header)[0] + if payload_size != RESPONSE_SIZE: + raise RuntimeError(f"原生 AI 响应长度异常: {payload_size}") + payload = self._read_exact(payload_size) + if self._apply_response(mob, payload, players): + applied += 1 + if done is not None: + done.add(id(mob)) except Exception as e: logger.warning("原生 AI tick 失败,回退到 Python AI: %s", e) self.shutdown() self._disabled = True + return applied + + @staticmethod + def _apply_response(mob, payload, players) -> bool: + ( + ok, + vx, + vz, + yaw, + pitch, + wander_cooldown, + aggressive_ticks, + look_time, + out_has_target, + out_target_x, + out_target_y, + out_target_z, + target_player_index, + ) = struct.unpack(RESPONSE_FORMAT, payload) + if not ok: return False + mob.vx = vx + mob.vz = vz + mob.yaw = yaw + mob.pitch = pitch + mob.wander_cooldown = max(0, int(wander_cooldown)) + mob.aggressive_ticks = max(0, int(aggressive_ticks)) + mob.look_time = max(0, int(look_time)) + if out_has_target: + mob.target_x = out_target_x + mob.target_y = out_target_y + mob.target_z = out_target_z + else: + mob.target_x = mob.target_y = mob.target_z = None + if 0 <= target_player_index < len(players): + mob.target_username = players[target_player_index].username + elif mob.profile.get("category") == "hostile": + mob.target_username = None + return True def shutdown(self): if getattr(self, "_process", None): diff --git a/world/biomes.py b/world/biomes.py index 1838c56..a3e03b7 100755 --- a/world/biomes.py +++ b/world/biomes.py @@ -108,13 +108,24 @@ def _biome_entry(temperature: float, downfall: float, BIOME_ID_TO_NAME = {index: name for name, index in BIOME_NAME_TO_ID.items()} -def build_biome_registry_entries() -> OrderedDict: - return BIOME_REGISTRY.copy() +def _noise_params(sampler: "BiomeSampler") -> list[float]: + """Noise tables of the seven samplers, in the layout vrs_biome_create reads.""" + out: list[float] = [] + for noise in (sampler.temperature_noise, sampler.humidity_noise, sampler.continental_noise, + sampler.erosion_noise, sampler.weirdness_noise, sampler.swamp_noise, + sampler.mushroom_noise): + out += [float(len(noise.noise_layers)), float(noise.persistence), float(noise.lacunarity), + float(noise._max_value)] + for layer in noise.noise_layers: + out += [layer.x_offset, layer.y_offset, layer.z_offset] + out += [float(v) for v in layer.perm[:512]] + return out class BiomeSampler: def __init__(self, seed: int = 0): self.seed = seed + self._native = None self.temperature_noise = OctaveNoise(seed + 11, octaves=3, persistence=0.5, lacunarity=2.0) self.humidity_noise = OctaveNoise(seed + 12, octaves=3, persistence=0.5, lacunarity=2.0) self.continental_noise = OctaveNoise(seed + 13, octaves=3, persistence=0.5, lacunarity=2.0) @@ -254,8 +265,50 @@ def sample_biome(self, world_x: int, world_y: int, world_z: int, return "minecraft:dripstone_caves" return surface_biome + def _native_handle(self): + """The native sampler built from this sampler's noise tables, or None.""" + if self._native is None: + self._native = False + try: + from .rs.native import load_library + lib = load_library() + except Exception: + lib = None + if lib is not None: + import ctypes + params = _noise_params(self) + array = (ctypes.c_double * len(params))(*params) + names = "\n".join(BIOME_ID_TO_NAME[i] for i in range(len(BIOME_ID_TO_NAME))) + handle = lib.vrs_biome_create(array, len(params), names.encode("utf-8")) + if handle: + self._native = (lib, handle) + return self._native or None + + def __del__(self): + native = getattr(self, "_native", None) + if native: + native[0].vrs_biome_destroy(native[1]) + def build_chunk_biome_sections(self, chunk_x: int, chunk_z: int, chunk_blocks: list[list[list[int]]]) -> list[list[int]]: + native = self._native_handle() + if native is not None: + return self._build_native(native, chunk_x, chunk_z, chunk_blocks) + return self._build_python(chunk_x, chunk_z, chunk_blocks) + + def _build_native(self, native, chunk_x: int, chunk_z: int, + chunk_blocks: list[list[list[int]]]) -> list[list[int]]: + import ctypes + from .fastpack import column_heights + lib, handle = native + heights = column_heights(chunk_blocks, None) + column = (ctypes.c_int32 * 256)(*heights) + out = (ctypes.c_int32 * (NUM_SECTIONS * 64))() + lib.vrs_biome_sections(handle, chunk_x, chunk_z, column, out) + return [list(out[s * 64:(s + 1) * 64]) for s in range(NUM_SECTIONS)] + + def _build_python(self, chunk_x: int, chunk_z: int, + chunk_blocks: list[list[list[int]]]) -> list[list[int]]: base_x = chunk_x * 16 base_z = chunk_z * 16 surface_heights = [[MIN_Y for _ in range(16)] for _ in range(16)] diff --git a/world/block_behavior.py b/world/block_behavior.py index d803317..afcfc3d 100755 --- a/world/block_behavior.py +++ b/world/block_behavior.py @@ -37,20 +37,10 @@ import os import random from pathlib import Path -from typing import Optional from dataclasses import dataclass, field -from .blocks import ( - AIR, STONE, GRANITE, DIORITE, ANDESITE, GRASS_BLOCK, DIRT, - COBBLESTONE, OAK_PLANKS, GLASS, SAND, OAK_LOG, TORCH, - BEDROCK, WATER, LAVA, CHEST, CRAFTING_TABLE, FURNACE, - FARMLAND, ANVIL, ENDER_CHEST, CAKE, OAK_DOOR, IRON_DOOR, - OAK_SIGN, OAK_TRAPDOOR, IRON_TRAPDOOR, TRAPPED_CHEST, - BLAST_FURNACE, REDSTONE_TORCH, CACTUS, WHITE_BED, - OBSIDIAN, -) from .chunk_io import STATE_ID_TO_BLOCK -from .inventory import ItemStack, encode_slot_entry +from .inventory import ItemStack logger = logging.getLogger("PyMC.方块行为") @@ -292,71 +282,6 @@ def get_block_tier_required(block_name: str) -> str | None: return None -def calculate_break_time(block_name: str, tool_item: ItemStack | None, - in_water: bool = False, on_ground: bool = True) -> float: - """ - Calculate the time in seconds to break a block. - - Args: - block_name: The block being mined - tool_item: The tool being used (or None for bare hands) - in_water: Whether the player is in water (5x slower) - on_ground: Whether the player is on ground (affects mining) - - Returns: - Time in seconds to break the block, or -1 if unbreakable - """ - hardness = get_block_hardness(block_name) - if hardness < 0: - return -1.0 # Unbreakable - - preferred_tool = get_block_tool(block_name) - tier_required = get_block_tier_required(block_name) - - # Base speed - if hardness == 0: - return 0.0 - - speed_multiplier = 1.0 - - # Tool bonus - if tool_item is not None and not tool_item.is_empty: - tool_type = tool_item.get_tool_type() - tool_tier = tool_item.get_tool_tier() - - if tool_type == preferred_tool: - # Correct tool: apply speed bonus - speed_multiplier = tool_item.get_mining_speed() - - # Check tier requirement - if tier_required is not None: - tool_tier_level = _TIER_ORDER.get(tool_tier, 0) if tool_tier else 0 - required_tier_level = _TIER_ORDER.get(tier_required, 0) - if tool_tier_level < required_tier_level: - # Can't mine with this tier - very slow - speed_multiplier = 1.0 - elif tool_type is not None: - # Wrong tool type but still a tool - speed_multiplier = 1.0 - - # Calculate break time - # Formula: break_time = hardness * 1.5 / speed_multiplier (simplified vanilla) - if speed_multiplier > 1.0: - break_time = hardness * 1.5 / speed_multiplier - else: - break_time = hardness * 5.0 # Without correct tool, 5x penalty - - # Water penalty - if in_water: - break_time *= 5.0 - - # Not on ground penalty (slight) - if not on_ground: - break_time *= 1.5 - - return max(0.05, break_time) - - def _harvest_tools() -> dict[str, frozenset[int]]: """Blocks that need the correct tool for drops -> protocol ids of the tools that work.""" global _HARVEST_TOOLS @@ -656,20 +581,13 @@ async def on_place(conn, server, x: int, y: int, z: int, """ return True - @staticmethod - async def on_break(conn, server, x: int, y: int, z: int) -> list[ItemStack]: - """Called when a block is broken. Return list of drops.""" - return [] - @staticmethod async def on_step_on(conn, server, x: int, y: int, z: int) -> None: """Called when an entity steps on this block.""" - pass @staticmethod async def on_projectile_hit(conn, server, x: int, y: int, z: int) -> None: """Called when a projectile hits this block.""" - pass @staticmethod def is_solid() -> bool: @@ -707,6 +625,11 @@ class ContainerData: burn_time: int = 0 # Remaining fuel burn time cook_time: int = 0 # Current cook progress cook_time_total: int = 0 # Total cook time for current recipe + brew_time: int = 0 # Brewing stand: ticks left in the current brew + brew_fuel: int = 0 # Brewing stand: brew fuel units left (one blaze powder = 20) + enchant_seed: int = 0 # Enchanting table: seed of the offers (changes after each enchant) + enchant_offers: list = field(default_factory=list) # Enchanting table: current offers (not saved) + anvil_cost: int = 0 # Anvil: levels the current result costs (not saved) def __post_init__(self): if not self.items: @@ -722,6 +645,13 @@ def __post_init__(self): self.items = [None] * 5 elif self.type == "brewing_stand": self.items = [None] * 5 # 0-2 bottles, 3 ingredient, 4 blaze powder + elif self.type == "enchanting_table": + self.items = [None] * 2 # 0 item, 1 lapis lazuli + if not self.enchant_seed: + import random as _random + self.enchant_seed = _random.getrandbits(31) + elif self.type == "anvil": + self.items = [None] * 3 # 0 left, 1 right, 2 result elif self.type == "dropper" or self.type == "dispenser": self.items = [None] * 9 else: @@ -737,6 +667,9 @@ def to_dict(self) -> dict: "burn_time": self.burn_time, "cook_time": self.cook_time, "cook_time_total": self.cook_time_total, + "brew_time": self.brew_time, + "brew_fuel": self.brew_fuel, + "enchant_seed": self.enchant_seed, } @classmethod @@ -750,6 +683,9 @@ def from_dict(cls, data: dict) -> 'ContainerData': container.burn_time = int(data.get("burn_time", 0)) container.cook_time = int(data.get("cook_time", 0)) container.cook_time_total = int(data.get("cook_time_total", 0)) + container.brew_time = int(data.get("brew_time", 0)) + container.brew_fuel = int(data.get("brew_fuel", 0)) + container.enchant_seed = int(data.get("enchant_seed", 0)) return container @@ -1108,6 +1044,137 @@ def is_interactive() -> bool: return True +# -------------------------------------------------- +# Brewing (BrewingStandBlockEntity / PotionBrewing) +# -------------------------------------------------- +# +# A potion is an item (minecraft:potion / splash_potion / lingering_potion) whose +# nbt "potion" names its effect: "water", "awkward", "healing", "long_swiftness", +# "strong_healing", ... Only the common base-potion mixes are listed here; the +# potion's appearance and effect are not sent to clients or applied yet. + +BREW_TIME = 400 +BREW_FUEL_PER_POWDER = 20 +POTION_ITEMS = {"minecraft:potion": "potion", "minecraft:splash_potion": "splash", + "minecraft:lingering_potion": "lingering"} +_POTION_OF_KIND = {"potion": "minecraft:potion", "splash": "minecraft:splash_potion", + "lingering": "minecraft:lingering_potion"} +_AWKWARD_MIXES = { + "glistering_melon_slice": "healing", "sugar": "swiftness", "rabbit_foot": "leaping", + "blaze_powder": "strength", "golden_carrot": "night_vision", "pufferfish": "water_breathing", + "magma_cream": "fire_resistance", "spider_eye": "poison", "turtle_helmet": "turtle_master", + "phantom_membrane": "slow_falling", "ghast_tear": "regeneration", +} +_STRONG_OK = {"healing", "swiftness", "leaping", "strength", "poison", "regeneration", "turtle_master"} +_LONG_OK = {"night_vision", "invisibility", "leaping", "fire_resistance", "swiftness", "slowness", + "water_breathing", "poison", "regeneration", "strength", "weakness", "turtle_master", "slow_falling"} +_CORRUPT = {"swiftness": "slowness", "healing": "harming", "night_vision": "invisibility"} +BREWING_INGREDIENTS = {"minecraft:" + n for n in ( + "nether_wart", "redstone", "glowstone_dust", "fermented_spider_eye", "gunpowder", "dragon_breath", "sugar", + "rabbit_foot", "glistering_melon_slice", "spider_eye", "pufferfish", "magma_cream", "golden_carrot", + "blaze_powder", "ghast_tear", "turtle_helmet", "phantom_membrane", "breeze_rod", "slime_block", "cobweb", + "stone")} + + +def potion_of(item) -> tuple[str, str] | None: + """(kind, effect) of a potion item, or None.""" + if item is None or item.is_empty or item.item_id not in POTION_ITEMS: + return None + return POTION_ITEMS[item.item_id], str((item.nbt or {}).get("potion", "water")) + + +def mix_potion(kind: str, effect: str, ingredient: str) -> tuple[str, str] | None: + """PotionBrewing.mix: the potion that ingredient turns (kind, effect) into, or None.""" + ingredient = ingredient.split(":")[-1] + if kind == "potion" and effect == "water" and ingredient == "nether_wart": + return ("potion", "awkward") + if ingredient == "gunpowder" and kind == "potion": + return ("splash", effect) + if ingredient == "dragon_breath" and kind == "splash": + return ("lingering", effect) + prefix, base = ("strong_", effect[7:]) if effect.startswith("strong_") else \ + (("long_", effect[5:]) if effect.startswith("long_") else ("", effect)) + if effect == "awkward" and ingredient in _AWKWARD_MIXES: + return (kind, _AWKWARD_MIXES[ingredient]) + if ingredient == "glowstone_dust" and not prefix and base in _STRONG_OK: + return (kind, "strong_" + base) + if ingredient == "redstone" and not prefix and base in _LONG_OK: + return (kind, "long_" + base) + if ingredient == "fermented_spider_eye" and base in _CORRUPT: + return (kind, prefix + _CORRUPT[base]) + return None + + +def _potion_stack(kind: str, effect: str): + from .inventory import ItemStack + return ItemStack(_POTION_OF_KIND[kind], 1, 0, {"potion": effect}) + + +def brewing_mixes(container) -> list: + """Bottle slots that the ingredient in slot 3 would change now: [(slot, kind, effect)].""" + ingredient = container.items[3] + if ingredient is None or ingredient.is_empty: + return [] + out = [] + for slot in (0, 1, 2): + potion = potion_of(container.items[slot]) + if potion is None: + continue + result = mix_potion(potion[0], potion[1], ingredient.item_id) + if result is not None: + out.append((slot, result[0], result[1])) + return out + + +def brewing_can_place(container, slot: int, item_id: str) -> bool: + """BrewingStandBlockEntity.canPlaceItem.""" + if slot == 3: + return item_id in BREWING_INGREDIENTS + if slot == 4: + return item_id == "minecraft:blaze_powder" + if slot in (0, 1, 2): + current = container.items[slot] + return item_id in POTION_ITEMS and (current is None or current.is_empty) + return False + + +def brewing_tick(container) -> bool: + """One game tick of a brewing stand. Returns True when a brew finished.""" + items = container.items + if container.brew_fuel <= 0 and len(items) > 4 and items[4] is not None and not items[4].is_empty \ + and items[4].item_id == "minecraft:blaze_powder": + container.brew_fuel = BREW_FUEL_PER_POWDER + items[4].count -= 1 + if items[4].count <= 0: + items[4] = None + mixes = brewing_mixes(container) + can_brew = bool(mixes) + finished = False + if container.brew_time > 0: + container.brew_time -= 1 + if container.brew_time == 0 and can_brew: + for slot, kind, effect in mixes: + items[slot] = _potion_stack(kind, effect) + items[3].count -= 1 + if items[3].count <= 0: + items[3] = None + finished = True + elif not can_brew: + container.brew_time = 0 + elif can_brew and container.brew_fuel > 0: + container.brew_fuel -= 1 + container.brew_time = BREW_TIME + return finished + + +def brewing_bottle_state(container, state: int) -> int: + """has_bottle_0..2 follow the bottle slots.""" + from .rs.core import with_props + changes = {f"has_bottle_{i}": "true" if container.items[i] is not None and not container.items[i].is_empty + else "false" for i in range(3)} + return with_props(state, **changes) + + class BrewingStandBehavior(BlockBehavior): """Brewing stand window: 3 bottles, ingredient, blaze powder.""" @@ -1131,26 +1198,22 @@ def is_interactive() -> bool: return True -# PotionBrewing ingredients (1.21.1) and what goes into the bottle slots -BREWING_INGREDIENTS = {"minecraft:" + n for n in ( - "nether_wart", "redstone", "glowstone_dust", "fermented_spider_eye", "gunpowder", "dragon_breath", "sugar", - "rabbit_foot", "glistering_melon_slice", "spider_eye", "pufferfish", "magma_cream", "golden_carrot", - "blaze_powder", "ghast_tear", "turtle_helmet", "phantom_membrane", "breeze_rod", "slime_block", "cobweb", - "stone")} -BREWING_BOTTLES = {"minecraft:potion", "minecraft:splash_potion", "minecraft:lingering_potion", - "minecraft:glass_bottle"} - - -def brewing_can_place(container, slot: int, item_id: str) -> bool: - """BrewingStandBlockEntity.canPlaceItem.""" - if slot == 3: - return item_id in BREWING_INGREDIENTS - if slot == 4: - return item_id == "minecraft:blaze_powder" - if slot in (0, 1, 2): - current = container.items[slot] - return item_id in BREWING_BOTTLES and (current is None or current.is_empty) - return False +def tick_brewing_stands(server) -> list: + """Advance every brewing stand one tick; returns (x, y, z, state) for the blocks whose bottles changed.""" + from .editing import get_world_block, set_world_block + changes = [] + for (x, y, z), container in list(container_manager.containers.items()): + if container.type != "brewing_stand": + continue + brewing_tick(container) + state = get_world_block(server, x, y, z) + if state is None: + continue + new_state = brewing_bottle_state(container, state) + if new_state != state: + set_world_block(server, x, y, z, new_state) + changes.append((x, y, z, new_state)) + return changes class CraftingTableBehavior(BlockBehavior): @@ -1245,17 +1308,21 @@ def is_interactive() -> bool: class AnvilBehavior(BlockBehavior): - """Anvil repair/enchant interface.""" + """Anvil: merge an enchanted book (or a matching item) into an item.""" @staticmethod async def on_use(conn, server, x: int, y: int, z: int, face: int, hand: int) -> bool: from world.inventory import send_open_container + from world.enchanting_window import open_window, ANVIL + container = container_manager.get_or_create(x, y, z, ANVIL) window_id = container_manager.allocate_window_id() conn._open_window_id = window_id conn._open_container_pos = (x, y, z) - + conn._open_container_type = 'block' await send_open_container(conn, window_id, "minecraft:anvil", {"translate": "container.repair"}) + await open_window(conn, window_id, container, (x, y, z)) + container_manager.add_viewer(x, y, z, conn.entity_id) return True @staticmethod @@ -1264,17 +1331,21 @@ def is_interactive() -> bool: class EnchantingTableBehavior(BlockBehavior): - """Enchanting table interface.""" + """Enchanting table: an item and lapis lazuli, three enchantment offers.""" @staticmethod async def on_use(conn, server, x: int, y: int, z: int, face: int, hand: int) -> bool: from world.inventory import send_open_container + from world.enchanting_window import open_window, ENCHANT_TABLE + container = container_manager.get_or_create(x, y, z, ENCHANT_TABLE) window_id = container_manager.allocate_window_id() conn._open_window_id = window_id conn._open_container_pos = (x, y, z) - + conn._open_container_type = 'block' await send_open_container(conn, window_id, "minecraft:enchantment", {"translate": "container.enchant"}) + await open_window(conn, window_id, container, (x, y, z)) + container_manager.add_viewer(x, y, z, conn.entity_id) return True @staticmethod @@ -1651,12 +1722,6 @@ async def _ignite(server, x: int, y: int, z: int): await _broadcast_block_change(server, x, y, z, AIR) server.entity_manager.create_tnt(x + 0.5, y, z + 0.5) - @staticmethod - async def _create_explosion(server, cx: int, cy: int, cz: int, radius: float = 4.0): - """Explosion at a block position (vanilla algorithm in world.explosion).""" - from world.explosion import explode - await explode(server, cx + 0.5, cy + 0.0625, cz + 0.5, radius) - @staticmethod def is_interactive() -> bool: return True @@ -1936,8 +2001,3 @@ def get_block_behavior(block_name: str) -> BlockBehavior | None: return BLOCK_BEHAVIORS.get(block_name) -def get_block_name_from_state(state_id: int) -> str: - """Get block name from a block state ID.""" - if state_id in STATE_ID_TO_BLOCK: - return STATE_ID_TO_BLOCK[state_id][0] - return "minecraft:air" diff --git a/world/chunk_io.py b/world/chunk_io.py index e4e0e8d..b3cad42 100755 --- a/world/chunk_io.py +++ b/world/chunk_io.py @@ -26,7 +26,6 @@ from .fastpack import flatten_section, pack_longs, palette_of, to_signed, unpack_longs import struct import sys -from functools import lru_cache from pathlib import Path from protocol.nbt import ( @@ -126,17 +125,24 @@ def _find_blocks_json() -> str: ) +def _load_blocks_json() -> list: + with open(_find_blocks_json(), "r", encoding="utf-8") as f: + return json.load(f) + + def _build_block_registry(): - blocks_path = _find_blocks_json() - with open(blocks_path, "r", encoding="utf-8") as f: - blocks = json.load(f) + """State tables for every block state. Keys and property pairs are shared objects, which keeps the + ~25k entries small; the legacy (pre-1.21 state order) table is only built when an old chunk needs it.""" + pairs: dict[tuple[str, str], tuple[str, str]] = {} + + def share(key): + return tuple(pairs.setdefault(pair, pair) for pair in key) state_id_to_block: dict[int, tuple[str, dict[str, str]]] = {} block_key_to_state_id: dict[tuple[str, tuple[tuple[str, str], ...]], int] = {} block_name_to_default_state: dict[str, int] = {} - legacy_key_to_state_id: dict[tuple[str, tuple[tuple[str, str], ...]], int] = {} - for block in blocks: + for block in _load_blocks_json(): name = f"minecraft:{block['name']}" default_state = int(block["defaultState"]) block_name_to_default_state[name] = default_state @@ -146,21 +152,32 @@ def _build_block_registry(): for state_id in range(min_state, max_state + 1): props = _state_id_to_properties(block, state_id) state_id_to_block[state_id] = (name, props) - block_key_to_state_id[(name, tuple(sorted(props.items())))] = state_id - legacy_props = _state_id_to_properties(block, state_id, legacy=True) - legacy_key_to_state_id[(name, tuple(sorted(legacy_props.items())))] = state_id + block_key_to_state_id[(name, share(sorted(props.items())))] = state_id # 允许省略 Properties 时直接落到 defaultState default_props = _state_id_to_properties(block, default_state) block_key_to_state_id[(name, tuple())] = default_state - block_key_to_state_id[(name, tuple(sorted(default_props.items())))] = default_state + block_key_to_state_id[(name, share(sorted(default_props.items())))] = default_state - global LEGACY_KEY_TO_STATE_ID - LEGACY_KEY_TO_STATE_ID = legacy_key_to_state_id return state_id_to_block, block_key_to_state_id, block_name_to_default_state -LEGACY_KEY_TO_STATE_ID: dict = {} +_LEGACY_KEY_TO_STATE_ID: dict | None = None + + +def _legacy_table() -> dict: + global _LEGACY_KEY_TO_STATE_ID + if _LEGACY_KEY_TO_STATE_ID is None: + table: dict = {} + for block in _load_blocks_json(): + name = f"minecraft:{block['name']}" + for state_id in range(int(block["minStateId"]), int(block["maxStateId"]) + 1): + legacy_props = _state_id_to_properties(block, state_id, legacy=True) + table[(name, tuple(sorted(legacy_props.items())))] = state_id + _LEGACY_KEY_TO_STATE_ID = table + return _LEGACY_KEY_TO_STATE_ID + + STATE_ID_TO_BLOCK, BLOCK_KEY_TO_STATE_ID, BLOCK_NAME_TO_DEFAULT_STATE = _build_block_registry() # Chunks written by this version carry this tag; see _uses_legacy_state_order(). @@ -261,7 +278,7 @@ def _palette_entry_to_state_id(entry: dict, legacy: bool = False) -> int: for k, v in props.items() )) - table = LEGACY_KEY_TO_STATE_ID if legacy else BLOCK_KEY_TO_STATE_ID + table = _legacy_table() if legacy else BLOCK_KEY_TO_STATE_ID state_id = table.get((name, normalized)) if state_id is not None: return state_id @@ -313,15 +330,6 @@ def _build_section_nbt(section_blocks: list[list[list[int]]], section_y: int, return section -@lru_cache(maxsize=1) -def _empty_heightmaps() -> dict: - empty_chunk = [[[0 for _ in range(16)] for _ in range(16)] for _ in range(WORLD_HEIGHT)] - return { - "MOTION_BLOCKING": NbtLongArray(build_heightmap_from_terrain(empty_chunk, include_water=False)), - "WORLD_SURFACE": NbtLongArray(build_heightmap_from_terrain(empty_chunk, include_water=True)), - } - - def serialize_chunk(chunk_blocks: list[list[list[int]]], chunk_x: int = 0, chunk_z: int = 0, chunk_biomes: list[list[int]] | None = None) -> bytes: """ @@ -524,21 +532,3 @@ def deserialize_chunk(data: bytes) -> list[list[list[int]]] | None: return blocks -def serialize_chunk_fast(flat_blocks: array.array, chunk_x: int = 0, - chunk_z: int = 0) -> bytes: - """ - 从扁平 uint16 数组编码原版 Chunk NBT。 - """ - if len(flat_blocks) != BLOCKS_COUNT: - raise ValueError(f"flat_blocks 长度应为 {BLOCKS_COUNT}, 实际 {len(flat_blocks)}") - - blocks = [] - offset = 0 - for _ in range(WORLD_HEIGHT): - layer = [] - for _ in range(16): - layer.append(list(flat_blocks[offset:offset + 16])) - offset += 16 - blocks.append(layer) - - return serialize_chunk(blocks, chunk_x=chunk_x, chunk_z=chunk_z) diff --git a/world/crafting.py b/world/crafting.py index 8ffb844..497a131 100755 --- a/world/crafting.py +++ b/world/crafting.py @@ -54,7 +54,6 @@ """ import logging -from typing import Optional logger = logging.getLogger("PyMC.合成") @@ -1679,75 +1678,6 @@ def check_smelting(self, ingredient: str) -> tuple[str, float, int] | None: return (result_item, recipe["xp"], recipe["cook_time"]) return None - def check_stonecutting(self, ingredient: str) -> list[tuple[str, int]]: - """ - Check stonecutting recipes for a given ingredient. - Returns list of (result_item, result_count) tuples (multiple possible). - """ - results = [] - for recipe_name, recipe in STONECUTTING_RECIPES.items(): - if recipe["ingredient"] == ingredient: - result_item, result_count = recipe["result"] - results.append((result_item, result_count)) - return results - - def check_smithing(self, template: str, base: str, addition: str) -> tuple[str, int] | None: - """ - Check a smithing recipe. - Returns (result_item, result_count) or None if no match. - """ - for recipe_name, recipe in SMITHING_RECIPES.items(): - if (recipe["template"] == template and - recipe["base"] == base and - recipe["addition"] == addition): - return recipe["result"] - return None - - def get_fuel_burn_time(self, fuel_item: str) -> int: - """Get the burn time in ticks for a fuel item.""" - return FUEL_VALUES.get(fuel_item, 0) - - def consume_ingredients(self, grid: list[list[str]]) -> list[list[str]]: - """ - Consume one of each ingredient from the crafting grid. - Returns the updated grid with consumed items removed. - """ - result = [] - for row in grid: - result_row = [] - for cell in row: - # Each ingredient is consumed (replaced with air) - if cell and cell != "minecraft:air": - result_row.append("") - else: - result_row.append(cell) - result.append(result_row) - return result - - def check_2x2_crafting(self, slots: list[str]) -> tuple[str, int] | None: - """ - Check a 2x2 crafting grid from the player inventory. - slots is a list of 4 item IDs: [top-left, top-right, bottom-left, bottom-right] - """ - grid = [ - [slots[0] if len(slots) > 0 else "", slots[1] if len(slots) > 1 else ""], - [slots[2] if len(slots) > 2 else "", slots[3] if len(slots) > 3 else ""], - ] - return self.check_crafting(grid) - - def check_3x3_crafting(self, slots: list[str]) -> tuple[str, int] | None: - """ - Check a 3x3 crafting grid from a crafting table. - slots is a list of 9 item IDs in row-major order. - """ - grid = [ - [slots[0] if len(slots) > 0 else "", slots[1] if len(slots) > 1 else "", slots[2] if len(slots) > 2 else ""], - [slots[3] if len(slots) > 3 else "", slots[4] if len(slots) > 4 else "", slots[5] if len(slots) > 5 else ""], - [slots[6] if len(slots) > 6 else "", slots[7] if len(slots) > 7 else "", slots[8] if len(slots) > 8 else ""], - ] - return self.check_crafting(grid) - - # Global crafting system instance crafting_system = CraftingSystem() diff --git a/world/data/enchantments.json b/world/data/enchantments.json new file mode 100644 index 0000000..3e5c620 --- /dev/null +++ b/world/data/enchantments.json @@ -0,0 +1,2186 @@ +[ + { + "id": 0, + "name": "aqua_affinity", + "max_level": 1, + "min_cost": [ + 1, + 0 + ], + "max_cost": [ + 41, + 0 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet" + ], + "primary": [ + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 1, + "name": "bane_of_arthropods", + "max_level": 5, + "min_cost": [ + 5, + 8 + ], + "max_cost": [ + 25, + 8 + ], + "weight": 5, + "anvil_cost": 2, + "supported": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword", + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "mace" + ], + "primary": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword" + ], + "exclusive": [ + "sharpness", + "smite", + "bane_of_arthropods", + "impaling", + "density", + "breach" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 2, + "name": "binding_curse", + "max_level": 1, + "min_cost": [ + 25, + 0 + ], + "max_cost": [ + 50, + 0 + ], + "weight": 1, + "anvil_cost": 8, + "supported": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet", + "elytra", + "player_head", + "creeper_head", + "zombie_head", + "skeleton_skull", + "wither_skeleton_skull", + "dragon_head", + "piglin_head", + "carved_pumpkin" + ], + "primary": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet", + "elytra", + "player_head", + "creeper_head", + "zombie_head", + "skeleton_skull", + "wither_skeleton_skull", + "dragon_head", + "piglin_head", + "carved_pumpkin" + ], + "exclusive": [], + "treasure": true, + "curse": true, + "tradeable": true, + "in_enchanting_table": false + }, + { + "id": 3, + "name": "blast_protection", + "max_level": 4, + "min_cost": [ + 5, + 8 + ], + "max_cost": [ + 13, + 8 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet" + ], + "primary": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet" + ], + "exclusive": [ + "protection", + "blast_protection", + "fire_protection", + "projectile_protection" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 4, + "name": "breach", + "max_level": 4, + "min_cost": [ + 15, + 9 + ], + "max_cost": [ + 65, + 9 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "mace" + ], + "primary": [ + "mace" + ], + "exclusive": [ + "sharpness", + "smite", + "bane_of_arthropods", + "impaling", + "density", + "breach" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 5, + "name": "channeling", + "max_level": 1, + "min_cost": [ + 25, + 0 + ], + "max_cost": [ + 50, + 0 + ], + "weight": 1, + "anvil_cost": 8, + "supported": [ + "trident" + ], + "primary": [ + "trident" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 6, + "name": "density", + "max_level": 5, + "min_cost": [ + 5, + 8 + ], + "max_cost": [ + 25, + 8 + ], + "weight": 5, + "anvil_cost": 2, + "supported": [ + "mace" + ], + "primary": [ + "mace" + ], + "exclusive": [ + "sharpness", + "smite", + "bane_of_arthropods", + "impaling", + "density", + "breach" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 7, + "name": "depth_strider", + "max_level": 3, + "min_cost": [ + 10, + 10 + ], + "max_cost": [ + 25, + 10 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots" + ], + "primary": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots" + ], + "exclusive": [ + "frost_walker", + "depth_strider" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 8, + "name": "efficiency", + "max_level": 5, + "min_cost": [ + 1, + 10 + ], + "max_cost": [ + 51, + 10 + ], + "weight": 10, + "anvil_cost": 1, + "supported": [ + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "diamond_pickaxe", + "stone_pickaxe", + "golden_pickaxe", + "netherite_pickaxe", + "wooden_pickaxe", + "iron_pickaxe", + "diamond_shovel", + "stone_shovel", + "golden_shovel", + "netherite_shovel", + "wooden_shovel", + "iron_shovel", + "diamond_hoe", + "stone_hoe", + "golden_hoe", + "netherite_hoe", + "wooden_hoe", + "iron_hoe", + "shears" + ], + "primary": [ + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "diamond_pickaxe", + "stone_pickaxe", + "golden_pickaxe", + "netherite_pickaxe", + "wooden_pickaxe", + "iron_pickaxe", + "diamond_shovel", + "stone_shovel", + "golden_shovel", + "netherite_shovel", + "wooden_shovel", + "iron_shovel", + "diamond_hoe", + "stone_hoe", + "golden_hoe", + "netherite_hoe", + "wooden_hoe", + "iron_hoe", + "shears" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 9, + "name": "feather_falling", + "max_level": 4, + "min_cost": [ + 5, + 6 + ], + "max_cost": [ + 11, + 6 + ], + "weight": 5, + "anvil_cost": 2, + "supported": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots" + ], + "primary": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 10, + "name": "fire_aspect", + "max_level": 2, + "min_cost": [ + 10, + 20 + ], + "max_cost": [ + 60, + 20 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword", + "mace" + ], + "primary": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 11, + "name": "fire_protection", + "max_level": 4, + "min_cost": [ + 10, + 8 + ], + "max_cost": [ + 18, + 8 + ], + "weight": 5, + "anvil_cost": 2, + "supported": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet" + ], + "primary": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet" + ], + "exclusive": [ + "protection", + "blast_protection", + "fire_protection", + "projectile_protection" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 12, + "name": "flame", + "max_level": 1, + "min_cost": [ + 20, + 0 + ], + "max_cost": [ + 50, + 0 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "bow" + ], + "primary": [ + "bow" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 13, + "name": "fortune", + "max_level": 3, + "min_cost": [ + 15, + 9 + ], + "max_cost": [ + 65, + 9 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "diamond_pickaxe", + "stone_pickaxe", + "golden_pickaxe", + "netherite_pickaxe", + "wooden_pickaxe", + "iron_pickaxe", + "diamond_shovel", + "stone_shovel", + "golden_shovel", + "netherite_shovel", + "wooden_shovel", + "iron_shovel", + "diamond_hoe", + "stone_hoe", + "golden_hoe", + "netherite_hoe", + "wooden_hoe", + "iron_hoe" + ], + "primary": [ + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "diamond_pickaxe", + "stone_pickaxe", + "golden_pickaxe", + "netherite_pickaxe", + "wooden_pickaxe", + "iron_pickaxe", + "diamond_shovel", + "stone_shovel", + "golden_shovel", + "netherite_shovel", + "wooden_shovel", + "iron_shovel", + "diamond_hoe", + "stone_hoe", + "golden_hoe", + "netherite_hoe", + "wooden_hoe", + "iron_hoe" + ], + "exclusive": [ + "fortune", + "silk_touch" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 14, + "name": "frost_walker", + "max_level": 2, + "min_cost": [ + 10, + 10 + ], + "max_cost": [ + 25, + 10 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots" + ], + "primary": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots" + ], + "exclusive": [ + "frost_walker", + "depth_strider" + ], + "treasure": true, + "curse": false, + "tradeable": true, + "in_enchanting_table": false + }, + { + "id": 15, + "name": "impaling", + "max_level": 5, + "min_cost": [ + 1, + 8 + ], + "max_cost": [ + 21, + 8 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "trident" + ], + "primary": [ + "trident" + ], + "exclusive": [ + "sharpness", + "smite", + "bane_of_arthropods", + "impaling", + "density", + "breach" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 16, + "name": "infinity", + "max_level": 1, + "min_cost": [ + 20, + 0 + ], + "max_cost": [ + 50, + 0 + ], + "weight": 1, + "anvil_cost": 8, + "supported": [ + "bow" + ], + "primary": [ + "bow" + ], + "exclusive": [ + "infinity", + "mending" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 17, + "name": "knockback", + "max_level": 2, + "min_cost": [ + 5, + 20 + ], + "max_cost": [ + 55, + 20 + ], + "weight": 5, + "anvil_cost": 2, + "supported": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword" + ], + "primary": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 18, + "name": "looting", + "max_level": 3, + "min_cost": [ + 15, + 9 + ], + "max_cost": [ + 65, + 9 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword" + ], + "primary": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 19, + "name": "loyalty", + "max_level": 3, + "min_cost": [ + 12, + 7 + ], + "max_cost": [ + 50, + 0 + ], + "weight": 5, + "anvil_cost": 2, + "supported": [ + "trident" + ], + "primary": [ + "trident" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 20, + "name": "luck_of_the_sea", + "max_level": 3, + "min_cost": [ + 15, + 9 + ], + "max_cost": [ + 65, + 9 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "fishing_rod" + ], + "primary": [ + "fishing_rod" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 21, + "name": "lure", + "max_level": 3, + "min_cost": [ + 15, + 9 + ], + "max_cost": [ + 65, + 9 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "fishing_rod" + ], + "primary": [ + "fishing_rod" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 22, + "name": "mending", + "max_level": 1, + "min_cost": [ + 25, + 25 + ], + "max_cost": [ + 75, + 25 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet", + "elytra", + "shield", + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword", + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "diamond_pickaxe", + "stone_pickaxe", + "golden_pickaxe", + "netherite_pickaxe", + "wooden_pickaxe", + "iron_pickaxe", + "diamond_shovel", + "stone_shovel", + "golden_shovel", + "netherite_shovel", + "wooden_shovel", + "iron_shovel", + "diamond_hoe", + "stone_hoe", + "golden_hoe", + "netherite_hoe", + "wooden_hoe", + "iron_hoe", + "bow", + "crossbow", + "trident", + "flint_and_steel", + "shears", + "brush", + "fishing_rod", + "carrot_on_a_stick", + "warped_fungus_on_a_stick", + "mace" + ], + "primary": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet", + "elytra", + "shield", + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword", + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "diamond_pickaxe", + "stone_pickaxe", + "golden_pickaxe", + "netherite_pickaxe", + "wooden_pickaxe", + "iron_pickaxe", + "diamond_shovel", + "stone_shovel", + "golden_shovel", + "netherite_shovel", + "wooden_shovel", + "iron_shovel", + "diamond_hoe", + "stone_hoe", + "golden_hoe", + "netherite_hoe", + "wooden_hoe", + "iron_hoe", + "bow", + "crossbow", + "trident", + "flint_and_steel", + "shears", + "brush", + "fishing_rod", + "carrot_on_a_stick", + "warped_fungus_on_a_stick", + "mace" + ], + "exclusive": [], + "treasure": true, + "curse": false, + "tradeable": true, + "in_enchanting_table": false + }, + { + "id": 23, + "name": "multishot", + "max_level": 1, + "min_cost": [ + 20, + 0 + ], + "max_cost": [ + 50, + 0 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "crossbow" + ], + "primary": [ + "crossbow" + ], + "exclusive": [ + "multishot", + "piercing" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 24, + "name": "piercing", + "max_level": 4, + "min_cost": [ + 1, + 10 + ], + "max_cost": [ + 50, + 0 + ], + "weight": 10, + "anvil_cost": 1, + "supported": [ + "crossbow" + ], + "primary": [ + "crossbow" + ], + "exclusive": [ + "multishot", + "piercing" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 25, + "name": "power", + "max_level": 5, + "min_cost": [ + 1, + 10 + ], + "max_cost": [ + 16, + 10 + ], + "weight": 10, + "anvil_cost": 1, + "supported": [ + "bow" + ], + "primary": [ + "bow" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 26, + "name": "projectile_protection", + "max_level": 4, + "min_cost": [ + 3, + 6 + ], + "max_cost": [ + 9, + 6 + ], + "weight": 5, + "anvil_cost": 2, + "supported": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet" + ], + "primary": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet" + ], + "exclusive": [ + "protection", + "blast_protection", + "fire_protection", + "projectile_protection" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 27, + "name": "protection", + "max_level": 4, + "min_cost": [ + 1, + 11 + ], + "max_cost": [ + 12, + 11 + ], + "weight": 10, + "anvil_cost": 1, + "supported": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet" + ], + "primary": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet" + ], + "exclusive": [ + "protection", + "blast_protection", + "fire_protection", + "projectile_protection" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 28, + "name": "punch", + "max_level": 2, + "min_cost": [ + 12, + 20 + ], + "max_cost": [ + 37, + 20 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "bow" + ], + "primary": [ + "bow" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 29, + "name": "quick_charge", + "max_level": 3, + "min_cost": [ + 12, + 20 + ], + "max_cost": [ + 50, + 0 + ], + "weight": 5, + "anvil_cost": 2, + "supported": [ + "crossbow" + ], + "primary": [ + "crossbow" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 30, + "name": "respiration", + "max_level": 3, + "min_cost": [ + 10, + 10 + ], + "max_cost": [ + 40, + 10 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet" + ], + "primary": [ + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 31, + "name": "riptide", + "max_level": 3, + "min_cost": [ + 17, + 7 + ], + "max_cost": [ + 50, + 0 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "trident" + ], + "primary": [ + "trident" + ], + "exclusive": [ + "loyalty", + "channeling" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 32, + "name": "sharpness", + "max_level": 5, + "min_cost": [ + 1, + 11 + ], + "max_cost": [ + 21, + 11 + ], + "weight": 10, + "anvil_cost": 1, + "supported": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword", + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe" + ], + "primary": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword" + ], + "exclusive": [ + "sharpness", + "smite", + "bane_of_arthropods", + "impaling", + "density", + "breach" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 33, + "name": "silk_touch", + "max_level": 1, + "min_cost": [ + 15, + 0 + ], + "max_cost": [ + 65, + 0 + ], + "weight": 1, + "anvil_cost": 8, + "supported": [ + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "diamond_pickaxe", + "stone_pickaxe", + "golden_pickaxe", + "netherite_pickaxe", + "wooden_pickaxe", + "iron_pickaxe", + "diamond_shovel", + "stone_shovel", + "golden_shovel", + "netherite_shovel", + "wooden_shovel", + "iron_shovel", + "diamond_hoe", + "stone_hoe", + "golden_hoe", + "netherite_hoe", + "wooden_hoe", + "iron_hoe" + ], + "primary": [ + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "diamond_pickaxe", + "stone_pickaxe", + "golden_pickaxe", + "netherite_pickaxe", + "wooden_pickaxe", + "iron_pickaxe", + "diamond_shovel", + "stone_shovel", + "golden_shovel", + "netherite_shovel", + "wooden_shovel", + "iron_shovel", + "diamond_hoe", + "stone_hoe", + "golden_hoe", + "netherite_hoe", + "wooden_hoe", + "iron_hoe" + ], + "exclusive": [ + "fortune", + "silk_touch" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 34, + "name": "smite", + "max_level": 5, + "min_cost": [ + 5, + 8 + ], + "max_cost": [ + 25, + 8 + ], + "weight": 5, + "anvil_cost": 2, + "supported": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword", + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "mace" + ], + "primary": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword" + ], + "exclusive": [ + "sharpness", + "smite", + "bane_of_arthropods", + "impaling", + "density", + "breach" + ], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 35, + "name": "soul_speed", + "max_level": 3, + "min_cost": [ + 10, + 10 + ], + "max_cost": [ + 25, + 10 + ], + "weight": 1, + "anvil_cost": 8, + "supported": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots" + ], + "primary": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots" + ], + "exclusive": [], + "treasure": true, + "curse": false, + "tradeable": false, + "in_enchanting_table": false + }, + { + "id": 36, + "name": "sweeping_edge", + "max_level": 3, + "min_cost": [ + 5, + 9 + ], + "max_cost": [ + 20, + 9 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword" + ], + "primary": [ + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 37, + "name": "swift_sneak", + "max_level": 3, + "min_cost": [ + 25, + 25 + ], + "max_cost": [ + 75, + 25 + ], + "weight": 1, + "anvil_cost": 8, + "supported": [ + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings" + ], + "primary": [ + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings" + ], + "exclusive": [], + "treasure": true, + "curse": false, + "tradeable": false, + "in_enchanting_table": false + }, + { + "id": 38, + "name": "thorns", + "max_level": 3, + "min_cost": [ + 10, + 20 + ], + "max_cost": [ + 60, + 20 + ], + "weight": 1, + "anvil_cost": 8, + "supported": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet" + ], + "primary": [ + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 39, + "name": "unbreaking", + "max_level": 3, + "min_cost": [ + 5, + 8 + ], + "max_cost": [ + 55, + 8 + ], + "weight": 5, + "anvil_cost": 2, + "supported": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet", + "elytra", + "shield", + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword", + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "diamond_pickaxe", + "stone_pickaxe", + "golden_pickaxe", + "netherite_pickaxe", + "wooden_pickaxe", + "iron_pickaxe", + "diamond_shovel", + "stone_shovel", + "golden_shovel", + "netherite_shovel", + "wooden_shovel", + "iron_shovel", + "diamond_hoe", + "stone_hoe", + "golden_hoe", + "netherite_hoe", + "wooden_hoe", + "iron_hoe", + "bow", + "crossbow", + "trident", + "flint_and_steel", + "shears", + "brush", + "fishing_rod", + "carrot_on_a_stick", + "warped_fungus_on_a_stick", + "mace" + ], + "primary": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet", + "elytra", + "shield", + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword", + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "diamond_pickaxe", + "stone_pickaxe", + "golden_pickaxe", + "netherite_pickaxe", + "wooden_pickaxe", + "iron_pickaxe", + "diamond_shovel", + "stone_shovel", + "golden_shovel", + "netherite_shovel", + "wooden_shovel", + "iron_shovel", + "diamond_hoe", + "stone_hoe", + "golden_hoe", + "netherite_hoe", + "wooden_hoe", + "iron_hoe", + "bow", + "crossbow", + "trident", + "flint_and_steel", + "shears", + "brush", + "fishing_rod", + "carrot_on_a_stick", + "warped_fungus_on_a_stick", + "mace" + ], + "exclusive": [], + "treasure": false, + "curse": false, + "tradeable": true, + "in_enchanting_table": true + }, + { + "id": 40, + "name": "vanishing_curse", + "max_level": 1, + "min_cost": [ + 25, + 0 + ], + "max_cost": [ + 50, + 0 + ], + "weight": 1, + "anvil_cost": 8, + "supported": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet", + "elytra", + "shield", + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword", + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "diamond_pickaxe", + "stone_pickaxe", + "golden_pickaxe", + "netherite_pickaxe", + "wooden_pickaxe", + "iron_pickaxe", + "diamond_shovel", + "stone_shovel", + "golden_shovel", + "netherite_shovel", + "wooden_shovel", + "iron_shovel", + "diamond_hoe", + "stone_hoe", + "golden_hoe", + "netherite_hoe", + "wooden_hoe", + "iron_hoe", + "bow", + "crossbow", + "trident", + "flint_and_steel", + "shears", + "brush", + "fishing_rod", + "carrot_on_a_stick", + "warped_fungus_on_a_stick", + "mace", + "compass", + "carved_pumpkin", + "player_head", + "creeper_head", + "zombie_head", + "skeleton_skull", + "wither_skeleton_skull", + "dragon_head", + "piglin_head" + ], + "primary": [ + "leather_boots", + "chainmail_boots", + "golden_boots", + "iron_boots", + "diamond_boots", + "netherite_boots", + "leather_leggings", + "chainmail_leggings", + "golden_leggings", + "iron_leggings", + "diamond_leggings", + "netherite_leggings", + "leather_chestplate", + "chainmail_chestplate", + "golden_chestplate", + "iron_chestplate", + "diamond_chestplate", + "netherite_chestplate", + "leather_helmet", + "chainmail_helmet", + "golden_helmet", + "iron_helmet", + "diamond_helmet", + "netherite_helmet", + "turtle_helmet", + "elytra", + "shield", + "diamond_sword", + "stone_sword", + "golden_sword", + "netherite_sword", + "wooden_sword", + "iron_sword", + "diamond_axe", + "stone_axe", + "golden_axe", + "netherite_axe", + "wooden_axe", + "iron_axe", + "diamond_pickaxe", + "stone_pickaxe", + "golden_pickaxe", + "netherite_pickaxe", + "wooden_pickaxe", + "iron_pickaxe", + "diamond_shovel", + "stone_shovel", + "golden_shovel", + "netherite_shovel", + "wooden_shovel", + "iron_shovel", + "diamond_hoe", + "stone_hoe", + "golden_hoe", + "netherite_hoe", + "wooden_hoe", + "iron_hoe", + "bow", + "crossbow", + "trident", + "flint_and_steel", + "shears", + "brush", + "fishing_rod", + "carrot_on_a_stick", + "warped_fungus_on_a_stick", + "mace", + "compass", + "carved_pumpkin", + "player_head", + "creeper_head", + "zombie_head", + "skeleton_skull", + "wither_skeleton_skull", + "dragon_head", + "piglin_head" + ], + "exclusive": [], + "treasure": true, + "curse": true, + "tradeable": true, + "in_enchanting_table": false + }, + { + "id": 41, + "name": "wind_burst", + "max_level": 3, + "min_cost": [ + 15, + 9 + ], + "max_cost": [ + 65, + 9 + ], + "weight": 2, + "anvil_cost": 4, + "supported": [ + "mace" + ], + "primary": [ + "mace" + ], + "exclusive": [], + "treasure": true, + "curse": false, + "tradeable": false, + "in_enchanting_table": false + } +] diff --git a/world/data/potions.json b/world/data/potions.json new file mode 100644 index 0000000..865ba1f --- /dev/null +++ b/world/data/potions.json @@ -0,0 +1,52 @@ +{ + "registry": "minecraft:potion", + "source": "Registration order of the 1.21.1 potion registry (static registry; ids are the index).", + "names": [ + "water", + "mundane", + "thick", + "awkward", + "night_vision", + "long_night_vision", + "invisibility", + "long_invisibility", + "leaping", + "long_leaping", + "strong_leaping", + "fire_resistance", + "long_fire_resistance", + "swiftness", + "long_swiftness", + "strong_swiftness", + "slowness", + "long_slowness", + "strong_slowness", + "turtle_master", + "long_turtle_master", + "strong_turtle_master", + "water_breathing", + "long_water_breathing", + "healing", + "strong_healing", + "harming", + "strong_harming", + "poison", + "long_poison", + "strong_poison", + "regeneration", + "long_regeneration", + "strong_regeneration", + "strength", + "long_strength", + "strong_strength", + "weakness", + "long_weakness", + "luck", + "slow_falling", + "long_slow_falling", + "wind_charged", + "weaving", + "oozing", + "infested" + ] +} \ No newline at end of file diff --git a/world/editing.py b/world/editing.py index a881c18..e18dd8e 100755 --- a/world/editing.py +++ b/world/editing.py @@ -168,13 +168,6 @@ def set_world_block(server, x: int, y: int, z: int, block_state: int) -> set[tup return dirty_chunks -def fill_box(server, x1: int, y1: int, z1: int, x2: int, y2: int, z2: int, block_state: int) -> tuple[int, set[tuple[int, int]]]: - changed_positions, changed_chunks, _ = fill_box_detailed( - server, x1, y1, z1, x2, y2, z2, block_state - ) - return changed_positions, changed_chunks - - def fill_box_detailed( server, x1: int, @@ -211,33 +204,6 @@ def _ranges_overlap(a_min: int, a_max: int, b_min: int, b_max: int) -> bool: return not (a_max < b_min or b_max < a_min) -def clone_box( - server, - x1: int, - y1: int, - z1: int, - x2: int, - y2: int, - z2: int, - dest_x: int, - dest_y: int, - dest_z: int, - *, - mask_mode: str = "replace", - clone_mode: str = "normal", - filter_block_state: int | None = None, -) -> tuple[int, set[tuple[int, int]]]: - changed_positions, changed_chunks, _ = clone_box_detailed( - server, - x1, y1, z1, x2, y2, z2, - dest_x, dest_y, dest_z, - mask_mode=mask_mode, - clone_mode=clone_mode, - filter_block_state=filter_block_state, - ) - return changed_positions, changed_chunks - - def clone_box_detailed( server, x1: int, diff --git a/world/enchanting.py b/world/enchanting.py new file mode 100644 index 0000000..270f907 --- /dev/null +++ b/world/enchanting.py @@ -0,0 +1,307 @@ +""" +Enchanting table, anvil and enchanted books (1.21.1 rules). + +* Enchantment data comes from world/data/enchantments.json (generated by + tools/gen_enchantment_data.py from the 1.21.1 registry): levels, costs, + weights, the items each enchantment accepts, exclusive sets, treasure/curse. +* Enchantments live in the item's nbt: "enchantments" on tools and armour, + "stored_enchantments" on enchanted books. Both map short names to levels. +* Enchanting table: the three offers come from the vanilla cost roll + (EnchantmentMenu.slotsChanged / EnchantmentHelper.selectEnchantment), with + the power from bookshelves around the table. +* Anvil: an enchanted book or a matching item merged into the left item, with + the vanilla anvil cost (anvil_cost * level per enchantment). +""" + +from __future__ import annotations + +import json +import random +from functools import lru_cache +from pathlib import Path + +DATA_FILE = Path(__file__).resolve().parent / "data" / "enchantments.json" +MAX_POWER = 15 +TOO_EXPENSIVE = 40 + +# Item.getEnchantmentValue() for the common items (1.21.1) +_MATERIAL_ENCHANTABILITY = {"wooden": 15, "stone": 5, "iron": 14, "golden": 22, "diamond": 10, + "netherite": 15, "leather": 15, "chainmail": 12, "turtle": 9} +_TOOL_SUFFIXES = ("_sword", "_pickaxe", "_axe", "_shovel", "_hoe", "_helmet", "_chestplate", + "_leggings", "_boots") +_OTHER_ENCHANTABILITY = {"book": 1, "enchanted_book": 1, "bow": 1, "crossbow": 1, "fishing_rod": 1, + "trident": 1, "mace": 15} +BOOK_ITEMS = ("minecraft:book", "minecraft:enchanted_book") + + +@lru_cache(maxsize=1) +def _data(): + with open(DATA_FILE, "r", encoding="utf-8") as f: + entries = json.load(f) + by_name = {} + for entry in entries: + entry["exclusive"] = set(entry["exclusive"]) + entry["supported"] = set(entry["supported"]) + by_name[entry["name"]] = entry + return entries, by_name + + +def enchantments() -> list[dict]: + return _data()[0] + + +def enchantment(name: str) -> dict | None: + return _data()[1].get(short_name(name)) + + +def short_name(name: str) -> str: + return name.split(":", 1)[-1] + + +def protocol_id(name: str) -> int | None: + """Registry id of an enchantment (the order of the synced enchantment registry).""" + entry = enchantment(name) + return None if entry is None else entry["id"] + + +def name_of_protocol_id(index: int) -> str | None: + entries = enchantments() + return entries[index]["name"] if 0 <= index < len(entries) else None + + +def item_enchantability(item_id: str) -> int: + short = short_name(item_id) + if short in _OTHER_ENCHANTABILITY: + return _OTHER_ENCHANTABILITY[short] + material, _, rest = short.partition("_") + if material in _MATERIAL_ENCHANTABILITY and short.endswith(_TOOL_SUFFIXES): + return _MATERIAL_ENCHANTABILITY[material] + return 0 + + +def is_book(item_id: str) -> bool: + return item_id in BOOK_ITEMS + + +def accepts(item_id: str, name: str) -> bool: + """Enchantment.canEnchant (books accept everything).""" + entry = enchantment(name) + if entry is None: + return False + if is_book(item_id): + return True + return short_name(item_id) in entry["supported"] + + +def compatible(name: str, existing) -> bool: + """Not exclusive with any other enchantment already on the item.""" + entry = enchantment(name) + short = short_name(name) + for other in existing: + other_short = short_name(other) + if other_short == short: + continue + other_entry = enchantment(other) + if other_entry is None: + continue + if other_short in entry["exclusive"] or short in other_entry["exclusive"]: + return False + return True + + +def level_cost(entry: dict, level: int, which: str) -> int: + base, per_level = entry[which] + return base + per_level * (level - 1) + + +@lru_cache(maxsize=1) +def bookshelf_states() -> frozenset: + from .chunk_io import STATE_ID_TO_BLOCK + return frozenset(sid for sid, (name, _) in STATE_ID_TO_BLOCK.items() if name == "minecraft:bookshelf") + + +def bookshelf_power(get_block, x: int, y: int, z: int) -> int: + """EnchantmentMenu power: bookshelves in the ring around the table (each adds 1, max 15). + + A shelf counts when the block between it and the table is empty (air).""" + shelves = bookshelf_states() + power = 0 + for dx in range(-2, 3): + for dz in range(-2, 3): + if abs(dx) < 2 and abs(dz) < 2: + continue # the 3x3 around the table + for dy in (0, 1): + if get_block(x + dx, y + dy, z + dz) in shelves and \ + get_block(x + dx // 2, y + dy, z + dz // 2) in (0, None): + power += 1 + return min(power, MAX_POWER) + + +def _weighted_pick(rng: random.Random, candidates: list[tuple[dict, int]]): + total = sum(entry["weight"] for entry, _ in candidates) + roll = rng.randrange(total) + for entry, level in candidates: + roll -= entry["weight"] + if roll < 0: + return entry, level + return candidates[-1] + + +def select_enchantments(rng: random.Random, item_id: str, cost: int, allow_treasure: bool = False) -> list[tuple[str, int]]: + """EnchantmentHelper.selectEnchantment: the enchantments one offer gives.""" + enchantability = item_enchantability(item_id) if not is_book(item_id) else 1 + if enchantability <= 0: + return [] + cost += 1 + rng.randint(0, enchantability // 4) + rng.randint(0, enchantability // 4) + factor = (rng.random() + rng.random() - 1.0) * 0.15 + cost = max(1, round(cost + cost * factor)) + + def candidates_for(cost_value: int, chosen: list[tuple[dict, int]]): + out = [] + for entry in enchantments(): + if entry["treasure"] and not allow_treasure: + continue + if not entry["in_enchanting_table"] or not accepts(item_id, entry["name"]): + continue + if any(entry["name"] == other["name"] or other["name"] in entry["exclusive"] or + entry["name"] in other["exclusive"] for other, _ in chosen): + continue + level = _fitting_level(entry, cost_value) + if level: + out.append((entry, level)) + return out + + candidates = candidates_for(cost, []) + if not candidates: + return [] + chosen: list[tuple[dict, int]] = [_weighted_pick(rng, candidates)] + # EnchantmentHelper: each extra enchantment needs a roll under the (halving) cost + while True: + cost //= 2 + if rng.randint(0, 49) > cost: + break + more = candidates_for(cost, chosen) + if not more: + break + chosen.append(_weighted_pick(rng, more)) + return [(entry["name"], level) for entry, level in chosen] + + +def _fitting_level(entry: dict, cost: int) -> int: + """Highest level whose cost range contains ``cost`` (0 when none does).""" + for level in range(entry["max_level"], 0, -1): + if level_cost(entry, level, "min_cost") <= cost <= level_cost(entry, level, "max_cost"): + return level + return 0 + + +def offer_costs(seed: int, item_id: str, power: int) -> list[int]: + """EnchantmentMenu.slotsChanged: the three level costs for the current item and power.""" + enchantability = item_enchantability(item_id) if not is_book(item_id) else 1 + if enchantability <= 0: + return [0, 0, 0] + rng = random.Random(seed) + costs = [] + for slot in range(3): + cost = rng.randint(0, 7) + 1 + (power >> 1) + rng.randint(0, power) + if slot == 0: + cost = max(cost // 3, 1) + elif slot == 1: + cost = cost * 2 // 3 + 1 + else: + cost = max(cost, power * 2) + costs.append(cost if cost >= slot + 1 else 0) + return costs + + +def enchanting_offers(seed: int, item_id: str, power: int) -> list[dict | None]: + """The three offers: {"requirement": level needed, "levels": levels spent, "lapis": lapis spent, + "enchants": [(name, level), ...]} or None.""" + costs = offer_costs(seed, item_id, power) + offers = [] + for slot, cost in enumerate(costs): + if cost <= 0: + offers.append(None) + continue + enchants = select_enchantments(random.Random(seed + slot), item_id, cost) + offers.append({"requirement": cost, "levels": slot + 1, "lapis": slot + 1, "enchants": enchants} + if enchants else None) + return offers + + +def with_enchantments(item_id: str, nbt: dict, enchants: list[tuple[str, int]]) -> tuple[str, dict]: + """Result of enchanting an item: books become enchanted books (stored_enchantments).""" + nbt = dict(nbt or {}) + if is_book(item_id): + stored = dict(nbt.get("stored_enchantments", {})) + for name, level in enchants: + stored[short_name(name)] = level + nbt.pop("enchantments", None) + nbt["stored_enchantments"] = stored + return "minecraft:enchanted_book", nbt + current = dict(nbt.get("enchantments", {})) + for name, level in enchants: + current[short_name(name)] = level + nbt["enchantments"] = current + return item_id, nbt + + +def repair_cost(item) -> int: + """Prior work penalty of an item (nbt "repair_cost"): it doubles-plus-one each time the item is used in an anvil.""" + return int((getattr(item, "nbt", None) or {}).get("repair_cost", 0) or 0) + + +def anvil_merge(left, right): + """The anvil result for (left item, right item): (result ItemStack or None, cost in levels). + + The cost is the enchantments' anvil cost plus the prior work penalties of both items; the + result's penalty is max(left, right) * 2 + 1 (AnvilMenu.createResult).""" + from .inventory import ItemStack + if left is None or right is None or left.is_empty or right.is_empty: + return None, 0 + source = dict(right.nbt.get("stored_enchantments", {}) if is_book(right.item_id) + else right.nbt.get("enchantments", {})) + if is_book(right.item_id) and not source: + return None, 0 + if not is_book(right.item_id) and right.item_id != left.item_id: + return None, 0 + if not is_book(right.item_id) and not source: + return None, 0 + if not (is_book(left.item_id) or item_enchantability(left.item_id) > 0): + return None, 0 + + current = dict(left.nbt.get("stored_enchantments", {}) if is_book(left.item_id) + else left.nbt.get("enchantments", {})) + applied = [] + cost = 0 + for name, level in source.items(): + full = "minecraft:" + short_name(name) + entry = enchantment(full) + if entry is None or not accepts(left.item_id, full): + continue + if not compatible(full, list(current)): + continue + have = int(current.get(short_name(name), 0)) + if have > level: + new_level = have + elif have == level: + new_level = min(level + 1, entry["max_level"]) + else: + new_level = level + if new_level == have: + continue + current[short_name(name)] = new_level + applied.append((short_name(name), new_level)) + cost += entry["anvil_cost"] * new_level + if not applied: + return None, 0 + left_penalty, right_penalty = repair_cost(left), repair_cost(right) + total = max(1, cost + left_penalty + right_penalty) + base_nbt = {k: v for k, v in left.nbt.items() if k not in ("enchantments", "stored_enchantments", "repair_cost")} + base_nbt["repair_cost"] = max(left_penalty, right_penalty) * 2 + 1 + if is_book(left.item_id): + result_id, nbt = "minecraft:enchanted_book", dict(base_nbt, stored_enchantments=current) + else: + result_id, nbt = left.item_id, dict(base_nbt, enchantments=current) + result = ItemStack(result_id, 1, left.damage, nbt) + return result, total diff --git a/world/enchanting_window.py b/world/enchanting_window.py new file mode 100644 index 0000000..119b729 --- /dev/null +++ b/world/enchanting_window.py @@ -0,0 +1,189 @@ +""" +Enchanting table and anvil windows: offers, the enchant button, anvil output, +experience and lapis costs, and returning the inputs when the window closes. + +Window layouts: + enchanting table slot 0 = item, slot 1 = lapis lazuli + anvil slot 0 = left item, slot 1 = right item, slot 2 = result (take only) +""" + +from __future__ import annotations + +import logging +import random + +from . import enchanting +from .inventory import ItemStack + +logger = logging.getLogger("PyMC.附魔") + +ENCHANT_TABLE = "enchanting_table" +ANVIL = "anvil" +ANVIL_RESULT_SLOT = 2 +TOO_EXPENSIVE = enchanting.TOO_EXPENSIVE + +# "Too Expensive!": the anvil refuses results from TOO_EXPENSIVE levels up (vanilla). Servers can +# switch the limit off with the anvil-too-expensive-limit property. +_limit_too_expensive = True + + +def set_too_expensive_limit(enabled: bool): + global _limit_too_expensive + _limit_too_expensive = bool(enabled) + + +# clientbound "Container Set Data" (craft_progress_bar, 0x14 in 1.21.1) +_PROPERTY_PACKET = "craft_progress_bar" + + +def _is_creative(conn) -> bool: + return getattr(conn, "gamemode", "") == "creative" + + +def _block_reader(x: int, y: int, z: int): + from .block_behavior import container_manager + reader = getattr(container_manager, "block_reader", None) + return reader(x, y, z) if reader is not None else None + + +def refresh(conn, container, pos) -> dict: + """Recompute the offers (table) or the result (anvil); returns the property values to send.""" + if container.type == ENCHANT_TABLE: + item = container.items[0] + power = enchanting.bookshelf_power(_block_reader, *pos) + if item is None or item.is_empty: + container.enchant_offers = [None, None, None] + costs = [0, 0, 0] + else: + container.enchant_offers = enchanting.enchanting_offers(container.enchant_seed, item.item_id, power) + costs = enchanting.offer_costs(container.enchant_seed, item.item_id, power) + props = {0: costs[0], 1: costs[1], 2: costs[2], 3: container.enchant_seed & 0xFFFF} + for slot, offer in enumerate(container.enchant_offers): + first = offer["enchants"][0] if offer and offer["enchants"] else None + props[4 + slot] = enchanting.protocol_id(first[0]) if first else -1 + props[7 + slot] = first[1] if first else 0 + return props + if container.type == ANVIL: + result, cost = enchanting.anvil_merge(container.items[0], container.items[1]) + if result is not None and _limit_too_expensive and cost >= TOO_EXPENSIVE and not _is_creative(conn): + result = None + container.items[ANVIL_RESULT_SLOT] = result + container.anvil_cost = cost if result is not None else 0 + return {0: container.anvil_cost} + return {} + + +async def send_properties(conn, window_id: int, props: dict): + from protocol.data_types import write_short, write_ubyte + from protocol.packet_map import get_clientbound_packet + pid = get_clientbound_packet(conn.protocol_version, _PROPERTY_PACKET) + if pid is None: + return + for prop, value in props.items(): + value = int(value) + value = value - 0x10000 if value > 0x7FFF else value + await conn.send_packet(pid, write_ubyte(window_id) + write_short(prop) + write_short(value)) + + +async def open_window(conn, window_id: int, container, pos): + """Refresh a freshly opened table/anvil and send its properties and contents.""" + from world.inventory_interactions import _sync_open_container + await send_properties(conn, window_id, refresh(conn, container, pos)) + await _sync_open_container(conn, window_id) + + +def anvil_take_allowed(conn, container) -> bool: + if _is_creative(conn): + return True + return int(getattr(conn, "experience_level", 0)) >= int(getattr(container, "anvil_cost", 0)) + + +def take_anvil_result(conn, container): + """The result was taken: spend the inputs and the levels (called from the window write).""" + cost = int(getattr(container, "anvil_cost", 0)) + for slot in (0, 1): + stack = container.items[slot] + if stack is not None: + stack.count -= 1 + if stack.count <= 0: + container.items[slot] = None + container.items[ANVIL_RESULT_SLOT] = None + container.anvil_cost = 0 + if not _is_creative(conn): + _take_levels(conn, cost) + + +def _take_levels(conn, levels: int): + """Remove levels from the player (the experience bar restarts at the new level).""" + from handlers.play.join import _experience_needed_for_next_level + level = max(0, int(conn.experience_level) - levels) + conn.experience_total = sum(_experience_needed_for_next_level(lv) for lv in range(level)) + conn.experience_level = level + conn.experience_progress = 0.0 + + +async def handle_enchant_button(conn, payload: bytes, server): + """Serverbound Enchant Item: the enchanting table's button (0-2).""" + from protocol.data_types import read_ubyte, read_varint + from world.inventory_interactions import _open_container, _sync_open_container + window_id, offset = read_ubyte(payload, 0) + button, _ = read_varint(payload, offset) + if getattr(conn, "_open_window_id", None) != window_id: + return + opened = _open_container(conn, window_id) + if opened is None or opened[0] != "block" or opened[1].type != ENCHANT_TABLE: + return + container = opened[1] + pos = conn._open_container_pos + refresh(conn, container, pos) + if not 0 <= button < 3: + return + offer = container.enchant_offers[button] if container.enchant_offers else None + item, lapis = container.items[0], container.items[1] + if offer is None or item is None or item.is_empty: + return + if lapis is None or lapis.count < offer["lapis"]: + return + if not _is_creative(conn) and int(conn.experience_level) < offer["requirement"]: + return + + new_id, new_nbt = enchanting.with_enchantments(item.item_id, item.nbt, offer["enchants"]) + container.items[0] = ItemStack(new_id, 1, item.damage, new_nbt) + lapis.count -= offer["lapis"] + container.items[1] = None if lapis.count <= 0 else lapis + if not _is_creative(conn): + _take_levels(conn, offer["levels"]) + container.enchant_seed = random.getrandbits(31) + from world.advancements import trigger as advancement_trigger + advancement_trigger(conn, "adventure/enchant_item", "enchanted_item") + + props = refresh(conn, container, pos) + await send_properties(conn, window_id, props) + await _sync_open_container(conn, window_id) + from handlers.play.join import _send_set_experience + await _send_set_experience(conn) + + +def return_inputs(conn, window_id: int) -> list: + """Closing the table or anvil gives its inputs back to the player (vanilla does). + + Returns the stacks that did not fit; the caller drops them.""" + from world.inventory_interactions import _open_container + opened = _open_container(conn, window_id) + if opened is None or opened[0] != "block" or opened[1].type not in (ENCHANT_TABLE, ANVIL): + return [] + container = opened[1] + leftovers = [] + for slot in range(2): + stack = container.items[slot] + container.items[slot] = None + if stack is None or stack.is_empty or conn.inventory_obj is None: + continue + left = conn.inventory_obj.add_item(stack) + if left > 0: + extra = stack.copy() + extra.count = left + leftovers.append(extra) + if len(container.items) > ANVIL_RESULT_SLOT: + container.items[ANVIL_RESULT_SLOT] = None + return leftovers diff --git a/world/entities.py b/world/entities.py index 370b056..be40afa 100755 --- a/world/entities.py +++ b/world/entities.py @@ -148,28 +148,6 @@ def distance_squared_to(self, x: float, y: float, z: float) -> float: dz = self.z - z return dx * dx + dy * dy + dz * dz - def as_dict(self) -> dict: - return { - "entity_id": self.entity_id, - "uuid": str(self.uuid_value), - "kind": self.kind, - "x": self.x, - "y": self.y, - "z": self.z, - "yaw": self.yaw, - "pitch": self.pitch, - "vx": self.vx, - "vy": self.vy, - "vz": self.vz, - "on_ground": self.on_ground, - "alive": self.alive, - "age_ticks": self.age_ticks, - "persistent": self.persistent, - "custom_name": self.custom_name, - "metadata": dict(self.metadata), - } - - @dataclass class ItemEntity(Entity): item_name: str = "minecraft:stone" @@ -258,20 +236,26 @@ def __init__(self, entity_id: int, x: float, y: float, z: float, } def tick(self, server, native_ai=None): + if not self.tick_begin(server): + return + used_native_ai = native_ai.tick_mob(self, server) if native_ai is not None else False + self.tick_finish(server, used_native_ai) + + def tick_begin(self, server) -> bool: + """Everything before the AI decision. Returns False when this tick ends here.""" super().tick(server) if getattr(self, "invulnerable_ticks", 0) > 0: self.invulnerable_ticks -= 1 if self.invulnerable_ticks == 0: self.last_hurt = 0.0 if not self.ai_enabled: - return + return False if self.attack_cooldown > 0: self.attack_cooldown -= 1 + return True - used_native_ai = False - if native_ai is not None: - used_native_ai = native_ai.tick_mob(self, server) - + def tick_finish(self, server, used_native_ai: bool): + """The AI (unless the native one already decided) and the physics of this tick.""" if not used_native_ai: if self.profile.get("category") == "hostile": self._tick_hostile_ai(server) @@ -564,6 +548,8 @@ class EntityManager: def __init__(self, server): self.server = server self.entities: dict[int, Entity] = {} + self._by_kind: dict[str, dict[int, Entity]] = {} # kind -> id -> entity (index for of_kind) + self.tick_stamp = 0 # increases every tick (per-tick caches) self.spawned_at: dict[int, float] = {} self.removed_ids: list[int] = [] self.native_ai = None @@ -605,6 +591,7 @@ def create_lightning(self, x: float, y: float, z: float) -> LightningBoltEntity: def add_entity(self, entity: Entity): self.entities[entity.entity_id] = entity + self._by_kind.setdefault(entity.kind, {})[entity.entity_id] = entity self.spawned_at[entity.entity_id] = time.time() def remove_entity(self, entity_id: int) -> Entity | None: @@ -612,8 +599,15 @@ def remove_entity(self, entity_id: int) -> Entity | None: entity = self.entities.pop(entity_id, None) if entity is not None: self.removed_ids.append(entity_id) + bucket = self._by_kind.get(entity.kind) + if bucket is not None: + bucket.pop(entity_id, None) return entity + def of_kind(self, kind: str) -> list[Entity]: + """Living entities of one kind, without scanning every entity.""" + return [entity for entity in self._by_kind.get(kind, {}).values() if entity.alive] + def get_entity(self, entity_id: int) -> Entity | None: return self.entities.get(entity_id) @@ -629,64 +623,22 @@ def count_by_kind(self) -> dict[str, int]: def count_mobs(self) -> int: return sum(1 for entity in self.list_entities() if entity.kind == "mob") - def spawn_natural_mobs(self, max_spawned: int = 2, cap: int = 32) -> int: - """Spawn a small vanilla-inspired trickle near players.""" - players = self.server.get_online_players() - if not players or self.count_mobs() >= cap: - return 0 - - terrain = getattr(self.server, "terrain_generator", None) - if terrain is None: - return 0 - - spawned = 0 - rng = random.Random(int(time.time() * 20) ^ self.server.next_entity_id) - is_night = 13000 <= int(getattr(self.server, "world_time", 0)) <= 23000 - - for player in players: - if spawned >= max_spawned or self.count_mobs() >= cap: - break - if player.gamemode == "spectator": - continue - - angle = rng.random() * math.tau - radius = rng.randint(24, 48) - x = math.floor(player.x + math.cos(angle) * radius) - z = math.floor(player.z + math.sin(angle) * radius) - try: - y = int(terrain.get_terrain_height(x, z)) + 1 - except Exception: - continue - - if abs(x - player.x) < 24 and abs(z - player.z) < 24: - continue - if not _is_passable(self.server.get_block_at(x, y, z)): - continue - if not _is_solid(self.server.get_block_at(x, y - 1, z)): - continue - - config = getattr(self.server, "config", {}) - if is_night: - # spawn-monsters=false 或和平难度下不生成敌对生物 - if (not config.get("spawn-monsters", True) - or str(config.get("difficulty", "easy")).lower() == "peaceful"): - continue - mob_type = rng.choice(["zombie", "skeleton", "creeper", "spider"]) - else: - if not config.get("spawn-animals", True): - continue - mob_type = rng.choice(["pig", "cow", "sheep"]) - self.create_mob(x + 0.5, y, z + 0.5, mob_type=mob_type) - spawned += 1 - - return spawned - def tick(self): + self.tick_stamp += 1 to_remove: list[int] = [] + mobs_for_native: list = [] + finishing: list = [] for entity in self.entities.values(): if not entity.alive: to_remove.append(entity.entity_id) continue + if isinstance(entity, MobEntity) and self.native_ai is not None: + if entity.tick_begin(self.server): + mobs_for_native.append(entity) + finishing.append(entity) + if not entity.alive: + to_remove.append(entity.entity_id) + continue if isinstance(entity, MobEntity): entity.tick(self.server, self.native_ai) else: @@ -694,6 +646,14 @@ def tick(self): if not entity.alive: to_remove.append(entity.entity_id) + # every mob's AI in one native round trip, then each mob's remaining steps + if mobs_for_native: + done = self.native_ai.tick_batch(mobs_for_native, self.server) # ids of mobs it decided for + for entity in finishing: + entity.tick_finish(self.server, id(entity) in done) + if not entity.alive: + to_remove.append(entity.entity_id) + for entity_id in to_remove: self.remove_entity(entity_id) diff --git a/world/fluids.py b/world/fluids.py index 317660b..4cbf3f9 100755 --- a/world/fluids.py +++ b/world/fluids.py @@ -28,12 +28,9 @@ """ import logging -from collections import deque -from typing import Optional from .blocks import ( AIR, WATER, LAVA, STONE, COBBLESTONE, OBSIDIAN, - BEDROCK, ) from .chunk_io import STATE_ID_TO_BLOCK, BLOCK_KEY_TO_STATE_ID @@ -288,7 +285,6 @@ def _process_flow(self, x: int, y: int, z: int, current_state: int, fluid_type: str, remaining: list): """Process flow for a single fluid block.""" from world.editing import set_world_block - from handlers.play.blocks import _broadcast_block_change level = _get_fluid_level(current_state) is_source = (level == 0) @@ -454,57 +450,3 @@ def _notify_fluid_update(self, x: int, y: int, z: int, new_state: int): self.server._fluid_updates = getattr(self.server, '_fluid_updates', []) self.server._fluid_updates.append((x, y, z, new_state)) - def get_fluid_level(self, x: int, y: int, z: int) -> int: - """ - Get fluid level at position. - Returns 0 for source, 1-7 for flowing, -1 for no fluid. - """ - block = self.server.get_block_at(x, y, z) - if block is None: - return -1 - return _get_fluid_level(block) - - def is_fluid_source(self, x: int, y: int, z: int) -> bool: - """Check if the fluid at a position is a source block.""" - level = self.get_fluid_level(x, y, z) - return level == 0 - - def scan_chunk_for_fluids(self, chunk_x: int, chunk_z: int, - chunk_blocks) -> list[tuple[int, int, int, str]]: - """ - Scan a newly loaded chunk for fluid blocks. - Returns list of (x, y, z, fluid_type) for all fluid blocks found. - """ - fluids = [] - for local_y in range(len(chunk_blocks)): - for local_z in range(16): - for local_x in range(16): - state_id = chunk_blocks[local_y][local_z][local_x] - if _is_water(state_id): - world_x = chunk_x * 16 + local_x - world_y = local_y - 64 # Adjust for MIN_Y - world_z = chunk_z * 16 + local_z - fluids.append((world_x, world_y, world_z, "water")) - elif _is_lava(state_id): - world_x = chunk_x * 16 + local_x - world_y = local_y - 64 - world_z = chunk_z * 16 + local_z - fluids.append((world_x, world_y, world_z, "lava")) - return fluids - - def count_fluid_blocks(self) -> dict[str, int]: - """Count total tracked fluid blocks by type.""" - water_count = 0 - lava_count = 0 - for x, y, z in self.fluid_sources: - block = self.server.get_block_at(x, y, z) - if block is not None: - if _is_water(block): - water_count += 1 - elif _is_lava(block): - lava_count += 1 - return {"water": water_count, "lava": lava_count} - - def get_pending_count(self) -> int: - """Get number of pending flow updates.""" - return len(self.pending_flows) diff --git a/world/generate_blocks.py b/world/generate_blocks.py deleted file mode 100755 index c252b48..0000000 --- a/world/generate_blocks.py +++ /dev/null @@ -1,62 +0,0 @@ -import urllib.request -import json -import os - -input_path = "blocks.json" -output_path = r"C:\Users\hekuo\Desktop\1\pymc\world\blocks.py" - -try: - print(f"正在从 {input_path} 读取数据...") - with open(input_path, 'r', encoding='utf-8') as f: - data = json.load(f) - - # 按 ID 从小到大排列 - data.sort(key=lambda x: x['id']) - - print(f"正在生成文件: {output_path}") - with open(output_path, 'w', encoding='utf-8') as f: - # 头部注释 - f.write("# -*- coding: utf-8 -*-\n") - f.write("# 自动从 PrismarineJS minecraft-data 提取\n") - f.write("# Minecraft 1.21.1 方块状态 ID 注册表 (全局调色板)\n\n") - - state_to_name_lines = [] - - for block in data: - name = block['name'] - display_name = block.get('displayName', name) - default_state = block['defaultState'] - - # 变量命名规则: 方块名大写 - # 处理可能的特殊字符(虽然 Minecraft 命名通常很规范) - var_name = name.upper().replace(" ", "_").replace("-", "_") - - # 写入常量 - f.write(f"{var_name} = {default_state} # {display_name}\n") - - # 准备反向字典条目 - state_to_name_lines.append(f" {default_state}: \"{name}\",") - - # 写入反向字典 - f.write("\n# 方块状态 ID 到名称的映射 (只包含 defaultState)\n") - f.write("STATE_TO_NAME = {\n") - # 由于可能存在多个方块对应同一个 defaultState (虽然在 Minecraft 中不太可能,但为了安全按 ID 排序) - # 这里的 state_to_name 要求是 0: "air", 1: "stone" - # 按照 state_id 排序写入 - - # 重新整理字典以确保唯一性并排序 - state_map = {block['defaultState']: block['name'] for block in data} - sorted_states = sorted(state_map.keys()) - - for state_id in sorted_states: - f.write(f" {state_id}: \"{state_map[state_id]}\",\n") - - f.write("}\n") - - print(f"成功生成 {len(data)} 个方块的常量定义。") - -except Exception as e: - print(f"发生错误: {e}") - import traceback - traceback.print_exc() - exit(1) diff --git a/world/inventory.py b/world/inventory.py index 8a5c760..1ed8995 100755 --- a/world/inventory.py +++ b/world/inventory.py @@ -17,12 +17,10 @@ 45: Crafting result (client-side only) """ -import copy import logging -from typing import Optional from protocol.data_types import ( - write_varint, write_boolean, write_byte, write_short, + write_varint, write_short, ) logger = logging.getLogger("PyMC.物品栏") @@ -157,11 +155,6 @@ def protocol_id_to_item_name(protocol_id: int) -> str: } -def block_name_to_item_name(block_name: str) -> str: - """Convert a block name to the item it drops when mined without silk touch.""" - return BLOCK_TO_ITEM_OVERRIDES.get(block_name, block_name) - - # -------------------------------------------------- # ItemStack # -------------------------------------------------- @@ -212,14 +205,6 @@ def from_dict(d: dict) -> 'ItemStack': # --- Backward compatibility methods --- - def is_empty_method(self) -> bool: - """Check if this stack is empty (method version for backward compat).""" - return self.is_empty - - def max_stack_size_method(self) -> int: - """Get max stack size (method version for backward compat).""" - return self.max_stack_size - def can_stack_with(self, other: 'ItemStack | None') -> bool: """Check if this stack can be combined with another.""" if other is None or other.is_empty: @@ -251,15 +236,6 @@ def get_tool_tier(self) -> str | None: """Get the tool tier if this item is a tiered tool.""" return TOOL_TIER_FROM_ITEM.get(self.item_id) - def get_mining_speed(self) -> float: - """Get the mining speed multiplier for this tool.""" - tier = self.get_tool_tier() - if tier: - return TOOL_TIER_SPEED.get(tier, 1.0) - if self.item_id == "minecraft:shears": - return 1.0 - return 1.0 - def __repr__(self) -> str: if self.is_empty: return "ItemStack(empty)" @@ -397,12 +373,6 @@ def count_item(self, item_id: str) -> int: total += slot.count return total - def swap_slots(self, a: int, b: int): - """Swap the contents of two slots.""" - if 0 <= a < self.TOTAL_SLOTS and 0 <= b < self.TOTAL_SLOTS: - self.slots[a], self.slots[b] = self.slots[b], self.slots[a] - self.state_id += 1 - def clear(self): """Clear all inventory slots.""" self.slots = [None] * self.TOTAL_SLOTS @@ -436,16 +406,6 @@ def get_armor(self) -> list[ItemStack | None]: """Get the 4 armor slots (boots, leggings, chestplate, helmet).""" return list(self.slots[36:40]) - def get_offhand(self) -> ItemStack | None: - """Get the offhand item.""" - return self.slots[40] - - def get_hotbar_slot(self, index: int) -> ItemStack | None: - """Get an item from the hotbar (0-8).""" - if 0 <= index < 9: - return self.slots[index] - return None - def set_held_slot(self, slot: int): """Set the currently selected hotbar slot (0-8).""" if 0 <= slot < 9: @@ -532,19 +492,47 @@ def from_legacy(cls, data: dict) -> 'PlayerInventory': """Create from legacy serialization format.""" return cls.deserialize_full(data) - def to_legacy_tuple(self, slot: int) -> tuple[str, int] | None: - """Convert a slot to legacy tuple format for old code compatibility.""" - item = self.get_slot(slot) - if item is None or item.is_empty: - return None - return (item.item_id, item.count) - - # -------------------------------------------------- # Protocol Encoding # -------------------------------------------------- SLOT_COMPONENT_DAMAGE = 3 # minecraft:damage in the 1.21.1 data component registry +SLOT_COMPONENT_ENCHANTMENTS = 9 # minecraft:enchantments (ItemEnchantments) +SLOT_COMPONENT_STORED_ENCHANTMENTS = 23 # minecraft:stored_enchantments (enchanted books) +SLOT_COMPONENT_POTION_CONTENTS = 31 # minecraft:potion_contents +POTION_ITEM_IDS = {"minecraft:potion", "minecraft:splash_potion", "minecraft:lingering_potion"} + + +def _potion_payload(name: str) -> bytes | None: + """PotionContents: optional potion id, optional custom colour, custom effects, optional custom name.""" + from protocol.data_types import write_boolean + from world.potions import protocol_id + registry_id = protocol_id(name) + if registry_id is None: + return None + return (write_boolean(True) + write_varint(registry_id) # potion + + write_boolean(False) # no custom colour + + write_varint(0) # no custom effects + + write_boolean(False)) # no custom name + + +def _enchantments_payload(levels: dict) -> bytes | None: + """ItemEnchantments: count, (registry id, level) pairs, show tooltip.""" + from protocol.data_types import write_boolean + from world.enchanting import protocol_id + entries = [] + for name, level in levels.items(): + registry_id = protocol_id(name) + if registry_id is not None and int(level) > 0: + entries.append((registry_id, int(level))) + if not entries: + return None + out = bytearray(write_varint(len(entries))) + for registry_id, level in entries: + out.extend(write_varint(registry_id)) + out.extend(write_varint(level)) + out.extend(write_boolean(True)) + return bytes(out) def encode_slot_entry(item: ItemStack | None) -> bytes: @@ -594,6 +582,20 @@ def encode_slot_entry(item: ItemStack | None) -> bytes: components.extend(write_varint(SLOT_COMPONENT_DAMAGE)) components.extend(write_varint(min(damage, item.max_durability))) component_count += 1 + nbt = getattr(item, "nbt", None) or {} + if item.item_id in POTION_ITEM_IDS and nbt.get("potion"): + potion_data = _potion_payload(str(nbt["potion"])) + if potion_data is not None: + components.extend(write_varint(SLOT_COMPONENT_POTION_CONTENTS)) + components.extend(potion_data) + component_count += 1 + for key, component in (("enchantments", SLOT_COMPONENT_ENCHANTMENTS), + ("stored_enchantments", SLOT_COMPONENT_STORED_ENCHANTMENTS)): + enchant_data = _enchantments_payload(nbt.get(key) or {}) + if enchant_data is not None: + components.extend(write_varint(component)) + components.extend(enchant_data) + component_count += 1 payload.extend(write_varint(component_count)) # addedComponentCount payload.extend(write_varint(0)) # removedComponentCount @@ -632,14 +634,51 @@ def decode_slot_entry(data: bytes, offset: int = 0) -> tuple[ItemStack | None, i added_count, offset = read_varint(data, offset) removed_count, offset = read_varint(data, offset) damage = 0 + nbt: dict = {} for index in range(added_count): component_type, offset = read_varint(data, offset) if component_type == SLOT_COMPONENT_DAMAGE: damage, offset = read_varint(data, offset) elif component_type in (1, 2): # max_stack_size / max_damage: VarInt _value, offset = read_varint(data, offset) + elif component_type in (SLOT_COMPONENT_ENCHANTMENTS, SLOT_COMPONENT_STORED_ENCHANTMENTS): + from world.enchanting import name_of_protocol_id + from protocol.data_types import read_boolean + count, offset = read_varint(data, offset) + levels = {} + for _ in range(count): + registry_id, offset = read_varint(data, offset) + level, offset = read_varint(data, offset) + name = name_of_protocol_id(registry_id) + if name is not None: + levels[name.split(":", 1)[-1]] = level + _show_tooltip, offset = read_boolean(data, offset) + key = "enchantments" if component_type == SLOT_COMPONENT_ENCHANTMENTS else "stored_enchantments" + if levels: + nbt[key] = levels + elif component_type == SLOT_COMPONENT_POTION_CONTENTS: + from protocol.data_types import read_boolean, read_int, read_string + from world.potions import name_of_protocol_id + has_potion, offset = read_boolean(data, offset) + if has_potion: + potion_id, offset = read_varint(data, offset) + name = name_of_protocol_id(potion_id) + if name is not None: + nbt["potion"] = name + has_colour, offset = read_boolean(data, offset) + if has_colour: + _colour, offset = read_int(data, offset) + effects, offset = read_varint(data, offset) + if effects: + # custom effects are not used by the server; their layout is not parsed + offset = len(data) + removed_count = 0 + break + has_name, offset = read_boolean(data, offset) + if has_name: + _custom_name, offset = read_string(data, offset) else: - # Other component payloads (names, enchantments, potion contents...) + # Other component payloads (names, potion contents...) # are not decoded; the rest of this slot cannot be parsed reliably. offset = len(data) removed_count = 0 @@ -647,7 +686,7 @@ def decode_slot_entry(data: bytes, offset: int = 0) -> tuple[ItemStack | None, i for _ in range(removed_count): _removed_type, offset = read_varint(data, offset) - item = ItemStack(item_id=item_name, count=max(1, item_count), damage=damage) + item = ItemStack(item_id=item_name, count=max(1, item_count), damage=damage, nbt=nbt) return (item, offset) diff --git a/world/inventory_interactions.py b/world/inventory_interactions.py index f9ff800..543b4c3 100644 --- a/world/inventory_interactions.py +++ b/world/inventory_interactions.py @@ -89,6 +89,8 @@ def window_slot_location(conn, window_id: int, slot_idx: int, player_slot_mapper return ('player', slot_idx - 37) # 37-45 -> hotbar 0-8 return None container_size = len(opened[1].items if opened[0] == 'block' else opened[1].ender_chest) + if opened[0] == 'block' and getattr(opened[1], 'type', '') == 'anvil' and slot_idx == 2: + return ('anvil_result', 0) # take only; see world/enchanting_window.py if slot_idx < container_size: return (opened[0], slot_idx) if slot_idx < container_size + 27: @@ -111,6 +113,9 @@ def _read_window_slot(conn, location): return store[idx] if kind == 'ender_chest': return inv.ender_chest[idx] + if kind == 'anvil_result': + opened = _open_container(conn, getattr(conn, '_open_window_id', -1)) + return opened[1].items[2] if opened is not None and opened[0] == 'block' else None opened = _open_container(conn, getattr(conn, '_open_window_id', -1)) if opened is not None and opened[0] == 'block': return opened[1].items[idx] @@ -126,6 +131,14 @@ def _write_window_slot(conn, location, item): return if kind == 'craft_result': return + if kind == 'anvil_result': + # the result is only ever taken: placing items on it is refused + if item is None: + opened = _open_container(conn, getattr(conn, '_open_window_id', -1)) + if opened is not None and opened[0] == 'block' and opened[1].items[2] is not None: + from world.enchanting_window import take_anvil_result + take_anvil_result(conn, opened[1]) + return if kind == 'craft': from .crafting_window import grid_slots store, _, _ = grid_slots(conn, getattr(conn, '_open_window_id', None)) @@ -615,6 +628,23 @@ async def handle_container_click(conn, payload: bytes, server, player_slot_mappe mutated = True crafting = False leftovers: list = [] + special = None + opened_now = _open_container(conn, window_id) if window_id != 0 else None + if opened_now is not None and opened_now[0] == 'block' and getattr(opened_now[1], 'type', '') == 'anvil': + special = 'anvil' + if slot_idx == 2 and mode == 2: + # a hotbar key swap would put items on the result: refused + await _sync_open_container(conn, window_id) + return + if slot_idx == 2 and mode in (0, 1, 4): + from world.enchanting_window import anvil_take_allowed + if inv.carried_item is not None or not anvil_take_allowed(conn, opened_now[1]): + # no taking the result into a held item, or without the levels for it + await _sync_open_container(conn, window_id) + return + elif opened_now is not None and opened_now[0] == 'block' and getattr(opened_now[1], 'type', '') == 'enchanting_table': + special = 'enchanting' + from .crafting_window import is_crafting_window, refresh_result grid_before = None if is_crafting_window(conn, window_id): @@ -699,6 +729,12 @@ async def handle_container_click(conn, payload: bytes, server, player_slot_mappe if crafting: refresh_result(conn, window_id) + if special is not None and window_id != 0: + from world.enchanting_window import refresh, send_properties + opened_after = _open_container(conn, window_id) + if opened_after is not None and opened_after[0] == 'block': + props = refresh(conn, opened_after[1], conn._open_container_pos) + await send_properties(conn, window_id, props) contents = _window_contents(conn, window_id) if contents is None: diff --git a/world/lighting.py b/world/lighting.py index 47ec14b..dfc8967 100644 --- a/world/lighting.py +++ b/world/lighting.py @@ -25,7 +25,11 @@ from __future__ import annotations +import ctypes +import threading +from array import array from collections import deque +from itertools import chain SECTION_VOLUME = 4096 LAYER = 256 @@ -80,7 +84,7 @@ def _spread(light: bytearray, queue: deque, blocks, opacity: list[int], height: queue.append((nx, ny, nz)) -def compute_light(blocks) -> tuple[bytearray, bytearray]: +def _compute_python(blocks) -> tuple[bytearray, bytearray]: """ Compute light for one chunk column. @@ -174,6 +178,72 @@ def compute_light(blocks) -> tuple[bytearray, bytearray]: return sky, block_light +_native = None # the loaded native library with the light tables set, False if unavailable +_native_lock = threading.Lock() + + +def _native_lib(): + """The native engine (vrs_light_*) with the tables set, or None to use the Python version.""" + global _native + if _native is None: + with _native_lock: + if _native is None: + _native = False + try: + from world.rs.native import load_library + lib = load_library() + except Exception: # the Python version is always there + lib = None + if lib is not None: + opacity, emission, _ = _light_tables() + lib.vrs_light_set_tables(bytes(opacity), bytes(emission), len(opacity)) + _native = lib + return _native or None + + +def _address(buffer: bytearray) -> int: + return ctypes.addressof((ctypes.c_char * len(buffer)).from_buffer(buffer)) + + +def _compute_native(lib, blocks) -> tuple[bytearray, bytearray]: + height = len(blocks) + flat = array("H", chain.from_iterable(chain.from_iterable(blocks))) + sky = bytearray(height * LAYER) + block_light = bytearray(height * LAYER) + lib.vrs_light_compute(flat.buffer_info()[0], height, _address(sky), _address(block_light)) + return sky, block_light + + +def compute_light_flat(flat, height: int | None = None) -> tuple[bytearray, bytearray]: + """ + Same as compute_light, for blocks already in a flat ``array('H')`` (index + ``y * 256 + z * 16 + x``). This is the fast path: the native engine reads the + array directly, while the nested-list form costs a few milliseconds to flatten. + """ + if height is None: + height = len(flat) // LAYER + lib = _native_lib() + if lib is not None: + sky = bytearray(height * LAYER) + block_light = bytearray(height * LAYER) + lib.vrs_light_compute(flat.buffer_info()[0], height, _address(sky), _address(block_light)) + return sky, block_light + nested = [[[flat[y * LAYER + z * 16 + x] for x in range(16)] for z in range(16)] for y in range(height)] + return _compute_python(nested) + + +def compute_light(blocks) -> tuple[bytearray, bytearray]: + """ + Compute light for one chunk column. + + ``blocks`` is the ``[y][z][x]`` state-id array. Returns flat + ``(sky, block)`` arrays indexed ``y * 256 + z * 16 + x`` with levels 0-15. + """ + # Nested lists: the Python version is faster (flattening them costs more than the + # native call saves). Flat arrays go to the native engine: see compute_light_flat. + return _compute_python(blocks) + + _FULL = b"\x0f" * SECTION_VOLUME _EMPTY = bytes(SECTION_VOLUME) _FULL_NIBBLES = b"\xff" * 2048 diff --git a/world/minecart.py b/world/minecart.py index 5682cea..fb12c40 100644 --- a/world/minecart.py +++ b/world/minecart.py @@ -174,12 +174,15 @@ def _push_entities(self, server): px, py, pz = player.x, player.y, player.z if px + 0.3 > x0 and px - 0.3 < x1 and pz + 0.3 > z0 and pz - 0.3 < z1 and py + 1.8 > y0 and py < y1: self._pushed_by(px, pz) - for other in minecarts(server): - if other is self or not other.alive: - continue - (ox0, oy0, oz0), (ox1, oy1, oz1) = other.bounding_box() - if ox1 > x0 and ox0 < x1 and oz1 > z0 and oz0 < z1 and oy1 > y0 and oy0 < y1: - other.collide_with(self) + grid = _cart_grid(server) + for gx in range(math.floor(x0 / _GRID_CELL), math.floor(x1 / _GRID_CELL) + 1): + for gz in range(math.floor(z0 / _GRID_CELL), math.floor(z1 / _GRID_CELL) + 1): + for other in grid.get((gx, gz), ()): + if other is self or not other.alive: + continue + (ox0, oy0, oz0), (ox1, oy1, oz1) = other.bounding_box() + if ox1 > x0 and ox0 < x1 and oz1 > z0 and oz0 < z1 and oy1 > y0 and oy0 < y1: + other.collide_with(self) def _pushed_by(self, px: float, pz: float): """Entity.push(minecart) from a player: away from them, 0.05 at most.""" @@ -351,7 +354,25 @@ def minecarts(server) -> list: manager = getattr(server, "entity_manager", None) if manager is None: return [] - return [e for e in manager.list_entities() if isinstance(e, MinecartEntity)] + return manager.of_kind("minecart") + + +_GRID_CELL = 2.0 + + +def _cart_grid(server) -> dict: + """Minecarts bucketed by 2x2-block cells; rebuilt once per entity tick.""" + manager = getattr(server, "entity_manager", None) + stamp = getattr(manager, "tick_stamp", None) + cached = getattr(server, "_cart_grid", None) + if cached is not None and cached[0] == stamp: + return cached[1] + grid: dict = {} + for cart in minecarts(server): + key = (math.floor(cart.x / _GRID_CELL), math.floor(cart.z / _GRID_CELL)) + grid.setdefault(key, []).append(cart) + server._cart_grid = (stamp, grid) + return grid def hopper_minecarts(server) -> list: diff --git a/world/potions.py b/world/potions.py new file mode 100644 index 0000000..b703374 --- /dev/null +++ b/world/potions.py @@ -0,0 +1,32 @@ +""" +Potion registry ids (minecraft:potion, a static registry of the 1.21.1 client). + +The id of a potion is its index in world/data/potions.json, the registration order of the +registry. Potion contents (the potion's name) travel in the potion_contents item component. +""" + +from __future__ import annotations + +import json +from functools import lru_cache +from pathlib import Path + +DATA_FILE = Path(__file__).resolve().parent / "data" / "potions.json" + + +@lru_cache(maxsize=1) +def _names() -> tuple[str, ...]: + with open(DATA_FILE, "r", encoding="utf-8") as f: + return tuple(json.load(f)["names"]) + + +def protocol_id(name: str) -> int | None: + """Registry id of a potion (``awkward``, ``minecraft:long_swiftness``, ...).""" + short = name.split(":", 1)[-1] + names = _names() + return names.index(short) if short in names else None + + +def name_of_protocol_id(index: int) -> str | None: + names = _names() + return names[index] if 0 <= index < len(names) else None diff --git a/world/redstone.py b/world/redstone.py index 6fb94fe..cd6fef3 100644 --- a/world/redstone.py +++ b/world/redstone.py @@ -1,9 +1,8 @@ """ -Redstone entry point. The engine is the vanilla-accurate port in world.rs; -the previous approximate engine is kept in world.redstone_legacy for reference. +Redstone entry point. The engine is the vanilla-accurate port in world.rs. """ -from .chunk_io import BLOCK_KEY_TO_STATE_ID, BLOCK_NAME_TO_DEFAULT_STATE, STATE_ID_TO_BLOCK +from .chunk_io import STATE_ID_TO_BLOCK from .rs import RedstoneEngine, is_redstone_block # noqa: F401 @@ -11,11 +10,3 @@ def _get_block_name(block_state_id: int) -> str: return STATE_ID_TO_BLOCK.get(block_state_id, ("minecraft:air", {}))[0] -def _get_block_props(block_state_id: int) -> dict: - return STATE_ID_TO_BLOCK.get(block_state_id, ("minecraft:air", {}))[1] - - -def resolve_state_id(block_name: str, **properties) -> int: - from .rs.core import with_props - state = BLOCK_NAME_TO_DEFAULT_STATE.get(block_name, 0) - return with_props(state, **properties) if properties else state diff --git a/world/redstone_legacy.py b/world/redstone_legacy.py deleted file mode 100755 index baef487..0000000 --- a/world/redstone_legacy.py +++ /dev/null @@ -1,2235 +0,0 @@ -# ============================================================ -# PyMC - Redstone Engine -# Tick-based redstone simulation for Minecraft 1.21.1 -# ============================================================ - -""" -Redstone simulation engine that handles all redstone components -including wires, torches, repeaters, comparators, pistons, -power sources, and mechanical block activations. - -Design: - - Runs every 2 game ticks (0.1s = 1 redstone tick) - - Uses dirty-flag system for efficiency - - BFS-based signal propagation from power sources - - Scheduled updates for delayed components (repeaters, torches) - - Integrates with the world block system via server.get_block_at / set_world_block - - Optional C++ native acceleration via NativeCore -""" - -import logging -import time -from collections import deque -from dataclasses import dataclass, field -from typing import Optional - -from .chunk_io import BLOCK_KEY_TO_STATE_ID, STATE_ID_TO_BLOCK, BLOCK_NAME_TO_DEFAULT_STATE -from .blocks import AIR - -logger = logging.getLogger("PyMC.Redstone") - -# -------------------------------------------------- -# Direction helpers -# -------------------------------------------------- - -# Facing directions used by many redstone components -FACING_DX = { - "north": (0, 0, -1), - "south": (0, 0, 1), - "east": (1, 0, 0), - "west": (-1, 0, 0), - "up": (0, 1, 0), - "down": (0, -1, 0), -} - -# Reverse facing -FACING_OPPOSITE = { - "north": "south", - "south": "north", - "east": "west", - "west": "east", - "up": "down", - "down": "up", -} - -# 6 cardinal neighbors -SIX_DIRS = [(0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1), (1, 0, 0), (-1, 0, 0)] - -# 4 horizontal neighbors -HORIZONTAL_DIRS = [(0, 0, 1), (0, 0, -1), (1, 0, 0), (-1, 0, 0)] - -# Button durations in redstone ticks (1 redstone tick = 2 game ticks) -BUTTON_DURATIONS = { - "stone": 10, # 10 redstone ticks (1s) - "polished_blackstone": 10, -} -WOOD_BUTTON_DURATION = 15 # 15 redstone ticks (1.5s) for all wood buttons - -# Torches burn out after toggling this many times within the burnout window -TORCH_BURNOUT_THRESHOLD = 8 -TORCH_BURNOUT_DURATION = 160 # 160 redstone ticks (8 seconds) burnout - -# World constants -MIN_Y = -64 -MAX_Y = 319 - -# Piston push limit -PISTON_PUSH_LIMIT = 12 - - -# -------------------------------------------------- -# Block name classification -# -------------------------------------------------- - -def _get_block_name(block_state_id: int) -> str: - """Get the minecraft block name from a block state ID.""" - if block_state_id in STATE_ID_TO_BLOCK: - return STATE_ID_TO_BLOCK[block_state_id][0] - return "" - - -def _get_block_props(block_state_id: int) -> dict[str, str]: - """Get block state properties from a block state ID.""" - if block_state_id in STATE_ID_TO_BLOCK: - return STATE_ID_TO_BLOCK[block_state_id][1] - return {} - - -def resolve_state_id(block_name: str, **properties) -> int: - """Resolve a block name + properties to a block state ID. - - Returns the default state ID if the exact combination is not found. - """ - key = (block_name, tuple(sorted(properties.items()))) - if key in BLOCK_KEY_TO_STATE_ID: - return BLOCK_KEY_TO_STATE_ID[key] - # Fallback: try default state - return BLOCK_NAME_TO_DEFAULT_STATE.get(block_name, 0) - - -# -------------------------------------------------- -# Component classification sets -# -------------------------------------------------- - -# Blocks that are redstone power sources (tracked by the engine) -REDSTONE_POWER_SOURCES = { - "minecraft:lever", - "minecraft:stone_button", "minecraft:oak_button", "minecraft:spruce_button", - "minecraft:birch_button", "minecraft:jungle_button", "minecraft:acacia_button", - "minecraft:cherry_button", "minecraft:dark_oak_button", "minecraft:mangrove_button", - "minecraft:bamboo_button", "minecraft:crimson_button", "minecraft:warped_button", - "minecraft:polished_blackstone_button", - "minecraft:stone_pressure_plate", "minecraft:oak_pressure_plate", - "minecraft:spruce_pressure_plate", "minecraft:birch_pressure_plate", - "minecraft:jungle_pressure_plate", "minecraft:acacia_pressure_plate", - "minecraft:cherry_pressure_plate", "minecraft:dark_oak_pressure_plate", - "minecraft:mangrove_pressure_plate", "minecraft:bamboo_pressure_plate", - "minecraft:crimson_pressure_plate", "minecraft:warped_pressure_plate", - "minecraft:polished_blackstone_pressure_plate", - "minecraft:light_weighted_pressure_plate", "minecraft:heavy_weighted_pressure_plate", - "minecraft:redstone_block", - "minecraft:daylight_detector", - "minecraft:tripwire_hook", - "minecraft:target", - "minecraft:detector_rail", -} - -REDSTONE_WIRE_NAMES = {"minecraft:redstone_wire"} - -REDSTONE_TORCH_NAMES = {"minecraft:redstone_torch", "minecraft:redstone_wall_torch"} - -REDSTONE_REPEATER_NAMES = {"minecraft:repeater"} - -REDSTONE_COMPARATOR_NAMES = {"minecraft:comparator"} - -REDSTONE_OBSERVER_NAMES = {"minecraft:observer"} - -PISTON_NAMES = {"minecraft:piston", "minecraft:sticky_piston"} - -# Container blocks that comparators can read -CONTAINER_NAMES = { - "minecraft:chest", "minecraft:trapped_chest", "minecraft:barrel", - "minecraft:hopper", "minecraft:dropper", "minecraft:dispenser", - "minecraft:furnace", "minecraft:blast_furnace", "minecraft:smoker", - "minecraft:brewing_stand", "minecraft:shulker_box", - "minecraft:white_shulker_box", "minecraft:orange_shulker_box", - "minecraft:magenta_shulker_box", "minecraft:light_blue_shulker_box", - "minecraft:yellow_shulker_box", "minecraft:lime_shulker_box", - "minecraft:pink_shulker_box", "minecraft:gray_shulker_box", - "minecraft:light_gray_shulker_box", "minecraft:cyan_shulker_box", - "minecraft:purple_shulker_box", "minecraft:blue_shulker_box", - "minecraft:brown_shulker_box", "minecraft:green_shulker_box", - "minecraft:red_shulker_box", "minecraft:black_shulker_box", - "minecraft:ender_chest", "minecraft:lectern", -} - -# Blocks that react to redstone signals -REDSTONE_ACTIVATABLE = { - "minecraft:oak_door", "minecraft:spruce_door", "minecraft:birch_door", - "minecraft:jungle_door", "minecraft:acacia_door", "minecraft:cherry_door", - "minecraft:dark_oak_door", "minecraft:mangrove_door", "minecraft:bamboo_door", - "minecraft:iron_door", "minecraft:crimson_door", "minecraft:warped_door", - "minecraft:oak_trapdoor", "minecraft:spruce_trapdoor", "minecraft:birch_trapdoor", - "minecraft:jungle_trapdoor", "minecraft:acacia_trapdoor", "minecraft:cherry_trapdoor", - "minecraft:dark_oak_trapdoor", "minecraft:mangrove_trapdoor", "minecraft:bamboo_trapdoor", - "minecraft:iron_trapdoor", "minecraft:crimson_trapdoor", "minecraft:warped_trapdoor", - "minecraft:oak_fence_gate", "minecraft:spruce_fence_gate", "minecraft:birch_fence_gate", - "minecraft:jungle_fence_gate", "minecraft:acacia_fence_gate", "minecraft:cherry_fence_gate", - "minecraft:dark_oak_fence_gate", "minecraft:mangrove_fence_gate", "minecraft:bamboo_fence_gate", - "minecraft:crimson_fence_gate", "minecraft:warped_fence_gate", - "minecraft:redstone_lamp", - "minecraft:tnt", - "minecraft:note_block", - "minecraft:dispenser", - "minecraft:dropper", - "minecraft:hopper", - "minecraft:powered_rail", - "minecraft:activator_rail", -} - -ALL_REDSTONE_NAMES = ( - REDSTONE_POWER_SOURCES | REDSTONE_WIRE_NAMES | REDSTONE_TORCH_NAMES | - REDSTONE_REPEATER_NAMES | REDSTONE_COMPARATOR_NAMES | REDSTONE_OBSERVER_NAMES | - PISTON_NAMES | REDSTONE_ACTIVATABLE -) - - -def is_redstone_block(block_name: str) -> bool: - """Check if a block name is any kind of redstone component.""" - return block_name in ALL_REDSTONE_NAMES - - -def _is_wood_button(name: str) -> bool: - return name.endswith("_button") and "stone" not in name - - -def _is_stone_button(name: str) -> bool: - return name in {"minecraft:stone_button", "minecraft:polished_blackstone_button"} - - -# -------------------------------------------------- -# Non-solid block set for wire connection logic -# -------------------------------------------------- - -_NON_SOLID_BLOCKS = { - "minecraft:air", "minecraft:redstone_wire", "minecraft:redstone_torch", - "minecraft:redstone_wall_torch", "minecraft:torch", "minecraft:wall_torch", - "minecraft:tripwire", "minecraft:tripwire_hook", - "minecraft:oak_sign", "minecraft:spruce_sign", "minecraft:birch_sign", - "minecraft:jungle_sign", "minecraft:acacia_sign", "minecraft:cherry_sign", - "minecraft:dark_oak_sign", "minecraft:mangrove_sign", "minecraft:bamboo_sign", - "minecraft:crimson_sign", "minecraft:warped_sign", - "minecraft:oak_hanging_sign", "minecraft:spruce_hanging_sign", - "minecraft:glass_pane", "minecraft:white_stained_glass_pane", - "minecraft:iron_bars", - "minecraft:tall_grass", "minecraft:fern", - "minecraft:dead_bush", "minecraft:vine", "minecraft:glow_lichen", - "minecraft:sugar_cane", "minecraft:wheat", - "minecraft:poppy", "minecraft:dandelion", - "minecraft:flower_pot", - "minecraft:ladder", - "minecraft:snow", -} - - -# -------------------------------------------------- -# Component data structures -# -------------------------------------------------- - -@dataclass -class RedstoneComponent: - """Tracks the state of a single redstone component in the world.""" - pos: tuple[int, int, int] - block_name: str - power: int = 0 # Current power output (0-15) - prev_power: int = 0 # Previous tick power (for edge detection) - facing: str = "north" # Facing direction - powered: bool = False # Is this component currently powered/active - prev_powered: bool = False - # Repeater-specific - delay: int = 1 # Repeater delay (1-4 redstone ticks) - locked: bool = False # Is this repeater locked - # Comparator-specific - mode: str = "compare" # Comparator mode: compare/subtract - # Observer-specific - observer_cooldown: int = 0 - # Button/pressure plate specific - active_timer: int = 0 # Ticks remaining for temporary activation - # Lever-specific - lever_on: bool = False - # Torch burnout - torch_burnout_timer: int = 0 - torch_toggle_count: int = 0 - torch_toggle_window_start: float = 0.0 - # Tripwire hook - attached: bool = False - # Daylight detector - inverted: bool = False - # Sticky piston flag - is_sticky: bool = False - # Target block - target_power: int = 0 - target_timer: int = 0 - # Piston - extended: bool = False - # Note block - note: int = 0 # 0-24 pitch - # TNT fuse (redstone ticks; 40 = 80 game ticks = 4 seconds) - fuse_ticks: int = 0 - # Dirty flag - needs recalculation - dirty: bool = True - # Wire connections (computed) - wire_connections: list[tuple[int, int, int]] = field(default_factory=list) - - -# -------------------------------------------------- -# Scheduled update entry -# -------------------------------------------------- - -@dataclass -class ScheduledUpdate: - """A scheduled redstone update to be processed at a future tick.""" - tick: int - pos: tuple[int, int, int] - target_powered: bool # What state to transition to - - -# -------------------------------------------------- -# Redstone Engine -# -------------------------------------------------- - -class RedstoneEngine: - """Tick-based redstone simulation engine integrated with the world.""" - - REDSTONE_TICK_RATE = 2 # 1 redstone tick = 2 game ticks - - def __init__(self, server): - self.server = server - # All tracked redstone components: pos -> RedstoneComponent - self.components: dict[tuple[int, int, int], RedstoneComponent] = {} - # Power levels at each block position (0-15) - self.power_levels: dict[tuple[int, int, int], int] = {} - # Strong power levels (from power sources strongly powering blocks) - self.strong_power: dict[tuple[int, int, int], int] = {} - # Scheduled updates - self.scheduled_updates: list[ScheduledUpdate] = [] - # Current redstone tick counter - self.current_tick: int = 0 - # Positions that need recalculation this tick - self.dirty_positions: set[tuple[int, int, int]] = set() - # Positions whose block state needs updating for clients - self.visual_updates: list[tuple[int, int, int, int]] = [] # (x, y, z, new_state_id) - # Async effects emitted by the sync tick (explosions, sounds, item drops) - self.pending_effects: list[tuple[str, dict]] = [] - # Native engine reference (optional C++ acceleration) - self._native_engine = None - # Performance tracking - self._tick_time_ms: float = 0.0 - self._component_count_at_last_log: int = 0 - - # Try to initialize native engine - self._init_native_engine() - - def _init_native_engine(self): - """Attempt to initialize the C++ native redstone engine.""" - try: - from native import NativeCore - core = NativeCore() - if core.is_available(): - self._native_engine = core.get_redstone_engine() - if self._native_engine: - logger.info("Redstone: C++ native engine initialized successfully") - else: - logger.info("Redstone: Native core available but redstone engine not ready, using Python fallback") - else: - logger.info("Redstone: Native core not available, using Python implementation") - except Exception as e: - logger.debug(f"Redstone: Native engine init failed ({e}), using Python fallback") - self._native_engine = None - - # -------------------------------------------------- - # Component registration - # -------------------------------------------------- - - def register_component(self, x: int, y: int, z: int, block_state_id: int): - """Register a redstone component when a block is placed.""" - pos = (x, y, z) - name = _get_block_name(block_state_id) - if not name or not is_redstone_block(name): - return - - props = _get_block_props(block_state_id) - comp = RedstoneComponent(pos=pos, block_name=name) - - # Extract facing from properties - comp.facing = props.get("facing", props.get("face", "north")) - if comp.facing not in ("north", "south", "east", "west", "up", "down"): - comp.facing = "north" - - # Component-specific initialization - if name in REDSTONE_WIRE_NAMES: - comp.power = int(props.get("power", "0")) - elif name in REDSTONE_TORCH_NAMES: - comp.powered = props.get("lit", "true") == "true" - comp.prev_powered = comp.powered - comp.power = 15 if comp.powered else 0 - elif name in REDSTONE_REPEATER_NAMES: - comp.delay = int(props.get("delay", "1")) - comp.powered = props.get("powered", "false") == "true" - comp.locked = props.get("locked", "false") == "true" - comp.power = 15 if comp.powered else 0 - elif name in REDSTONE_COMPARATOR_NAMES: - comp.mode = props.get("mode", "compare") - comp.powered = props.get("powered", "false") == "true" - comp.power = int(props.get("output_power", "0")) if comp.powered else 0 - elif name in REDSTONE_OBSERVER_NAMES: - comp.powered = props.get("powered", "false") == "true" - comp.power = 15 if comp.powered else 0 - elif name == "minecraft:lever": - comp.lever_on = props.get("powered", "false") == "true" - comp.power = 15 if comp.lever_on else 0 - elif name.endswith("_button"): - comp.powered = props.get("powered", "false") == "true" - if comp.powered: - if _is_wood_button(name): - comp.active_timer = WOOD_BUTTON_DURATION - else: - comp.active_timer = BUTTON_DURATIONS.get( - name.replace("minecraft:", "").replace("_button", ""), 10 - ) - elif name.endswith("_pressure_plate"): - if name in ("minecraft:light_weighted_pressure_plate", - "minecraft:heavy_weighted_pressure_plate"): - comp.power = int(props.get("power", "0")) - else: - comp.powered = props.get("powered", "false") == "true" - comp.power = 15 if comp.powered else 0 - elif name == "minecraft:redstone_block": - comp.power = 15 - elif name == "minecraft:daylight_detector": - comp.inverted = props.get("inverted", "false") == "true" - comp.power = int(props.get("power", "0")) - elif name == "minecraft:target": - comp.power = int(props.get("power", "0")) - elif name == "minecraft:tripwire_hook": - comp.powered = props.get("powered", "false") == "true" - comp.attached = props.get("attached", "false") == "true" - comp.power = 15 if comp.powered else 0 - elif name == "minecraft:detector_rail": - comp.powered = props.get("powered", "false") == "true" - comp.power = 15 if comp.powered else 0 - elif name in PISTON_NAMES: - comp.is_sticky = name == "minecraft:sticky_piston" - comp.extended = props.get("extended", "false") == "true" - elif name == "minecraft:redstone_lamp": - comp.powered = props.get("lit", "false") == "true" - elif name == "minecraft:note_block": - comp.note = int(props.get("note", "0")) - comp.powered = props.get("powered", "false") == "true" - elif name == "minecraft:tnt": - comp.powered = props.get("unstable", "false") == "true" - elif name in REDSTONE_ACTIVATABLE: - comp.powered = props.get("powered", "false") == "true" or props.get("open", "false") == "true" - - self.components[pos] = comp - self.dirty_positions.add(pos) - # Mark neighbors as dirty since a new component was added - self._mark_neighbors_dirty(x, y, z) - - # Register with native engine if available - if self._native_engine: - try: - component_type = self._name_to_native_type(name) - if component_type is not None: - facing_id = self._facing_to_native(comp.facing) - self._native_engine.add_component(x, y, z, component_type, facing_id) - except Exception as e: - logger.debug(f"Native engine add_component failed: {e}") - - def unregister_component(self, x: int, y: int, z: int): - """Unregister a redstone component when a block is broken.""" - pos = (x, y, z) - if pos in self.components: - del self.components[pos] - if pos in self.power_levels: - del self.power_levels[pos] - if pos in self.strong_power: - del self.strong_power[pos] - # Mark neighbors as dirty - self._mark_neighbors_dirty(x, y, z) - - # Unregister from native engine if available - if self._native_engine: - try: - self._native_engine.remove_component(x, y, z) - except Exception as e: - logger.debug(f"Native engine remove_component failed: {e}") - - def _mark_neighbors_dirty(self, x: int, y: int, z: int): - """Mark all neighboring positions as needing recalculation.""" - for dx, dy, dz in SIX_DIRS: - npos = (x + dx, y + dy, z + dz) - if npos in self.components: - self.components[npos].dirty = True - self.dirty_positions.add(npos) - # Also mark 2-block radius for wire connections - for dx2, dy2, dz2 in SIX_DIRS: - npos2 = (x + dx + dx2, y + dy + dy2, z + dz + dz2) - if npos2 in self.components: - self.components[npos2].dirty = True - self.dirty_positions.add(npos2) - - # -------------------------------------------------- - # Native engine helpers - # -------------------------------------------------- - - def _name_to_native_type(self, name: str) -> int | None: - """Convert a block name to a native component type ID.""" - from native import (COMPONENT_WIRE, COMPONENT_TORCH, COMPONENT_REPEATER, - COMPONENT_COMPARATOR, COMPONENT_PISTON, COMPONENT_STICKY_PISTON, - COMPONENT_OBSERVER, COMPONENT_LEVER, COMPONENT_BUTTON, - COMPONENT_PRESSURE_PLATE, COMPONENT_WEIGHTED_PRESSURE_PLATE) - mapping = { - "minecraft:redstone_wire": COMPONENT_WIRE, - "minecraft:redstone_torch": COMPONENT_TORCH, - "minecraft:redstone_wall_torch": COMPONENT_TORCH, - "minecraft:repeater": COMPONENT_REPEATER, - "minecraft:comparator": COMPONENT_COMPARATOR, - "minecraft:piston": COMPONENT_PISTON, - "minecraft:sticky_piston": COMPONENT_STICKY_PISTON, - "minecraft:observer": COMPONENT_OBSERVER, - "minecraft:lever": COMPONENT_LEVER, - } - if name in mapping: - return mapping[name] - if name.endswith("_button"): - return COMPONENT_BUTTON - if name.endswith("_pressure_plate"): - if name in ("minecraft:light_weighted_pressure_plate", - "minecraft:heavy_weighted_pressure_plate"): - return COMPONENT_WEIGHTED_PRESSURE_PLATE - return COMPONENT_PRESSURE_PLATE - return None - - def _facing_to_native(self, facing: str) -> int: - """Convert a facing string to a native facing ID.""" - from native import (FACING_DOWN, FACING_UP, FACING_NORTH, - FACING_SOUTH, FACING_WEST, FACING_EAST) - mapping = { - "down": FACING_DOWN, "up": FACING_UP, - "north": FACING_NORTH, "south": FACING_SOUTH, - "west": FACING_WEST, "east": FACING_EAST, - } - return mapping.get(facing, FACING_NORTH) - - # -------------------------------------------------- - # Block access helpers - # -------------------------------------------------- - - def _get_block_at(self, x: int, y: int, z: int) -> int: - """Get block state ID at a world position.""" - return self.server.get_block_at(x, y, z) or 0 - - def _get_block_name_at(self, x: int, y: int, z: int) -> str: - """Get block name at a world position.""" - return _get_block_name(self._get_block_at(x, y, z)) - - def _set_block_state(self, x: int, y: int, z: int, block_state_id: int): - """Set a block in the world and queue visual update.""" - from world.editing import set_world_block - set_world_block(self.server, x, y, z, block_state_id) - self.visual_updates.append((x, y, z, block_state_id)) - - def _is_solid_block(self, block_state_id: int) -> bool: - """Check if a block is solid (opaque cube).""" - if block_state_id == 0: # Air - return False - name = _get_block_name(block_state_id) - return name not in _NON_SOLID_BLOCKS - - # -------------------------------------------------- - # Power calculation - # -------------------------------------------------- - - def get_power_level(self, x: int, y: int, z: int) -> int: - """Get redstone power at a position (0-15).""" - return self.power_levels.get((x, y, z), 0) - - def get_strong_power(self, x: int, y: int, z: int) -> int: - """Get strong power at a position (0-15).""" - return self.strong_power.get((x, y, z), 0) - - def is_powered(self, x: int, y: int, z: int) -> bool: - """Check if a position has any redstone power. - - Checks both stored power levels and dynamically computed strong power - at any position (including non-component blocks). - """ - if self.get_power_level(x, y, z) > 0: - return True - if self.get_strong_power(x, y, z) > 0: - return True - # Also dynamically check strong power (for non-component blocks) - if self._get_strong_power_at(x, y, z) > 0: - return True - # Check if any adjacent power source directly powers this block - for dx, dy, dz in SIX_DIRS: - nx, ny, nz = x + dx, y + dy, z + dz - ncomp = self.components.get((nx, ny, nz)) - if ncomp and self._get_direct_power_from_neighbor(x, y, z, nx, ny, nz) > 0: - return True - # Check wire power at neighbor - wire_power = self.power_levels.get((nx, ny, nz), 0) - if wire_power > 0: - wire_comp = self.components.get((nx, ny, nz)) - if wire_comp and wire_comp.block_name in REDSTONE_WIRE_NAMES: - if wire_comp.power > 0: - return True - return False - - def _is_block_powered_excluding(self, x: int, y: int, z: int, - exclude_pos: tuple[int, int, int]) -> bool: - """Check if a block is powered, excluding a specific component's output. - - This is used by torches to avoid circular dependency - a torch - should not detect its own output as powering the attached block. - """ - # Check stored power levels - if self.power_levels.get((x, y, z), 0) > 0: - return True - if self.strong_power.get((x, y, z), 0) > 0: - return True - - # Check strong power at this position (excluding excluded component) - strong = self._get_strong_power_at(x, y, z) - if strong > 0: - return True - - # Check adjacent components for direct power (excluding excluded) - for dx, dy, dz in SIX_DIRS: - nx, ny, nz = x + dx, y + dy, z + dz - if (nx, ny, nz) == exclude_pos: - continue - ncomp = self.components.get((nx, ny, nz)) - if ncomp and self._get_direct_power_from_neighbor(x, y, z, nx, ny, nz) > 0: - return True - # Check wire power - if self.power_levels.get((nx, ny, nz), 0) > 0: - wire_comp = self.components.get((nx, ny, nz)) - if wire_comp and wire_comp.block_name in REDSTONE_WIRE_NAMES and wire_comp.power > 0: - return True - return False - - def _get_direct_power_from_neighbor(self, x: int, y: int, z: int, - from_x: int, from_y: int, from_z: int) -> int: - """Get the power that a neighbor block provides to this position. - - Power sources provide power directly: - - Lever/button/pressure plate: 15 when active - - Redstone torch: 15 when lit - - Repeater: 15 at its output face when powered - - Comparator: power level at its output face - - Redstone block: 15 to all adjacent blocks - - Redstone wire: its power level (degraded by 1) to connected blocks - """ - npos = (from_x, from_y, from_z) - comp = self.components.get(npos) - if comp is None: - return 0 - - name = comp.block_name - power = 0 - - if name == "minecraft:redstone_block": - power = 15 - elif name == "minecraft:lever": - if comp.lever_on: - power = 15 - elif name.endswith("_button"): - if comp.powered and comp.active_timer > 0: - power = 15 - elif name.endswith("_pressure_plate"): - if name in ("minecraft:light_weighted_pressure_plate", - "minecraft:heavy_weighted_pressure_plate"): - power = comp.power - else: - power = 15 if comp.powered else 0 - elif name in REDSTONE_TORCH_NAMES: - if comp.powered: - power = 15 - elif name in REDSTONE_REPEATER_NAMES: - # Repeater only outputs from its facing direction - if comp.powered: - fdx, fdy, fdz = FACING_DX.get(comp.facing, (0, 0, 1)) - output_pos = (from_x + fdx, from_y + fdy, from_z + fdz) - if output_pos == (x, y, z): - power = 15 - elif name in REDSTONE_COMPARATOR_NAMES: - # Comparator outputs from its facing direction - fdx, fdy, fdz = FACING_DX.get(comp.facing, (0, 0, 1)) - output_pos = (from_x + fdx, from_y + fdy, from_z + fdz) - if output_pos == (x, y, z): - power = comp.power - elif name in REDSTONE_OBSERVER_NAMES: - # Observer outputs from its facing direction - if comp.powered: - fdx, fdy, fdz = FACING_DX.get(comp.facing, (0, 0, 1)) - output_pos = (from_x + fdx, from_y + fdy, from_z + fdz) - if output_pos == (x, y, z): - power = 15 - elif name == "minecraft:daylight_detector": - power = comp.power - elif name == "minecraft:target": - power = comp.power - elif name == "minecraft:tripwire_hook": - if comp.powered: - power = 15 - elif name == "minecraft:detector_rail": - if comp.powered: - power = 15 - elif name in REDSTONE_WIRE_NAMES: - # Wire provides power - 1 to connected blocks - if comp.power > 0: - power = max(power, comp.power - 1) - - return power - - def _get_strong_power_at(self, x: int, y: int, z: int) -> int: - """Calculate strong power at a position. - - A block is strongly powered if a power source is directly attached - and pointing at it. Strongly powered blocks power adjacent redstone - wire to 15 (no degradation). - - Note: Redstone torches provide WEAK power only, not strong power. - Only levers, buttons, pressure plates, repeaters, and comparators - produce strong power. - """ - max_power = 0 - for dx, dy, dz in SIX_DIRS: - nx, ny, nz = x + dx, y + dy, z + dz - npos = (nx, ny, nz) - comp = self.components.get(npos) - if comp is None: - continue - - name = comp.block_name - # These components strongly power the block they're attached to - if name == "minecraft:redstone_block": - max_power = max(max_power, 15) - elif name == "minecraft:lever" and comp.lever_on: - max_power = max(max_power, 15) - elif name.endswith("_button") and comp.powered and comp.active_timer > 0: - max_power = max(max_power, 15) - elif name.endswith("_pressure_plate"): - if name in ("minecraft:light_weighted_pressure_plate", - "minecraft:heavy_weighted_pressure_plate"): - pp = comp.power - else: - pp = 15 if comp.powered else 0 - # Pressure plates strongly power the block below them - if dy == 1: # This block is below the pressure plate - max_power = max(max_power, pp) - elif name in REDSTONE_REPEATER_NAMES and comp.powered: - # Repeater strongly powers the block at its output face - fdx, fdy, fdz = FACING_DX.get(comp.facing, (0, 0, 1)) - output_pos = (nx + fdx, ny + fdy, nz + fdz) - if output_pos == (x, y, z): - max_power = max(max_power, 15) - elif name in REDSTONE_COMPARATOR_NAMES and comp.power > 0: - # Comparator strongly powers the block at its output face - fdx, fdy, fdz = FACING_DX.get(comp.facing, (0, 0, 1)) - output_pos = (nx + fdx, ny + fdy, nz + fdz) - if output_pos == (x, y, z): - max_power = max(max_power, comp.power) - - return max_power - - # -------------------------------------------------- - # Wire connection calculation - # -------------------------------------------------- - - def calculate_wire_connections(self, x: int, y: int, z: int) -> list[tuple[int, int, int]]: - """Calculate which blocks a redstone wire connects to. - - Wires connect: - - Horizontally to adjacent redstone-compatible blocks - - Up/down one block if the adjacent block is not solid - - To any redstone component that can provide/receive power - - Follows vanilla Minecraft wire connection rules: - 1. Wires connect to any redstone component on the same Y level - 2. Wires connect up over non-solid blocks to wires above - 3. Wires connect down through non-solid blocks below to wires below - 4. If a wire has no connections, it shows as a cross (dot) - """ - connections = [] - - for dx, dz in [(0, 1), (0, -1), (1, 0), (-1, 0)]: - nx, nz = x + dx, z + dz - - # Check same level - neighbor_name = self._get_block_name_at(nx, y, nz) - if self._can_wire_connect_to(neighbor_name): - connections.append((nx, y, nz)) - else: - # Check if the adjacent block is solid (wire can go up over it) - adj_block = self._get_block_at(nx, y, nz) - if self._is_solid_block(adj_block): - # Wire can connect up over the solid block - up_name = self._get_block_name_at(nx, y + 1, nz) - if up_name == "minecraft:redstone_wire": - connections.append((nx, y + 1, nz)) - - # Check one block down (wire going down when adjacent block is not solid) - if not self._is_solid_block(adj_block) and adj_block != 0: - # Non-solid, non-air block: check below - down_name = self._get_block_name_at(nx, y - 1, nz) - if down_name == "minecraft:redstone_wire": - connections.append((nx, y - 1, nz)) - - # Also check direct up connection when adjacent is air/non-solid - if not self._is_solid_block(adj_block): - up_name = self._get_block_name_at(nx, y + 1, nz) - if up_name == "minecraft:redstone_wire": - # Only connect up if the block above the wire-above is not solid - # (vanilla: wire can go up if no solid block blocks it) - above_above = self._get_block_at(nx, y + 2, nz) - if not self._is_solid_block(above_above): - connections.append((nx, y + 1, nz)) - - # Also connect to any redstone component directly adjacent (6 directions) - for dx, dy, dz in SIX_DIRS: - npos = (x + dx, y + dy, z + dz) - comp = self.components.get(npos) - if comp and comp.block_name not in REDSTONE_WIRE_NAMES: - if npos not in connections: - connections.append(npos) - - return connections - - def _can_wire_connect_to(self, block_name: str) -> bool: - """Check if redstone wire can connect to a block.""" - if not block_name: - return False - return block_name in ALL_REDSTONE_NAMES or block_name == "minecraft:redstone_wire" - - # -------------------------------------------------- - # Signal propagation (BFS) - # -------------------------------------------------- - - def _propagate_wire_signals(self): - """Propagate redstone signals through all wire networks using BFS. - - Uses a multi-source BFS from all power sources. Wire signal - degrades by 1 per block from the source. - - This implements the vanilla Minecraft algorithm: - 1. For each wire, find the maximum power it receives from non-wire sources - 2. Propagate through the wire network, degrading by 1 per block - 3. A wire can only receive power if a connected source provides it - """ - # Reset wire power levels - start fresh each tick - wire_powers: dict[tuple[int, int, int], int] = {} - - # Queue: (position, incoming_power) - queue: deque[tuple[tuple[int, int, int], int]] = deque() - - # Step 1: Seed the queue with all wires that receive power from non-wire sources - for pos, comp in self.components.items(): - if comp.block_name not in REDSTONE_WIRE_NAMES: - continue - - x, y, z = pos - max_input = 0 - - # Check power from non-wire adjacent sources - for dx, dy, dz in SIX_DIRS: - nx, ny, nz = x + dx, y + dy, z + dz - ncomp = self.components.get((nx, ny, nz)) - if ncomp is None: - # Check if the neighbor block is strongly powered - strong = self._get_strong_power_at(nx, ny, nz) - if strong > 0: - max_input = max(max_input, strong) - continue - - # Direct power from neighbor component (but not from wires) - if ncomp.block_name not in REDSTONE_WIRE_NAMES: - power = self._get_direct_power_from_neighbor(x, y, z, nx, ny, nz) - max_input = max(max_input, power) - - # Also check if this wire's block is strongly powered - strong = self._get_strong_power_at(x, y, z) - max_input = max(max_input, strong) - - if max_input > 0: - wire_powers[pos] = max_input - queue.append((pos, max_input)) - - # Step 2: BFS propagation through wire network - visited: set[tuple[int, int, int]] = set() - while queue: - pos, power = queue.popleft() - if pos in visited: - continue - visited.add(pos) - - comp = self.components.get(pos) - if comp is None or comp.block_name not in REDSTONE_WIRE_NAMES: - continue - - current = wire_powers.get(pos, 0) - if power > current: - wire_powers[pos] = power - current = power - - if current <= 1: - continue # Signal too weak to propagate further - - # Propagate to connected wires (using wire connections) - x, y, z = pos - connections = self.calculate_wire_connections(x, y, z) - for npos in connections: - ncomp = self.components.get(npos) - if ncomp is None or ncomp.block_name not in REDSTONE_WIRE_NAMES: - continue - new_power = current - 1 - existing = wire_powers.get(npos, 0) - if new_power > existing: - wire_powers[npos] = new_power - queue.append((npos, new_power)) - - # Step 3: Apply wire power levels - for pos, power in wire_powers.items(): - self.power_levels[pos] = power - - # Set unvisited wires to 0 - for pos, comp in self.components.items(): - if comp.block_name in REDSTONE_WIRE_NAMES and pos not in wire_powers: - self.power_levels[pos] = 0 - - # -------------------------------------------------- - # Component-specific update logic - # -------------------------------------------------- - - def _update_lever(self, comp: RedstoneComponent): - """Update lever power output.""" - comp.power = 15 if comp.lever_on else 0 - - def _update_button(self, comp: RedstoneComponent): - """Update button state - deactivate when timer expires.""" - if comp.active_timer > 0: - comp.active_timer -= 1 - if comp.active_timer <= 0: - comp.powered = False - comp.power = 0 - comp.dirty = True - - def _update_pressure_plate(self, comp: RedstoneComponent): - """Update pressure plate state based on entities standing on it. - - For now, we use a simplified model: check if any player is nearby. - Weighted plates output signal based on entity count. - """ - x, y, z = comp.pos - name = comp.block_name - - # Count entities on the pressure plate - entity_count = 0 - for player in self.server.get_online_players(): - px, py, pz = player.x, player.y, player.z - if (abs(px - (x + 0.5)) < 0.75 and - abs(pz - (z + 0.5)) < 0.75 and - abs(py - y) < 0.5): - entity_count += 1 - - # Also check mobs - if hasattr(self.server, 'entity_manager'): - try: - for entity in self.server.entity_manager.list_entities(): - if entity.kind != "mob": - continue - ex, ey, ez = entity.x, entity.y, entity.z - if (abs(ex - (x + 0.5)) < 0.75 and - abs(ez - (z + 0.5)) < 0.75 and - abs(ey - y) < 0.5): - entity_count += 1 - except Exception: - pass - - was_powered = comp.powered - - if name in ("minecraft:light_weighted_pressure_plate", - "minecraft:heavy_weighted_pressure_plate"): - if name == "minecraft:light_weighted_pressure_plate": - # Gold: 1 entity = signal 1, scales linearly - comp.power = min(15, entity_count) - comp.powered = entity_count > 0 - else: - # Iron: 1 signal per 10 entities - comp.power = min(15, entity_count // 10) - comp.powered = entity_count >= 10 - else: - # Standard pressure plates: on/off - comp.powered = entity_count > 0 - comp.power = 15 if comp.powered else 0 - - if was_powered != comp.powered: - comp.dirty = True - - def _update_redstone_torch(self, comp: RedstoneComponent): - """Update redstone torch state. - - A redstone torch is OFF when the block it's attached to is powered, - and ON when it's not. Has burnout protection. - - Important: When checking if the attached block is powered, we must - exclude this torch's own output to avoid circular dependency. - """ - x, y, z = comp.pos - name = comp.block_name - - # Determine the attached block position - if name == "minecraft:redstone_torch": - # Floor torch: attached to block below - attach_x, attach_y, attach_z = x, y - 1, z - elif name == "minecraft:redstone_wall_torch": - # Wall torch: attached to block opposite facing - fdx, fdy, fdz = FACING_DX.get(comp.facing, (0, 0, 1)) - attach_x, attach_y, attach_z = x - fdx, y, z - fdz - else: - return - - # Check if the attached block is powered by sources OTHER than this torch. - # We temporarily save and clear this torch's power to avoid circular dependency. - saved_powered = comp.powered - saved_power = comp.power - comp.powered = False - comp.power = 0 - - attached_powered = self._is_block_powered_excluding(attach_x, attach_y, attach_z, comp.pos) - - # Restore torch state - comp.powered = saved_powered - comp.power = saved_power - - was_powered = comp.powered - - if comp.torch_burnout_timer > 0: - comp.torch_burnout_timer -= 1 - comp.powered = False - comp.power = 0 - else: - # Torch inverts: OFF when attached block is powered - new_powered = not attached_powered - comp.powered = new_powered - comp.power = 15 if new_powered else 0 - - # Burnout detection: if toggling too rapidly - if was_powered != new_powered: - now = time.monotonic() - if now - comp.torch_toggle_window_start > 4.0: - # Reset the window - comp.torch_toggle_count = 1 - comp.torch_toggle_window_start = now - else: - comp.torch_toggle_count += 1 - if comp.torch_toggle_count >= TORCH_BURNOUT_THRESHOLD: - comp.torch_burnout_timer = TORCH_BURNOUT_DURATION - comp.torch_toggle_count = 0 - comp.powered = False - comp.power = 0 - logger.debug(f"Redstone torch burnout at {comp.pos}") - - if was_powered != comp.powered: - comp.dirty = True - - def _update_repeater(self, comp: RedstoneComponent): - """Update repeater state. - - A repeater: - - Receives input from its back face - - Outputs to its front face with a delay - - Can be locked by a powered repeater from the side - """ - x, y, z = comp.pos - - # Check if locked by side repeater - facing = comp.facing - # Get perpendicular directions - if facing in ("north", "south"): - side_dirs = [(1, 0, 0), (-1, 0, 0)] - else: - side_dirs = [(0, 0, 1), (0, 0, -1)] - - comp.locked = False - for sdx, sdy, sdz in side_dirs: - snpos = (x + sdx, y + sdy, z + sdz) - scomp = self.components.get(snpos) - if scomp and scomp.block_name in REDSTONE_REPEATER_NAMES: - # Check if the side repeater is pointing at us and powered - sfdx, sfdy, sfdz = FACING_DX.get(scomp.facing, (0, 0, 1)) - # The side repeater must be facing perpendicular AND pointing toward us - # i.e. the side repeater's output faces this repeater - s_output = (snpos[0] + sfdx, snpos[1] + sfdy, snpos[2] + sfdz) - if s_output == comp.pos and scomp.powered: - comp.locked = True - break - - if comp.locked: - # Locked repeater holds its current output state - return - - # Get input from back face - back_facing = FACING_OPPOSITE.get(facing, "south") - bdx, bdy, bdz = FACING_DX.get(back_facing, (0, 0, -1)) - input_x, input_y, input_z = x + bdx, y + bdy, z + bdz - - input_power = 0 - # Check direct power from input block - icomp = self.components.get((input_x, input_y, input_z)) - if icomp: - input_power = self._get_direct_power_from_neighbor( - x, y, z, input_x, input_y, input_z - ) - # Check strong power at input position - strong = self._get_strong_power_at(input_x, input_y, input_z) - input_power = max(input_power, strong) - # Check wire power - wire_power = self.power_levels.get((input_x, input_y, input_z), 0) - input_power = max(input_power, wire_power) - - # Check if block behind is powered (indirect power) - if input_power == 0: - if self.is_powered(input_x, input_y, input_z): - input_power = 15 - - should_power = input_power > 0 - was_powered = comp.powered - - if should_power != was_powered: - # Schedule the change after the delay - schedule_tick = self.current_tick + comp.delay - self.scheduled_updates.append(ScheduledUpdate( - tick=schedule_tick, - pos=comp.pos, - target_powered=should_power, - )) - - def _update_comparator(self, comp: RedstoneComponent): - """Update comparator state. - - Comparator modes: - - Compare: output = back_input if back_input >= max(side_inputs), else 0 - - Subtract: output = max(0, back_input - max(side_inputs)) - - Can also read container signal strength. - """ - x, y, z = comp.pos - facing = comp.facing - - # Get back input - back_facing = FACING_OPPOSITE.get(facing, "south") - bdx, bdy, bdz = FACING_DX.get(back_facing, (0, 0, -1)) - input_x, input_y, input_z = x + bdx, y + bdy, z + bdz - - back_input = 0 - icomp = self.components.get((input_x, input_y, input_z)) - if icomp: - back_input = self._get_direct_power_from_neighbor( - x, y, z, input_x, input_y, input_z - ) - strong = self._get_strong_power_at(input_x, input_y, input_z) - back_input = max(back_input, strong) - wire_power = self.power_levels.get((input_x, input_y, input_z), 0) - back_input = max(back_input, wire_power) - - # Check if block behind is powered (indirect power) - if back_input == 0 and self.is_powered(input_x, input_y, input_z): - back_input = 15 - - # Try to read container signal strength first (takes priority over redstone) - container_signal = self._read_container_signal(input_x, input_y, input_z) - if container_signal > 0 and back_input == 0: - back_input = container_signal - - # Get side inputs - if facing in ("north", "south"): - side_dirs = [(1, 0, 0), (-1, 0, 0)] - else: - side_dirs = [(0, 0, 1), (0, 0, -1)] - - side_inputs = [] - for sdx, sdy, sdz in side_dirs: - snx, sny, snz = x + sdx, y + sdy, z + sdz - sp = 0 - scomp = self.components.get((snx, sny, snz)) - if scomp: - sp = self._get_direct_power_from_neighbor(x, y, z, snx, sny, snz) - strong = self._get_strong_power_at(snx, sny, snz) - sp = max(sp, strong) - wire_power = self.power_levels.get((snx, sny, snz), 0) - sp = max(sp, wire_power) - side_inputs.append(sp) - - max_side = max(side_inputs) if side_inputs else 0 - - # Calculate output based on mode - if comp.mode == "compare": - new_power = back_input if back_input >= max_side else 0 - else: # subtract - new_power = max(0, back_input - max_side) - - was_powered = comp.powered - old_power = comp.power - - comp.power = new_power - comp.powered = new_power > 0 - - if was_powered != comp.powered or old_power != comp.power: - comp.dirty = True - - def _read_container_signal(self, x: int, y: int, z: int) -> int: - """Read signal strength from a container (chest, hopper, etc.). - - Signal = floor(16 * full_slots / total_slots) for most containers. - Returns 0 if no container is present or if it's empty. - """ - block_name = self._get_block_name_at(x, y, z) - if block_name not in CONTAINER_NAMES: - return 0 - - # Prefer the real block-container inventory when it exists. - from .block_behavior import container_manager - - container = container_manager.get_container(x, y, z) - if container is not None: - total = 0 - for stack in container.items: - if stack is None or stack.is_empty: - continue - max_size = max(1, stack.max_stack_size) - # Vanilla comparator formula: - # floor(1 + (count / max_stack_size) * 14). - total += 1 + (stack.count * 14) // max_size - return min(15, total) - - # Compatibility fallback for older callers that populated - # ``server._block_inventories`` directly. - inventory_data = getattr(self.server, '_block_inventories', {}).get((x, y, z)) - if inventory_data is None: - return 0 - - try: - # inventory_data should be a dict with 'used' and 'total' slots - used = inventory_data.get('used', 0) - total = inventory_data.get('total', 27) - if total == 0: - return 0 - # Calculate signal strength - # Signal 0 if empty, 1-15 based on fill level, 15 if full - if used == 0: - return 0 - # Each slot is 1/total of the signal range - signal = min(15, max(1, (used * 16) // total)) - return signal - except Exception: - return 0 - - def _update_observer(self, comp: RedstoneComponent): - """Update observer state. - - An observer detects block state changes in front of it and - emits a 2-tick pulse when a change is detected. - The observer monitors the block it's facing, not the block behind it. - """ - if comp.observer_cooldown > 0: - comp.observer_cooldown -= 1 - if comp.observer_cooldown <= 0: - comp.powered = False - comp.power = 0 - comp.dirty = True - - def _update_daylight_detector(self, comp: RedstoneComponent): - """Update daylight detector based on sky light level. - - The signal strength depends on the sun angle: - - Maximum at noon (time 6000) - - Zero at night (13000-23000) - - Inverted mode reverses the output - """ - time_of_day = self.server.world_time % 24000 - - if comp.inverted: - # Inverted: maximum at night, minimum at day - if 13000 <= time_of_day <= 23000: - # Night time - peak at 18000 - angle = 1.0 - abs(time_of_day - 18000) / 5000.0 - angle = max(0, min(1, angle)) - comp.power = int(angle * 15) - else: - # Day time - very low - if time_of_day < 13000: - comp.power = max(0, int((1.0 - time_of_day / 13000.0) * 3)) - else: - comp.power = max(0, int(((time_of_day - 23000) / 1000.0) * 3)) - else: - # Normal: maximum at noon, minimum at night - if 0 <= time_of_day <= 12000: - # Day - peak at 6000 - angle = 1.0 - abs(time_of_day - 6000) / 6000.0 - angle = max(0, min(1, angle)) - comp.power = int(angle * 15) - elif 12000 < time_of_day < 13000: - comp.power = 0 - elif 23000 <= time_of_day: - angle = (time_of_day - 23000) / 1000.0 - comp.power = int(angle * 10) - else: - comp.power = 0 - - comp.powered = comp.power > 0 - comp.dirty = True - - def _update_target(self, comp: RedstoneComponent): - """Update target block - activated by projectile hits.""" - if comp.target_timer > 0: - comp.target_timer -= 1 - if comp.target_timer <= 0: - comp.power = 0 - comp.powered = False - comp.dirty = True - - def _update_tripwire_hook(self, comp: RedstoneComponent): - """Update tripwire hook - detects entity crossing tripwire.""" - x, y, z = comp.pos - fdx, fdy, fdz = FACING_DX.get(comp.facing, (0, 0, 1)) - entity_detected = False - - for dist in range(1, 41): # Max 40 blocks - tx, ty, tz = x + fdx * dist, y, z + fdz * dist - tname = self._get_block_name_at(tx, ty, tz) - if tname == "minecraft:tripwire": - # Check for entities on this tripwire - for player in self.server.get_online_players(): - if (abs(player.x - (tx + 0.5)) < 0.75 and - abs(player.z - (tz + 0.5)) < 0.75 and - abs(player.y - ty) < 0.5): - entity_detected = True - break - if entity_detected: - break - comp.attached = True - else: - break - - was_powered = comp.powered - comp.powered = entity_detected - comp.power = 15 if entity_detected else 0 - if was_powered != comp.powered: - comp.dirty = True - - def _update_detector_rail(self, comp: RedstoneComponent): - """Update detector rail - detects an entity riding on the rail. - - PyMC does not have a dedicated minecart entity yet, so this checks - every tracked entity/player overlapping the rail block. That covers - minecarts once they are represented as ordinary entities. - """ - x, y, z = comp.pos - detected = False - - for player in self.server.get_online_players(): - if (abs(player.x - (x + 0.5)) < 0.75 - and abs(player.z - (z + 0.5)) < 0.75 - and abs(player.y - y) < 0.6): - detected = True - break - - if not detected and hasattr(self.server, 'entity_manager'): - try: - for entity in self.server.entity_manager.list_entities(): - if (abs(entity.x - (x + 0.5)) < 0.75 - and abs(entity.z - (z + 0.5)) < 0.75 - and abs(entity.y - y) < 0.6): - detected = True - break - except Exception: - pass - - was_powered = comp.powered - comp.powered = detected - comp.power = 15 if detected else 0 - if was_powered != comp.powered: - comp.dirty = True - - # -------------------------------------------------- - # Mechanical block activation - # -------------------------------------------------- - - def _activate_mechanical_blocks(self): - """Activate/deactivate blocks that respond to redstone signals.""" - for pos, comp in list(self.components.items()): - name = comp.block_name - if name not in REDSTONE_ACTIVATABLE: - continue - - x, y, z = pos - powered = self.is_powered(x, y, z) or self._get_strong_power_at(x, y, z) > 0 - - if name == "minecraft:redstone_lamp": - if powered != comp.powered: - comp.powered = powered - comp.dirty = True - - elif name == "minecraft:tnt": - if powered: - if not comp.powered: - comp.powered = True - comp.fuse_ticks = 40 - comp.dirty = True - logger.info(f"TNT ignited by redstone at {pos}") - elif comp.fuse_ticks > 0: - comp.fuse_ticks -= 1 - if comp.fuse_ticks <= 0: - self._detonate_tnt(pos, comp) - elif comp.powered: - comp.powered = False - comp.fuse_ticks = 0 - comp.dirty = True - - elif name == "minecraft:note_block": - # Note blocks play on rising edge. - if powered and not comp.powered: - comp.powered = True - comp.dirty = True - self._queue_effect("note", {"x": x, "y": y, "z": z, "note": comp.note}) - elif not powered and comp.powered: - comp.powered = False - comp.dirty = True - - elif name == "minecraft:hopper": - if powered != comp.powered: - comp.powered = powered - comp.dirty = True - - elif name.endswith("_door") or name.endswith("_trapdoor") or name.endswith("_fence_gate"): - # Toggle on rising edge - if powered and not comp.powered: - comp.powered = True - comp.dirty = True - self._toggle_openable(pos, comp, True) - elif not powered and comp.powered: - comp.powered = False - comp.dirty = True - self._toggle_openable(pos, comp, False) - - elif name in ("minecraft:dispenser", "minecraft:dropper"): - if powered and not comp.powered: - comp.powered = True - comp.dirty = True - self._activate_dispenser_or_dropper(pos, comp) - elif not powered and comp.powered: - comp.powered = False - comp.dirty = True - - elif name == "minecraft:powered_rail": - if powered != comp.powered: - comp.powered = powered - comp.dirty = True - - elif name == "minecraft:activator_rail": - if powered != comp.powered: - comp.powered = powered - comp.dirty = True - - def _detonate_tnt(self, pos: tuple[int, int, int], comp: RedstoneComponent): - """Remove lit TNT and queue the explosion for the async server tick.""" - x, y, z = pos - tnt_state = self._get_block_at(x, y, z) - - # Remove the block from the world synchronously so further redstone - # ticks do not double-trigger it. The actual explosion is async. - self._set_block_state(x, y, z, AIR) - self.on_block_change(x, y, z, tnt_state, AIR) - self.visual_updates.append((x, y, z, AIR)) - # powered TNT becomes primed TNT with the normal 80-tick fuse - entity_manager = getattr(self.server, "entity_manager", None) - if entity_manager is not None: - entity_manager.create_tnt(x + 0.5, y, z + 0.5) - else: - self._queue_effect("explosion", {"x": x, "y": y, "z": z}) - - def _activate_dispenser_or_dropper(self, pos: tuple[int, int, int], - comp: RedstoneComponent): - """Drop/dispense the first non-empty item on a rising redstone edge.""" - from .block_behavior import container_manager - - x, y, z = pos - container = container_manager.get_container(x, y, z) - if container is None: - logger.debug(f"No container data for {comp.block_name} at {pos}") - return - - # Find the first occupied slot. - for slot_idx, stack in enumerate(container.items): - if stack is None or stack.is_empty: - continue - - item_name = stack.item_id - stack.count -= 1 - if stack.count <= 0: - container.items[slot_idx] = None - - fdx, fdy, fdz = FACING_DX.get(comp.facing, (0, 0, 1)) - out_x = x + fdx * 1.0 - out_y = y + fdy * 0.5 - out_z = z + fdz * 1.0 - - entity_manager = getattr(self.server, 'entity_manager', None) - if entity_manager is not None: - try: - entity = entity_manager.create_item( - out_x + 0.5, out_y + 0.3, out_z + 0.5, - item_name=item_name, count=1 - ) - entity.vx = fdx * 0.16 - entity.vy = 0.06 - entity.vz = fdz * 0.16 - self._queue_effect("entity_spawn", {"entity_id": entity.entity_id}) - except Exception as e: - logger.warning(f"Failed to drop item from {comp.block_name}: {e}") - return - - def _queue_effect(self, kind: str, payload: dict): - """Queue an effect that must be broadcast/awaited outside the sync tick.""" - self.pending_effects.append((kind, payload)) - - def drain_pending_effects(self) -> list[tuple[str, dict]]: - """Return and clear queued async effects (sounds, explosions, drops).""" - effects = self.pending_effects - self.pending_effects = [] - return effects - - def _toggle_openable(self, pos: tuple[int, int, int], comp: RedstoneComponent, - should_open: bool): - """Toggle a door/trapdoor/fence gate open/closed state.""" - x, y, z = pos - block_id = self._get_block_at(x, y, z) - props = _get_block_props(block_id) - current_open = props.get("open", "false") == "true" - - if should_open != current_open: - new_props = dict(props) - new_props["open"] = "true" if should_open else "false" - new_state = resolve_state_id(comp.block_name, **new_props) - if new_state != block_id: - self._set_block_state(x, y, z, new_state) - - # -------------------------------------------------- - # Piston logic - # -------------------------------------------------- - - def _update_pistons(self): - """Process piston extend/retract operations.""" - for pos, comp in list(self.components.items()): - if comp.block_name not in PISTON_NAMES: - continue - - x, y, z = pos - powered = self.is_powered(x, y, z) or self._get_strong_power_at(x, y, z) > 0 - - if powered and not comp.extended: - # Extend piston - self._piston_extend(comp) - elif not powered and comp.extended: - # Retract piston - self._piston_retract(comp) - - def _piston_extend(self, comp: RedstoneComponent): - """Extend a piston, pushing blocks in its path.""" - x, y, z = comp.pos - fdx, fdy, fdz = FACING_DX.get(comp.facing, (0, 0, 1)) - - # Find blocks to push (up to 12) - blocks_to_push: list[tuple[int, int, int, int]] = [] - for i in range(1, PISTON_PUSH_LIMIT + 2): - bx, by, bz = x + fdx * i, y + fdy * i, z + fdz * i - block_id = self._get_block_at(bx, by, bz) - if block_id == 0: # Air - break - name = _get_block_name(block_id) - # Cannot push certain blocks - unpushable = { - "minecraft:obsidian", "minecraft:bedrock", "minecraft:command_block", - "minecraft:end_portal_frame", "minecraft:barrier", "minecraft:spawner", - "minecraft:reinforced_deepslate", "minecraft:piston_head", - "minecraft:moving_piston", - } - if name in unpushable: - return - if len(blocks_to_push) >= PISTON_PUSH_LIMIT: - return # Too many blocks - blocks_to_push.append((bx, by, bz, block_id)) - - # Check that the destination for the last block is clear - if blocks_to_push: - last_bx, last_by, last_bz, _ = blocks_to_push[-1] - dest_x = last_bx + fdx - dest_y = last_by + fdy - dest_z = last_bz + fdz - dest_id = self._get_block_at(dest_x, dest_y, dest_z) - if dest_id != 0: - return # Can't push into non-air - else: - # No blocks to push, just extend the piston head - head_x, head_y, head_z = x + fdx, y + fdy, z + fdz - head_id = self._get_block_at(head_x, head_y, head_z) - if head_id != 0: - return # Can't extend into non-air - - # Execute push: move blocks from far to near (preserve order) - for bx, by, bz, bid in reversed(blocks_to_push): - new_x, new_y, new_z = bx + fdx, by + fdy, bz + fdz - self._set_block_state(new_x, new_y, new_z, bid) - self._set_block_state(bx, by, bz, AIR) - # Notify engine of block changes - self.on_block_change(bx, by, bz, bid, AIR) - self.on_block_change(new_x, new_y, new_z, AIR, bid) - - # Place piston head - head_x, head_y, head_z = x + fdx, y + fdy, z + fdz - piston_head_name = "minecraft:piston_head" - head_props = {"facing": comp.facing, "type": "sticky" if comp.is_sticky else "normal"} - head_state = resolve_state_id(piston_head_name, **head_props) - self._set_block_state(head_x, head_y, head_z, head_state) - - # Update piston block to extended state - comp.extended = True - piston_props = {"facing": comp.facing, "extended": "true"} - piston_state = resolve_state_id(comp.block_name, **piston_props) - self._set_block_state(x, y, z, piston_state) - - def _piston_retract(self, comp: RedstoneComponent): - """Retract a piston, pulling the attached block if sticky.""" - x, y, z = comp.pos - fdx, fdy, fdz = FACING_DX.get(comp.facing, (0, 0, 1)) - - # Remove piston head - head_x, head_y, head_z = x + fdx, y + fdy, z + fdz - head_id = self._get_block_at(head_x, head_y, head_z) - head_name = _get_block_name(head_id) - if head_name == "minecraft:piston_head": - self._set_block_state(head_x, head_y, head_z, AIR) - self.on_block_change(head_x, head_y, head_z, head_id, AIR) - - # Sticky piston pulls one block - if comp.is_sticky: - pull_x, pull_y, pull_z = x + fdx * 2, y + fdy * 2, z + fdz * 2 - pull_id = self._get_block_at(pull_x, pull_y, pull_z) - pull_name = _get_block_name(pull_id) - if pull_id and pull_id != 0 and pull_name not in { - "minecraft:obsidian", "minecraft:bedrock", - "minecraft:piston_head", "minecraft:moving_piston", - }: - # Move the block - self._set_block_state(head_x, head_y, head_z, pull_id) - self._set_block_state(pull_x, pull_y, pull_z, AIR) - self.on_block_change(pull_x, pull_y, pull_z, pull_id, AIR) - self.on_block_change(head_x, head_y, head_z, AIR, pull_id) - - # Update piston block to retracted state - comp.extended = False - piston_props = {"facing": comp.facing, "extended": "false"} - piston_state = resolve_state_id(comp.block_name, **piston_props) - self._set_block_state(x, y, z, piston_state) - - # -------------------------------------------------- - # Main tick loop - # -------------------------------------------------- - - def tick(self): - """Process one redstone tick (2 game ticks = 0.1s). - - Steps: - 1. Process scheduled updates - 2. Update power sources (levers, buttons, plates, etc.) - 3. Propagate wire signals (BFS) - do this before signal processors - so that components can read current wire power levels - 4. Update signal processors (torches, repeaters, comparators) - 5. Re-propagate wire signals if processors changed - 6. Calculate block power levels - 7. Activate mechanical blocks - 8. Update pistons - 9. Apply visual updates - """ - tick_start = time.monotonic() - self.current_tick += 1 - self.visual_updates.clear() - - # If native engine is available and has enough components, delegate - if self._native_engine and len(self.components) > 100: - try: - self._tick_native() - self._tick_time_ms = (time.monotonic() - tick_start) * 1000 - return - except Exception as e: - logger.debug(f"Native tick failed, falling back: {e}") - - # 1. Process scheduled updates - self._process_scheduled_updates() - - # 2. Update all power sources - for pos, comp in list(self.components.items()): - name = comp.block_name - - if name == "minecraft:lever": - self._update_lever(comp) - elif name.endswith("_button"): - self._update_button(comp) - elif name.endswith("_pressure_plate"): - self._update_pressure_plate(comp) - elif name == "minecraft:daylight_detector": - self._update_daylight_detector(comp) - elif name == "minecraft:target": - self._update_target(comp) - elif name == "minecraft:tripwire_hook": - self._update_tripwire_hook(comp) - elif name == "minecraft:detector_rail": - self._update_detector_rail(comp) - - # 3. First wire propagation pass - so signal processors can read wire levels - self._propagate_wire_signals() - - # 4. Update signal processors (torches first, then repeaters, then comparators) - for pos, comp in list(self.components.items()): - if comp.block_name in REDSTONE_TORCH_NAMES: - self._update_redstone_torch(comp) - - for pos, comp in list(self.components.items()): - if comp.block_name in REDSTONE_REPEATER_NAMES: - self._update_repeater(comp) - - for pos, comp in list(self.components.items()): - if comp.block_name in REDSTONE_COMPARATOR_NAMES: - self._update_comparator(comp) - - for pos, comp in list(self.components.items()): - if comp.block_name in REDSTONE_OBSERVER_NAMES: - self._update_observer(comp) - - # 5. Second wire propagation pass - capture changes from signal processors - self._propagate_wire_signals() - - # 6. Calculate power levels for all component positions - self._calculate_power_levels() - - # 7. Activate mechanical blocks - self._activate_mechanical_blocks() - - # 8. Update pistons - self._update_pistons() - - # 9. Apply visual updates for dirty components - self._apply_visual_updates() - - # Performance tracking - self._tick_time_ms = (time.monotonic() - tick_start) * 1000 - - # Periodic logging - if self.current_tick % 200 == 0: # Every 20 seconds - comp_count = len(self.components) - if comp_count != self._component_count_at_last_log: - logger.info( - f"Redstone: {comp_count} components, " - f"tick={self._tick_time_ms:.1f}ms" - ) - self._component_count_at_last_log = comp_count - - def _tick_native(self): - """Delegate tick processing to the native C++ engine.""" - if not self._native_engine: - return - - # Process scheduled updates in Python first - self._process_scheduled_updates() - - # Sync component states to native engine - for pos, comp in self.components.items(): - try: - self._native_engine.set_power_level( - pos[0], pos[1], pos[2], comp.power - ) - except Exception: - pass - - # Run native tick - updates = self._native_engine.tick() - - # Apply updates from native engine - self.visual_updates.clear() - for update in updates: - x, y, z, new_state, flags = update.x, update.y, update.z, update.new_block_state, update.flags - # Update component power levels - pos = (x, y, z) - comp = self.components.get(pos) - if comp: - comp.power = new_state & 0xF - comp.powered = comp.power > 0 - comp.dirty = False - # Queue visual update - self._set_block_state(x, y, z, new_state) - - def _process_scheduled_updates(self): - """Process scheduled updates that have reached their execution tick.""" - remaining: list[ScheduledUpdate] = [] - for update in self.scheduled_updates: - if update.tick <= self.current_tick: - comp = self.components.get(update.pos) - if comp is None: - continue - - if comp.block_name in REDSTONE_REPEATER_NAMES: - # Apply the scheduled state change - comp.powered = update.target_powered - comp.power = 15 if comp.powered else 0 - comp.dirty = True - elif comp.block_name in REDSTONE_TORCH_NAMES: - comp.powered = update.target_powered - comp.power = 15 if comp.powered else 0 - comp.dirty = True - else: - remaining.append(update) - - self.scheduled_updates = remaining - - def _calculate_power_levels(self): - """Calculate power levels at all tracked positions.""" - for pos, comp in self.components.items(): - x, y, z = pos - if comp.block_name in REDSTONE_WIRE_NAMES: - # Wire power is already set by propagation - continue - - # For other components, calculate the power they receive - max_power = 0 - for dx, dy, dz in SIX_DIRS: - nx, ny, nz = x + dx, y + dy, z + dz - # Get power from wire - wire_power = self.power_levels.get((nx, ny, nz), 0) - max_power = max(max_power, wire_power) - - # Get power from components - ncomp = self.components.get((nx, ny, nz)) - if ncomp: - dp = self._get_direct_power_from_neighbor(x, y, z, nx, ny, nz) - max_power = max(max_power, dp) - - # Check strong power at this position - strong = self._get_strong_power_at(x, y, z) - max_power = max(max_power, strong) - - self.power_levels[pos] = max_power - self.strong_power[pos] = strong - - def _apply_visual_updates(self): - """Apply visual block state changes for dirty components.""" - for pos, comp in list(self.components.items()): - if not comp.dirty: - continue - - comp.dirty = False - x, y, z = pos - - # Compute the correct block state ID for this component - new_state = self._compute_visual_state(comp) - current_state = self._get_block_at(x, y, z) - - if new_state != current_state: - self._set_block_state(x, y, z, new_state) - - def _compute_visual_state(self, comp: RedstoneComponent) -> int: - """Compute the correct block state ID for a component's current state.""" - name = comp.block_name - - try: - if name in REDSTONE_WIRE_NAMES: - # Redstone wire: power 0-15 + connection directions - connections = self.calculate_wire_connections(*comp.pos) - conn_dirs: dict[str, str] = {"north": "none", "south": "none", "east": "none", "west": "none"} - cx, cy, cz = comp.pos - for nx, ny, nz in connections: - dx, dz = nx - cx, nz - cz - if dx == 1: - conn_dirs["east"] = "side" - elif dx == -1: - conn_dirs["west"] = "side" - if dz == 1: - conn_dirs["south"] = "side" - elif dz == -1: - conn_dirs["north"] = "side" - - # Check up connections - for nx, ny, nz in connections: - if ny > cy: - dx, dz = nx - cx, nz - cz - if dx == 1: - conn_dirs["east"] = "up" - elif dx == -1: - conn_dirs["west"] = "up" - if dz == 1: - conn_dirs["south"] = "up" - elif dz == -1: - conn_dirs["north"] = "up" - - # If no connections, show as cross (dot shape) - if all(v == "none" for v in conn_dirs.values()): - conn_dirs = {"north": "side", "south": "side", "east": "side", "west": "side"} - - return resolve_state_id(name, - power=str(comp.power), - north=conn_dirs["north"], - south=conn_dirs["south"], - east=conn_dirs["east"], - west=conn_dirs["west"]) - - elif name in REDSTONE_TORCH_NAMES: - if name == "minecraft:redstone_torch": - return resolve_state_id(name, lit="true" if comp.powered else "false") - else: - return resolve_state_id(name, - facing=comp.facing, - lit="true" if comp.powered else "false") - - elif name in REDSTONE_REPEATER_NAMES: - return resolve_state_id(name, - facing=comp.facing, - delay=str(comp.delay), - powered="true" if comp.powered else "false", - locked="true" if comp.locked else "false") - - elif name in REDSTONE_COMPARATOR_NAMES: - return resolve_state_id(name, - facing=comp.facing, - mode=comp.mode, - powered="true" if comp.powered else "false") - - elif name in REDSTONE_OBSERVER_NAMES: - return resolve_state_id(name, - facing=comp.facing, - powered="true" if comp.powered else "false") - - elif name == "minecraft:lever": - # Lever has face, facing, and powered properties - block_id = self._get_block_at(*comp.pos) - props = _get_block_props(block_id) - return resolve_state_id(name, - face=props.get("face", "wall"), - facing=props.get("facing", "north"), - powered="true" if comp.lever_on else "false") - - elif name.endswith("_button"): - block_id = self._get_block_at(*comp.pos) - props = _get_block_props(block_id) - return resolve_state_id(name, - face=props.get("face", "wall"), - facing=props.get("facing", "north"), - powered="true" if comp.powered else "false") - - elif name == "minecraft:redstone_block": - return resolve_state_id(name) - - elif name == "minecraft:redstone_lamp": - return resolve_state_id(name, lit="true" if comp.powered else "false") - - elif name == "minecraft:daylight_detector": - return resolve_state_id(name, - power=str(comp.power), - inverted="true" if comp.inverted else "false") - - elif name == "minecraft:target": - return resolve_state_id(name, power=str(comp.power)) - - elif name.endswith("_pressure_plate"): - if name in ("minecraft:light_weighted_pressure_plate", - "minecraft:heavy_weighted_pressure_plate"): - return resolve_state_id(name, power=str(comp.power)) - else: - return resolve_state_id(name, - powered="true" if comp.powered else "false") - - elif name == "minecraft:tripwire_hook": - return resolve_state_id(name, - facing=comp.facing, - attached="true" if comp.attached else "false", - powered="true" if comp.powered else "false") - - elif name in PISTON_NAMES: - return resolve_state_id(name, - facing=comp.facing, - extended="true" if comp.extended else "false") - - elif name in ("minecraft:dispenser", "minecraft:dropper"): - block_id = self._get_block_at(*comp.pos) - props = _get_block_props(block_id) - return resolve_state_id(name, - facing=props.get("facing", "north"), - triggered="true" if comp.powered else "false") - - elif name == "minecraft:hopper": - block_id = self._get_block_at(*comp.pos) - props = _get_block_props(block_id) - return resolve_state_id(name, - facing=props.get("facing", "down"), - enabled="false" if comp.powered else "true") - - elif name == "minecraft:powered_rail": - block_id = self._get_block_at(*comp.pos) - props = _get_block_props(block_id) - return resolve_state_id(name, - shape=props.get("shape", "north_south"), - powered="true" if comp.powered else "false", - waterlogged=props.get("waterlogged", "false")) - - elif name == "minecraft:activator_rail": - block_id = self._get_block_at(*comp.pos) - props = _get_block_props(block_id) - return resolve_state_id(name, - shape=props.get("shape", "north_south"), - powered="true" if comp.powered else "false", - waterlogged=props.get("waterlogged", "false")) - - elif name == "minecraft:detector_rail": - block_id = self._get_block_at(*comp.pos) - props = _get_block_props(block_id) - return resolve_state_id(name, - shape=props.get("shape", "north_south"), - powered="true" if comp.powered else "false", - waterlogged=props.get("waterlogged", "false")) - - elif name == "minecraft:note_block": - block_id = self._get_block_at(*comp.pos) - props = _get_block_props(block_id) - return resolve_state_id(name, - instrument=props.get("instrument", "harp"), - note=str(max(0, min(24, int(comp.note)))), - powered="true" if comp.powered else "false") - - elif name == "minecraft:tnt": - return resolve_state_id(name, - unstable="true" if comp.powered else "false") - - elif name.endswith("_door"): - block_id = self._get_block_at(*comp.pos) - props = _get_block_props(block_id) - return resolve_state_id(name, - facing=props.get("facing", "north"), - half=props.get("half", "lower"), - hinge=props.get("hinge", "left"), - open="true" if comp.powered else props.get("open", "false"), - powered="true" if comp.powered else "false") - - elif name.endswith("_trapdoor"): - block_id = self._get_block_at(*comp.pos) - props = _get_block_props(block_id) - return resolve_state_id(name, - facing=props.get("facing", "north"), - half=props.get("half", "bottom"), - open="true" if comp.powered else props.get("open", "false"), - powered="true" if comp.powered else "false", - waterlogged=props.get("waterlogged", "false")) - - elif name.endswith("_fence_gate"): - block_id = self._get_block_at(*comp.pos) - props = _get_block_props(block_id) - return resolve_state_id(name, - facing=props.get("facing", "north"), - in_wall=props.get("in_wall", "false"), - open="true" if comp.powered else props.get("open", "false"), - powered="true" if comp.powered else "false") - - except Exception as e: - logger.debug(f"Error computing visual state for {name} at {comp.pos}: {e}") - - # Fallback: return the default state for this block - return BLOCK_NAME_TO_DEFAULT_STATE.get(name, 0) - - # -------------------------------------------------- - # Event handlers - # -------------------------------------------------- - - def on_block_change(self, x: int, y: int, z: int, old_block: int, new_block: int): - """Called when a block is placed/broken/moved. - - Re-registers components and marks neighbors dirty. - """ - old_name = _get_block_name(old_block) - new_name = _get_block_name(new_block) - - # Unregister old component if it was redstone - if old_name and is_redstone_block(old_name): - self.unregister_component(x, y, z) - - # Register new component if it is redstone - if new_name and is_redstone_block(new_name): - self.register_component(x, y, z, new_block) - - # Mark neighbors dirty - self._mark_neighbors_dirty(x, y, z) - - # Check if an observer should detect this change - for dx, dy, dz in SIX_DIRS: - npos = (x + dx, y + dy, z + dz) - ncomp = self.components.get(npos) - if ncomp and ncomp.block_name in REDSTONE_OBSERVER_NAMES: - # Check if the observer is facing this block - fdx, fdy, fdz = FACING_DX.get(ncomp.facing, (0, 0, 1)) - observed_pos = (npos[0] + fdx, npos[1] + fdy, npos[2] + fdz) - if observed_pos == (x, y, z): - # Observer detects this change - if ncomp.observer_cooldown <= 0: - ncomp.powered = True - ncomp.power = 15 - ncomp.observer_cooldown = 2 # 2 redstone ticks pulse - ncomp.dirty = True - - def on_player_interact(self, x: int, y: int, z: int, player) -> bool: - """Handle player interaction with a redstone component. - - Returns True if the interaction was handled. - """ - pos = (x, y, z) - comp = self.components.get(pos) - if comp is None: - return False - - name = comp.block_name - - if name == "minecraft:lever": - comp.lever_on = not comp.lever_on - comp.power = 15 if comp.lever_on else 0 - comp.dirty = True - self._mark_neighbors_dirty(x, y, z) - return True - - elif name in REDSTONE_REPEATER_NAMES: - # Right-click cycles delay 1->2->3->4->1 - comp.delay = (comp.delay % 4) + 1 - comp.dirty = True - return True - - elif name in REDSTONE_COMPARATOR_NAMES: - # Right-click toggles mode - comp.mode = "subtract" if comp.mode == "compare" else "compare" - comp.dirty = True - return True - - elif name == "minecraft:daylight_detector": - # Right-click toggles inverted - comp.inverted = not comp.inverted - comp.dirty = True - return True - - elif name.endswith("_button"): - if not comp.powered: - comp.powered = True - comp.power = 15 - if _is_wood_button(name): - comp.active_timer = WOOD_BUTTON_DURATION - else: - btn_type = name.replace("minecraft:", "").replace("_button", "") - comp.active_timer = BUTTON_DURATIONS.get(btn_type, 10) - comp.dirty = True - self._mark_neighbors_dirty(x, y, z) - return True - - elif name == "minecraft:note_block": - # Right-click changes note pitch 0 -> 24 -> 0. - comp.note = (comp.note + 1) % 25 - comp.dirty = True - self._queue_effect("note", {"x": x, "y": y, "z": z, "note": comp.note}) - return True - - return False - - def on_projectile_hit(self, x: int, y: int, z: int): - """Handle a projectile hitting a block (for target blocks).""" - pos = (x, y, z) - comp = self.components.get(pos) - if comp and comp.block_name == "minecraft:target": - comp.power = 15 - comp.powered = True - comp.target_timer = 20 # 20 redstone ticks (2 seconds) - comp.dirty = True - self._mark_neighbors_dirty(x, y, z) - - def on_entity_move(self, x: int, y: int, z: int): - """Called when an entity moves (for pressure plates/tripwires).""" - # Check if any pressure plate at this position - for dy in range(-1, 2): - pos = (x, y + dy, z) - comp = self.components.get(pos) - if comp and comp.block_name.endswith("_pressure_plate"): - comp.dirty = True - self.dirty_positions.add(pos) - - # -------------------------------------------------- - # Scan existing world for redstone components - # -------------------------------------------------- - - def scan_chunk(self, chunk_x: int, chunk_z: int, chunk_blocks): - """Scan a chunk for redstone components and register them.""" - if chunk_blocks is None: - return - - for y_idx in range(len(chunk_blocks)): - for lz in range(16): - for lx in range(16): - block_id = int(chunk_blocks[y_idx][lz][lx]) - name = _get_block_name(block_id) - if name and is_redstone_block(name): - world_y = y_idx + MIN_Y # MIN_Y = -64, y_idx 0 -> y=-64 - world_x = chunk_x * 16 + lx - world_z = chunk_z * 16 + lz - pos = (world_x, world_y, world_z) - if pos not in self.components: - self.register_component(world_x, world_y, world_z, block_id) - - # -------------------------------------------------- - # Get visual updates for client sync - # -------------------------------------------------- - - def get_visual_updates(self) -> list[tuple[int, int, int, int]]: - """Get the list of block state changes that need to be sent to clients. - - Returns list of (x, y, z, new_block_state_id). - """ - return list(self.visual_updates) - - # -------------------------------------------------- - # Debug / admin utilities - # -------------------------------------------------- - - def get_status(self) -> dict: - """Get engine status for admin/debug display.""" - return { - "tick": self.current_tick, - "components": len(self.components), - "scheduled_updates": len(self.scheduled_updates), - "tick_time_ms": round(self._tick_time_ms, 2), - "native_engine": self._native_engine is not None, - "wires": sum(1 for c in self.components.values() if c.block_name in REDSTONE_WIRE_NAMES), - "torches": sum(1 for c in self.components.values() if c.block_name in REDSTONE_TORCH_NAMES), - "repeaters": sum(1 for c in self.components.values() if c.block_name in REDSTONE_REPEATER_NAMES), - "comparators": sum(1 for c in self.components.values() if c.block_name in REDSTONE_COMPARATOR_NAMES), - "observers": sum(1 for c in self.components.values() if c.block_name in REDSTONE_OBSERVER_NAMES), - "pistons": sum(1 for c in self.components.values() if c.block_name in PISTON_NAMES), - "activatables": sum(1 for c in self.components.values() if c.block_name in REDSTONE_ACTIVATABLE), - } - - def force_update_all(self): - """Force all components to recalculate. Useful after world edits.""" - for pos, comp in self.components.items(): - comp.dirty = True - self.dirty_positions.update(self.components.keys()) diff --git a/world/rs/blocks.py b/world/rs/blocks.py index 74a59fd..7f2dc9e 100644 --- a/world/rs/blocks.py +++ b/world/rs/blocks.py @@ -79,10 +79,6 @@ def is_face_sturdy(state: int, face: str) -> bool: return False -def is_signal_source_name(name: str) -> bool: - return name in SIGNAL_SOURCES - - def is_diode(state: int) -> bool: return name_of(state) in ("minecraft:repeater", "minecraft:comparator") diff --git a/world/rs/core.py b/world/rs/core.py index 80404bb..de24762 100644 --- a/world/rs/core.py +++ b/world/rs/core.py @@ -202,9 +202,6 @@ def get(self, pos) -> int: state = self.raw(pos) return 0 if state is None else state - def is_loaded(self, pos) -> bool: - return self.raw(pos) is not None - def _write(self, pos, state: int) -> bool: x, y, z = pos if y < -64 or y > 319: diff --git a/world/rs/native.py b/world/rs/native.py index f51235d..373a929 100644 --- a/world/rs/native.py +++ b/world/rs/native.py @@ -23,11 +23,11 @@ from pathlib import Path from . import RedstoneEngine, _holds_placeable_item, registry -from .core import DIRECTIONS, name_of +from .core import name_of logger = logging.getLogger("PyMC.红石") -ABI_VERSION = 3 +ABI_VERSION = 6 LOAD_CHUNK = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_uint16)) CONTAINER_SIGNAL = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int) @@ -89,6 +89,7 @@ def _declare(lib): i, i32p, d = ctypes.c_int, ctypes.POINTER(ctypes.c_int32), ctypes.c_double lib.vrs_init.argtypes = [ctypes.c_char_p] lib.vrs_set_callbacks.argtypes = [LOAD_CHUNK, CONTAINER_SIGNAL, ENTITY_COUNT] + lib.vrs_set_chunk_limit.argtypes = [i] lib.vrs_set_hopper_callbacks.argtypes = [INV_GET, CAN_PLACE, TAKE, GIVE, PICKUP, COMPOST, i] lib.vrs_tick_hopper_minecarts.argtypes = [i32p, ctypes.POINTER(d), ctypes.POINTER(ctypes.c_uint8), i] for name in ("vrs_drain_changes", "vrs_drain_effects", "vrs_drain_actions", "vrs_drain_hopper_changes", @@ -103,6 +104,13 @@ def _declare(lib): ctypes.POINTER(d), i32p, i] lib.vrs_exposure.argtypes = [i, i32p, ctypes.POINTER(ctypes.c_void_p), i, i] + [d] * 9 lib.vrs_exposure.restype = d + vp = ctypes.c_void_p + lib.vrs_light_set_tables.argtypes = [vp, vp, i] + lib.vrs_light_compute.argtypes = [vp, i, vp, vp] + lib.vrs_biome_create.argtypes = [ctypes.POINTER(d), i, ctypes.c_char_p] + lib.vrs_biome_create.restype = vp + lib.vrs_biome_destroy.argtypes = [vp] + lib.vrs_biome_sections.argtypes = [vp, i, i, ctypes.POINTER(ctypes.c_int32), ctypes.POINTER(ctypes.c_int32)] def load_library(): @@ -206,7 +214,7 @@ def _chunk_set(get_chunk, x: float, y: float, z: float, reach: float): class NativeRedstoneEngine(RedstoneEngine): """RedstoneEngine on top of native/vanilla (plus vanilla hoppers).""" - REFRESH_TICKS = 100 # re-read chunks from storage this often (writes that bypass the engine) + DEFAULT_CHUNK_LIMIT = 256 # chunks kept in the C++ mirror (about 196 KB each) def __init__(self, server): lib = load_library() @@ -221,7 +229,6 @@ def __init__(self, server): self.block_actions: list = [] self._item_keys: dict = {} self._item_proto: list = [None] - self._ticks_since_refresh = 0 self._buf = (ctypes.c_int32 * (6 * 4096))() from ..inventory import ItemStack bone_meal = self._item_key(ItemStack("minecraft:bone_meal", 1)) @@ -230,6 +237,9 @@ def __init__(self, server): CAN_PLACE(self._cb_can_place), TAKE(self._cb_take), GIVE(self._cb_give), PICKUP(self._cb_pickup), COMPOST(self._cb_compost)) lib.vrs_set_callbacks(*self._callbacks[:3]) + limit = int(server.config.get("redstone-chunk-cache", self.DEFAULT_CHUNK_LIMIT)) \ + if isinstance(getattr(server, "config", None), dict) else self.DEFAULT_CHUNK_LIMIT + lib.vrs_set_chunk_limit(limit) lib.vrs_set_hopper_callbacks(*self._callbacks[3:], bone_meal) self._block_names = self._registry_names() self._load_ticks() @@ -488,10 +498,6 @@ def _cb_pickup(self, kind, a, b, c): def tick(self): lib = self.lib - self._ticks_since_refresh += 1 - if self._ticks_since_refresh >= self.REFRESH_TICKS: - self._ticks_since_refresh = 0 - lib.vrs_invalidate_all() if not lib.vrs_tick(): logger.warning("Native redstone tick failed") hoppers = self._hopper_positions() @@ -535,9 +541,6 @@ def mirror_block(self, x: int, y: int, z: int, state: int): def invalidate_chunk(self, cx: int, cz: int): self.lib.vrs_invalidate_chunk(int(cx), int(cz)) - def invalidate_all(self): - self.lib.vrs_invalidate_all() - def on_container_changed(self, x: int, y: int, z: int): self.lib.vrs_container_changed(int(x), int(y), int(z)) self._finish_step() diff --git a/world/rs/piston.py b/world/rs/piston.py index 20481c3..4254ddc 100644 --- a/world/rs/piston.py +++ b/world/rs/piston.py @@ -11,11 +11,11 @@ from __future__ import annotations -from .blocks import Block, destroy_speed, is_face_sturdy +from .blocks import Block, destroy_speed from .core import ( - AIR, DATA_3D, DIRECTIONS, FROM_3D, OPP, SHAPE_ORDER, UPDATE_ALL, UPDATE_CLIENTS, - UPDATE_INVISIBLE, UPDATE_KNOWN_SHAPE, UPDATE_MOVE_BY_PISTON, UPDATE_NEIGHBORS, - default_state, java_hash_order, name_of, prop, rel, with_props, + AIR, DATA_3D, DIRECTIONS, FROM_3D, OPP, UPDATE_ALL, UPDATE_CLIENTS, UPDATE_INVISIBLE, + UPDATE_KNOWN_SHAPE, UPDATE_MOVE_BY_PISTON, default_state, java_hash_order, + name_of, prop, rel, with_props, ) MOVING_PISTON = "minecraft:moving_piston" diff --git a/world/spawning.py b/world/spawning.py new file mode 100644 index 0000000..3f5c49f --- /dev/null +++ b/world/spawning.py @@ -0,0 +1,207 @@ +# ============================================================ +# PyMC - natural mob spawning and despawning +# +# Rules follow vanilla 1.21.1 for the mobs the server has: +# * hostile mobs (zombie, skeleton, creeper, spider) spawn where the light a +# mob sees is 7 or less: max(block light, sky light - sky darkness), where +# the sky darkness is 11 at night and 0 by day; they never spawn in peaceful; +# * passive mobs (pig, cow, sheep) spawn on grass in light 9 or more; +# * no spawn within 24 blocks of a player, no spawn in water or lava; +# * caps: 70 hostile and 10 passive mobs per online player; +# * despawn: any mob with no player within 128 blocks is removed; a hostile +# mob further than 32 blocks from every player is removed with a small chance. +# +# Approximations: spawn positions are on the surface of the ring around a player +# (vanilla also spawns in caves), there is no group spawning, and the sky darkness +# ignores weather. The light of a chunk comes from world.lighting (per chunk). +# ============================================================ + +from __future__ import annotations + +import math +import random + +from .blocks import AIR, GRASS_BLOCK, LAVA, WATER + +HOSTILE = ("zombie", "skeleton", "creeper", "spider") +PASSIVE = ("pig", "cow", "sheep") + +SPAWN_INTERVAL = 10 # ticks between spawn cycles +DESPAWN_INTERVAL = 200 # ticks between despawn checks +ATTEMPTS = 6 # spawn attempts per player per category and cycle +MIN_DISTANCE = 24.0 # no spawns closer than this to any player +MAX_RING = 96 # spawn attempts land this far (at most) from the player +HOSTILE_CAP = 70 # per online player +PASSIVE_CAP = 10 # per online player +DESPAWN_FAR = 128.0 # removed at once beyond this +DESPAWN_SOFT = 32.0 # hostile mobs beyond this may be removed +DESPAWN_CHANCE = 0.25 # chance per check for a hostile mob beyond DESPAWN_SOFT +CHUNK_LIGHT_TTL = 200 # ticks a chunk's light is reused for +CHUNK_LIGHT_LIMIT = 256 +_LIQUIDS = frozenset({WATER, LAVA}) + + +def sky_darkness(world_time: int) -> int: + """How much the sky light is darkened at this time of day (vanilla: 11 at night).""" + return 11 if 13000 <= int(world_time) % 24000 <= 23000 else 0 + + +def brightness(block_light: int, sky_light: int, darkness: int) -> int: + """The light a mob sees (vanilla's getBrightness).""" + return max(block_light, sky_light - darkness) + + +def can_spawn(category: str, mob_type: str, feet: int | None, head: int | None, + ground: int | None, light: int, sky_raw: int, block_raw: int, passable) -> bool: + """Whether a mob of this kind can stand at the position (pure function, tested).""" + if feet is None or head is None or ground is None: + return False + if not passable(feet) or not passable(head) or feet in _LIQUIDS or head in _LIQUIDS: + return False + if passable(ground) or ground == AIR: + return False + if category == "hostile": + return mob_type in HOSTILE and light <= 7 + if category == "passive": + return mob_type in PASSIVE and ground == GRASS_BLOCK and max(block_raw, sky_raw) >= 9 + return False + + +# ------------------------------------------------------------ light of a chunk + +def _chunk_light(server, cx: int, cz: int, stamp: int): + """(sky, block) light arrays of a chunk, cached for CHUNK_LIGHT_TTL ticks.""" + cache = server.__dict__.setdefault("_spawn_light_cache", {}) + cached = cache.get((cx, cz)) + if cached is not None and stamp - cached[0] < CHUNK_LIGHT_TTL: + return cached[1], cached[2] + blocks = server.world_storage.load_generated_chunk(cx, cz) + if blocks is None: + return None + from .lighting import compute_light + sky, block = compute_light(blocks) + if len(cache) >= CHUNK_LIGHT_LIMIT: + cache.clear() + cache[(cx, cz)] = (stamp, sky, block) + return sky, block + + +def _light_at(server, x: int, y: int, z: int, stamp: int): + """(block light, sky light) at a block position, or None when its chunk is not loaded.""" + chunk = _chunk_light(server, x >> 4, z >> 4, stamp) + if chunk is None: + return None + index = (y + 64) * 256 + (z & 15) * 16 + (x & 15) + sky, block = chunk + return block[index], sky[index] + + +# ------------------------------------------------------------ spawning + +def _spawn_position(server, player, rng: random.Random): + """A random surface position in a ring around the player, or None.""" + angle = rng.random() * math.tau + radius = rng.uniform(MIN_DISTANCE, MAX_RING) + x = math.floor(player.x + math.cos(angle) * radius) + z = math.floor(player.z + math.sin(angle) * radius) + top = min(318, int(player.y) + 24) + bottom = max(-63, int(player.y) - 40) + for y in range(top, bottom, -1): + feet = server.get_block_at(x, y, z) + if feet is None: + return None + ground = server.get_block_at(x, y - 1, z) + if ground is not None and ground != AIR and not _passable(ground) and _passable(feet): + return x, y, z + return None + + +def _passable(block_id) -> bool: + from .entities import _is_passable + return _is_passable(block_id) + + +def _too_close(players, x: float, y: float, z: float) -> bool: + limit = MIN_DISTANCE * MIN_DISTANCE + for player in players: + dx, dz = player.x - x, player.z - z + if dx * dx + dz * dz < limit: + return True + return False + + +def run_spawning(server, tick_count: int) -> int: + """One spawn cycle (every SPAWN_INTERVAL ticks). Returns how many mobs were spawned.""" + if tick_count % SPAWN_INTERVAL: + return 0 + players = [p for p in server.get_online_players() if p.gamemode != "spectator"] + if not players: + return 0 + config = getattr(server, "config", {}) + peaceful = str(config.get("difficulty", "easy")).lower() == "peaceful" + world_time = int(getattr(server, "world_time", 0)) + darkness = sky_darkness(world_time) + rng = random.Random(tick_count ^ (server.next_entity_id * 2654435761)) + manager = server.entity_manager + stamp = tick_count + + counts = {"hostile": 0, "passive": 0} + for mob in manager.of_kind("mob"): + category = mob.profile.get("category") + if category in counts: + counts[category] += 1 + caps = {"hostile": HOSTILE_CAP * len(players), "passive": PASSIVE_CAP * len(players)} + enabled = {"hostile": config.get("spawn-monsters", True) and not peaceful, + "passive": config.get("spawn-animals", True)} + + spawned = 0 + for player in players: + for category in ("hostile", "passive"): + if not enabled[category]: + continue + for _ in range(ATTEMPTS): + if counts[category] >= caps[category]: + break + pos = _spawn_position(server, player, rng) + if pos is None: + continue + x, y, z = pos + if _too_close(players, x + 0.5, y, z + 0.5): + continue + kinds = HOSTILE if category == "hostile" else PASSIVE + mob_type = rng.choice(kinds) + light = _light_at(server, x, y, z, stamp) + if light is None: + continue + block_light, sky_light = light + feet = server.get_block_at(x, y, z) + head = server.get_block_at(x, y + 1, z) + ground = server.get_block_at(x, y - 1, z) + level = brightness(block_light, sky_light, darkness) + if not can_spawn(category, mob_type, feet, head, ground, level, + sky_light, block_light, _passable): + continue + manager.create_mob(x + 0.5, y, z + 0.5, mob_type=mob_type) + counts[category] += 1 + spawned += 1 + return spawned + + +def run_despawning(server, tick_count: int) -> int: + """Remove mobs that are too far from every player. Returns how many were removed.""" + if tick_count % DESPAWN_INTERVAL: + return 0 + players = server.get_online_players() + manager = server.entity_manager + rng = random.Random(tick_count * 31 + server.next_entity_id) + removed = 0 + for mob in list(manager.of_kind("mob")): + category = mob.profile.get("category") + if not players: + continue + nearest = min(math.hypot(p.x - mob.x, p.z - mob.z) for p in players) + if nearest > DESPAWN_FAR or (category == "hostile" and nearest > DESPAWN_SOFT + and rng.random() < DESPAWN_CHANCE): + manager.remove_entity(mob.entity_id) + removed += 1 + return removed diff --git a/world/storage.py b/world/storage.py index fc33cfd..dbe012e 100755 --- a/world/storage.py +++ b/world/storage.py @@ -50,14 +50,12 @@ import time import logging import json -import sys import threading from collections import OrderedDict from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path -from io import BytesIO -from .chunk_io import serialize_chunk, deserialize_chunk, deserialize_chunk_with_biomes -from .blocks import AIR, GRASS_BLOCK, WATER, STONE, LAVA, CACTUS, FIRE, SAND, DIRT +from .chunk_io import serialize_chunk, deserialize_chunk_with_biomes +from .blocks import AIR, WATER, LAVA, CACTUS, FIRE logger = logging.getLogger("pymc.storage") @@ -774,46 +772,6 @@ def convert_linear_to_anvil(linear_path: str, mca_path: str, return region.chunk_count -def convert_world_linear_to_anvil(world_dir: str, - compression_type: int = 2) -> int: - """ - 将世界目录中所有 Linear 文件转换为 Anvil 格式。 - - 用于导出为原版兼容格式。 - - 返回: 转换的文件数量 - """ - region_dir = Path(world_dir) / "region" - if not region_dir.exists(): - return 0 - - linear_files = list(region_dir.glob("*.linear")) - if not linear_files: - return 0 - - logger.info(f"Found {len(linear_files)} Linear region files, converting to Anvil format...") - - converted = 0 - total_chunks = 0 - - for linear_file in linear_files: - mca_file = linear_file.with_suffix('.mca') - try: - chunks = convert_linear_to_anvil(str(linear_file), str(mca_file), compression_type) - if chunks > 0: - total_chunks += chunks - converted += 1 - logger.info(f" Exported: {linear_file.name} -> {mca_file.name} " - f"({chunks} chunks)") - except Exception as e: - logger.error(f" Export failed: {linear_file.name}: {e}") - - logger.info(f"Linear -> Anvil export complete: {converted} files, " - f"total {total_chunks} chunks") - - return converted - - # ============================================================ # LRU 区域文件缓存 # ============================================================ @@ -954,11 +912,6 @@ def _evict(self): def size(self) -> int: return len(self.access_order) - def estimated_memory(self) -> int: - """估算当前缓存使用的内存。""" - return self.current_memory - - # ============================================================ # 世界存储管理器 (增强版) # ============================================================ @@ -975,6 +928,7 @@ class WorldStorage: def __init__(self, world_dir: str, max_cached_regions: int = DEFAULT_MAX_REGIONS, max_memory_mb: int = DEFAULT_MAX_MEMORY_MB, + decoded_cache_size: int | None = None, region_format: str = "anvil"): self.world_dir = Path(world_dir) self.region_format = "linear" if str(region_format).lower() == "linear" else "anvil" @@ -998,6 +952,8 @@ def __init__(self, world_dir: str, # LRU 缓存 self._cache = LRUCache(max_cached_regions, max_memory_mb) + if decoded_cache_size is not None: + self.DECODED_CACHE_SIZE = max(1, int(decoded_cache_size)) self._cache.set_flush_callback(self._flush_region_impl) # 确保目录存在 @@ -1109,7 +1065,7 @@ def load_chunk(self, cx: int, cz: int) -> bytes | None: # TPS 拖垮, 所以把解码后的数组按 LRU 缓存起来。缓存中的数组是共享对象: # 修改后必须调用 save_generated_chunk() 写回 (世界编辑代码都是这么做的)。 - DECODED_CACHE_SIZE = 192 + DECODED_CACHE_SIZE = 64 # about 1.2 MB per decoded chunk (nested lists): ~80 MB at most def _decoded_cache_get(self, key): with self._decoded_lock: @@ -1226,35 +1182,11 @@ def flush(self): except Exception as e: logger.error(f"Failed to save region ({rx}, {rz}): {e}") - def flush_region(self, rx: int, rz: int): - """保存单个区域文件。""" - with self._io_lock: - key = (rx, rz) - if not self._cache.is_dirty(key): - return - region = self._cache.get(key) - if region is None: - return - path = self._get_region_path(rx, rz) - try: - region.write(str(path)) - self._cache.dirty.discard(key) - except Exception as e: - logger.error(f"Failed to save region ({rx}, {rz}): {e}") - def has_dirty_regions(self) -> bool: """是否存在尚未落盘的区域修改。""" with self._io_lock: return bool(self._cache.dirty) - def unload_region(self, rx: int, rz: int): - """卸载区域文件 (先保存再释放内存)。""" - with self._io_lock: - key = (rx, rz) - if self._cache.is_dirty(key): - self.flush_region(rx, rz) - self._cache.remove(key) - def close(self): """关闭存储,保存所有未写入的数据。""" with self._io_lock: @@ -1385,172 +1317,6 @@ def _is_safe_spawn_location(self, chunk_blocks, local_x: int, return True - def find_safe_spawn_point(self, terrain_generator=None, - preferred_x: int = 0, - preferred_z: int = 0) -> tuple[int, int, int]: - """ - 查找安全的出生点。 - - 增强功能: - - 检查更宽的半径 (16 个区块) - - 避免水、熔岩、仙人掌、火焰 - - 优先选择 y=63-80 处的草方块 - - 在世界生成后验证出生点 - - Args: - terrain_generator: 地形生成器 (用于生成未加载的区块) - preferred_x, preferred_z: 首选的世界坐标 - - Returns: - (x, y, z) 安全出生点坐标 - """ - # 转换为区块坐标 - center_cx = preferred_x >> 4 - center_cz = preferred_z >> 4 - - best_pos = None - best_score = -1 - - # 螺旋搜索 - 16 个区块半径 - for dist in range(SAFE_SPAWN_RADIUS + 1): - for dx in range(-dist, dist + 1): - for dz in range(-dist, dist + 1): - if abs(dx) != dist and abs(dz) != dist: - continue # 只搜索外圈 - - cx = center_cx + dx - cz = center_cz + dz - - # 尝试加载或生成区块 - chunk_blocks = self.load_generated_chunk(cx, cz) - if chunk_blocks is None and terrain_generator is not None: - try: - chunk_blocks = terrain_generator.generate_chunk(cx, cz) - except Exception: - continue - - if chunk_blocks is None: - continue - - # 在区块中心寻找出生点 - wx = cx * 16 + 8 - wz = cz * 16 + 8 - local_x = 8 - local_z = 8 - - # 寻找地表 - surface_y = MIN_Y - for yi in range(WORLD_HEIGHT - 1, -1, -1): - block = chunk_blocks[yi][local_z][local_x] - if block != AIR and block != WATER: - surface_y = MIN_Y + yi - break - - # 评分系统 - score = 0 - - # 优先 y=63-80 (海平面附近, 草地高度) - if 63 <= surface_y <= 80: - score += 15 - elif 60 <= surface_y <= 90: - score += 10 - elif 50 <= surface_y <= 100: - score += 5 - - # 优先草方块 - surface_yi = surface_y - MIN_Y - if 0 <= surface_yi < WORLD_HEIGHT: - surface_block = chunk_blocks[surface_yi][local_z][local_x] - if surface_block == GRASS_BLOCK: - score += 20 - elif surface_block == DIRT: - score += 10 - elif surface_block == SAND: - score += 5 - - # 避免危险方块 - if 0 <= surface_yi < WORLD_HEIGHT: - # 检查脚下方块是否危险 - foot_block = chunk_blocks[surface_yi][local_z][local_x] - if self._is_dangerous_block(foot_block): - score -= 100 # 强烈避免 - - # 检查附近是否有危险方块 - for check_yi in range(max(0, surface_yi - 1), - min(WORLD_HEIGHT, surface_yi + 3)): - for check_dx in range(-2, 3): - for check_dz in range(-2, 3): - nx, nz = local_x + check_dx, local_z + check_dz - if 0 <= nx < 16 and 0 <= nz < 16: - check_block = chunk_blocks[check_yi][nz][nx] - if check_block in DANGEROUS_BLOCKS: - if check_block == LAVA: - score -= 50 - elif check_block == WATER: - score -= 20 - elif check_block in (FIRE, CACTUS): - score -= 30 - - # 避免水下 - if surface_y <= SEA_LEVEL: - score -= 50 - - # 避免高海拔 - if surface_y > 120: - score -= 20 - - # 距离偏好 (越近越好) - score -= dist * 2 - - # 验证出生点安全性 - if score > 0 and self._is_safe_spawn_location( - chunk_blocks, local_x, surface_y + 1, local_z): - if score > best_score: - best_score = score - best_pos = (wx, surface_y + 1, wz) - - if best_pos is None: - # 回退: 使用首选坐标 (海平面 + 1) - return (preferred_x, SEA_LEVEL + 1, preferred_z) - - return best_pos - - def validate_spawn_point(self, spawn_x: int, spawn_y: int, - spawn_z: int) -> tuple[int, int, int]: - """ - 验证出生点是否安全,不安全则寻找附近的替代点。 - - 增强功能: - - 检查脚下和头部方块 - - 避免水、熔岩、仙人掌、火焰 - - 验证失败时搜索更宽区域 - - Args: - spawn_x, spawn_y, spawn_z: 待验证的出生点 - - Returns: - 验证后的安全出生点 - """ - cx = spawn_x >> 4 - cz = spawn_z >> 4 - local_x = spawn_x & 15 - local_z = spawn_z & 15 - - chunk_blocks = self.load_generated_chunk(cx, cz) - if chunk_blocks is None: - return (spawn_x, spawn_y, spawn_z) - - # 检查出生点安全性 - if self._is_safe_spawn_location(chunk_blocks, local_x, spawn_y, local_z): - return (spawn_x, spawn_y, spawn_z) - - # 寻找安全的替代点 - return self.find_safe_spawn_point( - preferred_x=spawn_x, - preferred_z=spawn_z, - ) - - # ============================================================ # 玩家存档 <-> 原版 NBT # ============================================================ diff --git a/world/terrain.py b/world/terrain.py index 816d758..1b26e4e 100755 --- a/world/terrain.py +++ b/world/terrain.py @@ -47,38 +47,22 @@ - 矿石分布: 根据高度和噪声随机嵌入 """ -import math import random as _random from functools import lru_cache -from .noise import OctaveNoise, ImprovedNoise +from .noise import OctaveNoise from .biomes import BiomeSampler +from .terrain_decor import DecorationMixin from .blocks import ( - AIR, STONE, GRANITE, DIORITE, ANDESITE, - GRASS_BLOCK, DIRT, COARSE_DIRT, PODZOL, - COBBLESTONE, BEDROCK, - WATER, SAND, RED_SAND, GRAVEL, SANDSTONE, - COAL_ORE, IRON_ORE, GOLD_ORE, DIAMOND_ORE, LAPIS_ORE, - COPPER_ORE, EMERALD_ORE, REDSTONE_ORE, - DEEPSLATE_COAL_ORE, DEEPSLATE_IRON_ORE, DEEPSLATE_GOLD_ORE, - DEEPSLATE_DIAMOND_ORE, DEEPSLATE_LAPIS_ORE, DEEPSLATE_COPPER_ORE, - DEEPSLATE_EMERALD_ORE, DEEPSLATE_REDSTONE_ORE, - DEEPSLATE, TUFF, CLAY, - SNOW_BLOCK, SNOW, ICE, PACKED_ICE, - GRAVEL as GRAVEL_BLOCK, - OAK_LOG, OAK_LEAVES, BIRCH_LOG, BIRCH_LEAVES, - SPRUCE_LOG, SPRUCE_LEAVES, JUNGLE_LOG, JUNGLE_LEAVES, - ACACIA_LOG, ACACIA_LEAVES, CHERRY_LOG, CHERRY_LEAVES, + AIR, STONE, GRANITE, DIORITE, ANDESITE, GRASS_BLOCK, DIRT, COARSE_DIRT, + PODZOL, BEDROCK, WATER, SAND, RED_SAND, GRAVEL, SANDSTONE, COAL_ORE, + IRON_ORE, GOLD_ORE, DIAMOND_ORE, LAPIS_ORE, COPPER_ORE, EMERALD_ORE, + REDSTONE_ORE, DEEPSLATE_COAL_ORE, DEEPSLATE_IRON_ORE, + DEEPSLATE_GOLD_ORE, DEEPSLATE_DIAMOND_ORE, DEEPSLATE_LAPIS_ORE, + DEEPSLATE_COPPER_ORE, DEEPSLATE_EMERALD_ORE, DEEPSLATE_REDSTONE_ORE, + DEEPSLATE, TUFF, CLAY, SNOW_BLOCK, SNOW, ICE, OAK_LOG, OAK_LEAVES, + BIRCH_LOG, BIRCH_LEAVES, SPRUCE_LOG, SPRUCE_LEAVES, JUNGLE_LOG, + JUNGLE_LEAVES, ACACIA_LOG, ACACIA_LEAVES, CHERRY_LOG, CHERRY_LEAVES, DARK_OAK_LOG, DARK_OAK_LEAVES, MANGROVE_LOG, MANGROVE_LEAVES, - SHORT_GRASS, DANDELION, POPPY, - DIRT_PATH, - MOSS_BLOCK, - SEAGRASS, TALL_SEAGRASS, KELP, KELP_PLANT, - TUBE_CORAL_BLOCK, BRAIN_CORAL_BLOCK, BUBBLE_CORAL_BLOCK, - FIRE_CORAL_BLOCK, HORN_CORAL_BLOCK, - TUBE_CORAL_FAN, BRAIN_CORAL_FAN, BUBBLE_CORAL_FAN, - FIRE_CORAL_FAN, HORN_CORAL_FAN, - BLUE_ORCHID, ALLIUM, AZURE_BLUET, RED_TULIP, ORANGE_TULIP, - WHITE_TULIP, PINK_TULIP, OXEYE_DAISY, CORNFLOWER, LILY_OF_THE_VALLEY, ) # -------------------------------------------------- @@ -96,7 +80,7 @@ NUM_SECTIONS = WORLD_HEIGHT // SECTION_HEIGHT # 24 -class TerrainGenerator: +class TerrainGenerator(DecorationMixin): """ 类原版地形生成器。 @@ -641,43 +625,6 @@ def _place_decorations(self, blocks, height_map, base_x, base_z): elif top_block in (SAND, RED_SAND, GRAVEL, CLAY) and surface_h < SEA_LEVEL: self._place_underwater_decor(blocks, biome, lx, lz, yi, rng) - def _should_place_tree(self, biome: str, surface_h: int, rng: _random.Random) -> bool: - tree_chance = { - "minecraft:plains": 0.015, - "minecraft:forest": 0.08, - "minecraft:flower_forest": 0.07, - "minecraft:birch_forest": 0.08, - "minecraft:dark_forest": 0.09, - "minecraft:jungle": 0.10, - "minecraft:bamboo_jungle": 0.08, - "minecraft:sparse_jungle": 0.05, - "minecraft:taiga": 0.07, - "minecraft:old_growth_pine_taiga": 0.08, - "minecraft:old_growth_spruce_taiga": 0.08, - "minecraft:cherry_grove": 0.06, - "minecraft:savanna": 0.035, - "minecraft:savanna_plateau": 0.03, - "minecraft:windswept_savanna": 0.025, - "minecraft:mangrove_swamp": 0.04, - "minecraft:swamp": 0.03, - }.get(biome, 0.0) - - if surface_h > 130: - tree_chance *= 0.3 - return rng.random() < tree_chance - - def _is_clear_for_tree(self, blocks, lx: int, lz: int, trunk_base_y: int, - radius: int = 2, height: int = 7) -> bool: - for y in range(trunk_base_y, min(trunk_base_y + height, WORLD_HEIGHT)): - for dz in range(-radius, radius + 1): - for dx in range(-radius, radius + 1): - nx, nz = lx + dx, lz + dz - if not (0 <= nx < 16 and 0 <= nz < 16): - return False - if blocks[y][nz][nx] not in (AIR, WATER): - return False - return True - def _place_tree(self, blocks, biome: str, lx: int, lz: int, trunk_base_y: int, rng: _random.Random): log_block = OAK_LOG @@ -728,71 +675,6 @@ def _place_tree(self, blocks, biome: str, lx: int, lz: int, trunk_base_y: int, if top_y < WORLD_HEIGHT and blocks[top_y][lz][lx] == AIR: blocks[top_y][lz][lx] = leaves_block - def _place_surface_plant(self, blocks, biome: str, lx: int, lz: int, plant_y: int, - rng: _random.Random): - flower_tables = { - "minecraft:flower_forest": [DANDELION, POPPY, ALLIUM, AZURE_BLUET, - RED_TULIP, ORANGE_TULIP, WHITE_TULIP, - PINK_TULIP, OXEYE_DAISY, CORNFLOWER, - LILY_OF_THE_VALLEY], - "minecraft:cherry_grove": [PINK_TULIP, WHITE_TULIP, ALLIUM], - "minecraft:meadow": [ALLIUM, AZURE_BLUET, CORNFLOWER, OXEYE_DAISY], - "minecraft:swamp": [BLUE_ORCHID], - "minecraft:mangrove_swamp": [BLUE_ORCHID], - "minecraft:plains": [DANDELION, POPPY, CORNFLOWER], - "minecraft:sunflower_plains": [DANDELION, POPPY, CORNFLOWER], - } - - if biome in flower_tables and rng.random() < 0.18: - blocks[plant_y][lz][lx] = rng.choice(flower_tables[biome]) - elif biome in {"minecraft:plains", "minecraft:forest", "minecraft:birch_forest", - "minecraft:flower_forest", "minecraft:meadow", "minecraft:taiga", - "minecraft:old_growth_pine_taiga", "minecraft:old_growth_spruce_taiga"} and rng.random() < 0.35: - blocks[plant_y][lz][lx] = SHORT_GRASS - - def _place_underwater_decor(self, blocks, biome: str, lx: int, lz: int, floor_y: int, - rng: _random.Random): - water_y = floor_y + 1 - if water_y >= WORLD_HEIGHT or blocks[water_y][lz][lx] != WATER: - return - - if biome in {"minecraft:warm_ocean", "minecraft:lukewarm_ocean"} and rng.random() < 0.08: - coral_blocks = [ - TUBE_CORAL_BLOCK, BRAIN_CORAL_BLOCK, BUBBLE_CORAL_BLOCK, - FIRE_CORAL_BLOCK, HORN_CORAL_BLOCK, - ] - coral_fans = [ - TUBE_CORAL_FAN, BRAIN_CORAL_FAN, BUBBLE_CORAL_FAN, - FIRE_CORAL_FAN, HORN_CORAL_FAN, - ] - blocks[floor_y][lz][lx] = rng.choice(coral_blocks) - if water_y < WORLD_HEIGHT and blocks[water_y][lz][lx] == WATER: - blocks[water_y][lz][lx] = rng.choice(coral_fans) - return - - if biome in {"minecraft:ocean", "minecraft:deep_ocean", "minecraft:cold_ocean", - "minecraft:deep_cold_ocean", "minecraft:lukewarm_ocean", - "minecraft:warm_ocean"}: - if rng.random() < 0.22: - height = 1 + rng.randint(0, 4) - for i in range(height): - y = water_y + i - if y >= WORLD_HEIGHT or blocks[y][lz][lx] != WATER: - break - blocks[y][lz][lx] = KELP if i == height - 1 else KELP_PLANT - elif rng.random() < 0.35: - blocks[water_y][lz][lx] = SEAGRASS - - def _block_hash(self, x: int, y: int, z: int) -> float: - """ - 简单的坐标哈希函数,返回 [0, 1) 的伪随机值。 - 用于基岩层随机和其他确定性随机。 - """ - n = x * 374761393 + y * 668265263 + z * 1274126177 + self.seed - n = (n ^ (n >> 13)) * 1103515245 - n = n ^ (n >> 16) - return (n & 0x7FFFFFFF) / 0x7FFFFFFF - def get_height_map(self, chunk_x: int, chunk_z: int) -> list[list[int]]: """ 计算区块高度图 (16x16)。 diff --git a/world/terrain_decor.py b/world/terrain_decor.py new file mode 100644 index 0000000..2040e6c --- /dev/null +++ b/world/terrain_decor.py @@ -0,0 +1,126 @@ +""" +Shared decoration helpers for the two Python terrain generators. + +``TerrainGenerator`` (the plain fallback) and ``VanillaTerrainGenerator`` place +trees, surface plants and underwater decoration the same way, so these methods +live here once and both classes inherit them. They use ``self.seed`` only. +""" + +import random as _random + +from .blocks import ( + AIR, WATER, SHORT_GRASS, DANDELION, POPPY, KELP, KELP_PLANT, SEAGRASS, + ALLIUM, AZURE_BLUET, BLUE_ORCHID, CORNFLOWER, LILY_OF_THE_VALLEY, + ORANGE_TULIP, OXEYE_DAISY, PINK_TULIP, RED_TULIP, WHITE_TULIP, + BRAIN_CORAL_BLOCK, BRAIN_CORAL_FAN, BUBBLE_CORAL_BLOCK, BUBBLE_CORAL_FAN, + FIRE_CORAL_BLOCK, FIRE_CORAL_FAN, HORN_CORAL_BLOCK, HORN_CORAL_FAN, + TUBE_CORAL_BLOCK, TUBE_CORAL_FAN, +) + +WORLD_HEIGHT = 384 # MAX_Y - MIN_Y + 1 + + +class DecorationMixin: + """Tree, plant and underwater decoration placement shared by both generators.""" + + def _block_hash(self, x: int, y: int, z: int) -> float: + """ + 简单的坐标哈希函数,返回 [0, 1) 的伪随机值。 + 用于基岩层随机和其他确定性随机。 + """ + n = x * 374761393 + y * 668265263 + z * 1274126177 + self.seed + n = (n ^ (n >> 13)) * 1103515245 + n = n ^ (n >> 16) + return (n & 0x7FFFFFFF) / 0x7FFFFFFF + + def _is_clear_for_tree(self, blocks, lx: int, lz: int, trunk_base_y: int, + radius: int = 2, height: int = 7) -> bool: + for y in range(trunk_base_y, min(trunk_base_y + height, WORLD_HEIGHT)): + for dz in range(-radius, radius + 1): + for dx in range(-radius, radius + 1): + nx, nz = lx + dx, lz + dz + if not (0 <= nx < 16 and 0 <= nz < 16): + return False + if blocks[y][nz][nx] not in (AIR, WATER): + return False + return True + + def _place_surface_plant(self, blocks, biome: str, lx: int, lz: int, plant_y: int, + rng: _random.Random): + flower_tables = { + "minecraft:flower_forest": [DANDELION, POPPY, ALLIUM, AZURE_BLUET, + RED_TULIP, ORANGE_TULIP, WHITE_TULIP, + PINK_TULIP, OXEYE_DAISY, CORNFLOWER, + LILY_OF_THE_VALLEY], + "minecraft:cherry_grove": [PINK_TULIP, WHITE_TULIP, ALLIUM], + "minecraft:meadow": [ALLIUM, AZURE_BLUET, CORNFLOWER, OXEYE_DAISY], + "minecraft:swamp": [BLUE_ORCHID], + "minecraft:mangrove_swamp": [BLUE_ORCHID], + "minecraft:plains": [DANDELION, POPPY, CORNFLOWER], + "minecraft:sunflower_plains": [DANDELION, POPPY, CORNFLOWER], + } + + if biome in flower_tables and rng.random() < 0.18: + blocks[plant_y][lz][lx] = rng.choice(flower_tables[biome]) + elif biome in {"minecraft:plains", "minecraft:forest", "minecraft:birch_forest", + "minecraft:flower_forest", "minecraft:meadow", "minecraft:taiga", + "minecraft:old_growth_pine_taiga", "minecraft:old_growth_spruce_taiga"} and rng.random() < 0.35: + blocks[plant_y][lz][lx] = SHORT_GRASS + + def _place_underwater_decor(self, blocks, biome: str, lx: int, lz: int, floor_y: int, + rng: _random.Random): + water_y = floor_y + 1 + if water_y >= WORLD_HEIGHT or blocks[water_y][lz][lx] != WATER: + return + + if biome in {"minecraft:warm_ocean", "minecraft:lukewarm_ocean"} and rng.random() < 0.08: + coral_blocks = [ + TUBE_CORAL_BLOCK, BRAIN_CORAL_BLOCK, BUBBLE_CORAL_BLOCK, + FIRE_CORAL_BLOCK, HORN_CORAL_BLOCK, + ] + coral_fans = [ + TUBE_CORAL_FAN, BRAIN_CORAL_FAN, BUBBLE_CORAL_FAN, + FIRE_CORAL_FAN, HORN_CORAL_FAN, + ] + blocks[floor_y][lz][lx] = rng.choice(coral_blocks) + if water_y < WORLD_HEIGHT and blocks[water_y][lz][lx] == WATER: + blocks[water_y][lz][lx] = rng.choice(coral_fans) + return + + if biome in {"minecraft:ocean", "minecraft:deep_ocean", "minecraft:cold_ocean", + "minecraft:deep_cold_ocean", "minecraft:lukewarm_ocean", + "minecraft:warm_ocean"}: + if rng.random() < 0.22: + height = 1 + rng.randint(0, 4) + for i in range(height): + y = water_y + i + if y >= WORLD_HEIGHT or blocks[y][lz][lx] != WATER: + break + blocks[y][lz][lx] = KELP if i == height - 1 else KELP_PLANT + elif rng.random() < 0.35: + blocks[water_y][lz][lx] = SEAGRASS + + def _should_place_tree(self, biome: str, surface_h: int, rng: _random.Random) -> bool: + tree_chance = { + "minecraft:plains": 0.015, + "minecraft:forest": 0.08, + "minecraft:flower_forest": 0.07, + "minecraft:birch_forest": 0.08, + "minecraft:dark_forest": 0.09, + "minecraft:jungle": 0.10, + "minecraft:bamboo_jungle": 0.08, + "minecraft:sparse_jungle": 0.05, + "minecraft:taiga": 0.07, + "minecraft:old_growth_pine_taiga": 0.08, + "minecraft:old_growth_spruce_taiga": 0.08, + "minecraft:cherry_grove": 0.06, + "minecraft:savanna": 0.035, + "minecraft:savanna_plateau": 0.03, + "minecraft:windswept_savanna": 0.025, + "minecraft:mangrove_swamp": 0.04, + "minecraft:swamp": 0.03, + }.get(biome, 0.0) + + if surface_h > 130: + tree_chance *= 0.3 + return rng.random() < tree_chance diff --git a/world/vanilla_terrain.py b/world/vanilla_terrain.py index ee660d9..e9bfe32 100755 --- a/world/vanilla_terrain.py +++ b/world/vanilla_terrain.py @@ -37,46 +37,26 @@ import math import random as _random -from dataclasses import dataclass, field +from dataclasses import dataclass from typing import Optional, Callable from .blocks import ( - AIR, STONE, GRANITE, DIORITE, ANDESITE, - GRASS_BLOCK, DIRT, COARSE_DIRT, PODZOL, - COBBLESTONE, BEDROCK, - WATER, SAND, RED_SAND, GRAVEL, SANDSTONE, - COAL_ORE, IRON_ORE, GOLD_ORE, DIAMOND_ORE, LAPIS_ORE, - COPPER_ORE, EMERALD_ORE, REDSTONE_ORE, - DEEPSLATE_COAL_ORE, DEEPSLATE_IRON_ORE, DEEPSLATE_GOLD_ORE, - DEEPSLATE_DIAMOND_ORE, DEEPSLATE_LAPIS_ORE, DEEPSLATE_COPPER_ORE, - DEEPSLATE_EMERALD_ORE, DEEPSLATE_REDSTONE_ORE, - DEEPSLATE, TUFF, CLAY, CALCITE, - SNOW_BLOCK, SNOW, ICE, PACKED_ICE, BLUE_ICE, - OAK_LOG, OAK_LEAVES, BIRCH_LOG, BIRCH_LEAVES, - SPRUCE_LOG, SPRUCE_LEAVES, JUNGLE_LOG, JUNGLE_LEAVES, - ACACIA_LOG, ACACIA_LEAVES, - CHERRY_LOG, CHERRY_LEAVES, - DARK_OAK_LOG, DARK_OAK_LEAVES, - MANGROVE_LOG, MANGROVE_LEAVES, - SHORT_GRASS, DANDELION, POPPY, - DIRT_PATH, - MOSS_BLOCK, - SEAGRASS, TALL_SEAGRASS, KELP, KELP_PLANT, - TUBE_CORAL_BLOCK, BRAIN_CORAL_BLOCK, BUBBLE_CORAL_BLOCK, - FIRE_CORAL_BLOCK, HORN_CORAL_BLOCK, - TUBE_CORAL_FAN, BRAIN_CORAL_FAN, BUBBLE_CORAL_FAN, - FIRE_CORAL_FAN, HORN_CORAL_FAN, - BLUE_ORCHID, ALLIUM, AZURE_BLUET, RED_TULIP, ORANGE_TULIP, - WHITE_TULIP, PINK_TULIP, OXEYE_DAISY, CORNFLOWER, LILY_OF_THE_VALLEY, - TERRACOTTA, WHITE_TERRACOTTA, ORANGE_TERRACOTTA, YELLOW_TERRACOTTA, - RED_TERRACOTTA, BROWN_TERRACOTTA, GREEN_TERRACOTTA, - LIGHT_GRAY_TERRACOTTA, GRAY_TERRACOTTA, LIGHT_BLUE_TERRACOTTA, - MAGENTA_TERRACOTTA, PINK_TERRACOTTA, LIME_TERRACOTTA, - CYAN_TERRACOTTA, PURPLE_TERRACOTTA, BLUE_TERRACOTTA, - RAW_IRON_BLOCK, RAW_COPPER_BLOCK, - LAVA, + AIR, STONE, GRANITE, DIORITE, ANDESITE, GRASS_BLOCK, DIRT, COARSE_DIRT, + PODZOL, COBBLESTONE, BEDROCK, WATER, SAND, RED_SAND, GRAVEL, SANDSTONE, + COAL_ORE, IRON_ORE, GOLD_ORE, DIAMOND_ORE, LAPIS_ORE, COPPER_ORE, + EMERALD_ORE, REDSTONE_ORE, DEEPSLATE_COAL_ORE, DEEPSLATE_IRON_ORE, + DEEPSLATE_GOLD_ORE, DEEPSLATE_DIAMOND_ORE, DEEPSLATE_LAPIS_ORE, + DEEPSLATE_COPPER_ORE, DEEPSLATE_EMERALD_ORE, DEEPSLATE_REDSTONE_ORE, + DEEPSLATE, TUFF, CLAY, CALCITE, SNOW_BLOCK, SNOW, ICE, PACKED_ICE, + OAK_LOG, OAK_LEAVES, BIRCH_LOG, BIRCH_LEAVES, SPRUCE_LOG, + SPRUCE_LEAVES, JUNGLE_LOG, JUNGLE_LEAVES, ACACIA_LOG, ACACIA_LEAVES, + CHERRY_LOG, CHERRY_LEAVES, DARK_OAK_LOG, DARK_OAK_LEAVES, MANGROVE_LOG, + MANGROVE_LEAVES, TERRACOTTA, WHITE_TERRACOTTA, ORANGE_TERRACOTTA, + YELLOW_TERRACOTTA, RED_TERRACOTTA, BROWN_TERRACOTTA, + LIGHT_GRAY_TERRACOTTA, LAVA, ) from .biomes import BIOME_NAME_TO_ID +from .terrain_decor import DecorationMixin # -------------------------------------------------- # World constants (vanilla overworld) @@ -311,9 +291,6 @@ def noise(self, x: float, y: float, z: float, y_smooth_input, ) - def _p_idx(self, idx: int) -> int: - return self._p[idx & 0xFF] - @staticmethod def _grad_dot(h: int, x: float, y: float, z: float) -> float: g = _GRADIENT[h & 0x0F] @@ -511,19 +488,6 @@ def compute(self, x: float, y: float, z: float, return self._noise.get_value(sx, sy, sz) -class Clamped(DensityFunction): - """Clamp a density function output to [min, max].""" - - def __init__(self, inner: DensityFunction, min_val: float, max_val: float): - self._inner = inner - self._min = min_val - self._max = max_val - - def compute(self, x: float, y: float, z: float, - climate: 'ClimateSample') -> float: - return max(self._min, min(self._max, self._inner.compute(x, y, z, climate))) - - class Spline(DensityFunction): """ Vanilla's cubic spline interpolation. @@ -581,20 +545,6 @@ def _extract_value(self, x, y, z, climate): return climate.erosion -class PeaksValleysSpline(Spline): - """Spline that maps peaks_and_valleys to density contribution.""" - - def _extract_value(self, x, y, z, climate): - return climate.peaks_valleys - - -class WeirdnessSpline(Spline): - """Spline that maps weirdness to density contribution.""" - - def _extract_value(self, x, y, z, climate): - return climate.weirdness - - def _catmull_rom(p0: float, p1: float, p2: float, p3: float, t: float) -> float: """Catmull-Rom cubic interpolation.""" t2 = t * t @@ -720,41 +670,6 @@ def compute(self, x: float, y: float, z: float, return max(self._min, min(self._max, result)) -class AddDensity(DensityFunction): - """Add two density functions.""" - - def __init__(self, a: DensityFunction, b: DensityFunction): - self._a = a - self._b = b - - def compute(self, x: float, y: float, z: float, - climate: 'ClimateSample') -> float: - return self._a.compute(x, y, z, climate) + self._b.compute(x, y, z, climate) - - -class MulDensity(DensityFunction): - """Multiply two density functions.""" - - def __init__(self, a: DensityFunction, b: DensityFunction): - self._a = a - self._b = b - - def compute(self, x: float, y: float, z: float, - climate: 'ClimateSample') -> float: - return self._a.compute(x, y, z, climate) * self._b.compute(x, y, z, climate) - - -class ConstantDensity(DensityFunction): - """Constant density value.""" - - def __init__(self, value: float): - self._value = value - - def compute(self, x: float, y: float, z: float, - climate: 'ClimateSample') -> float: - return self._value - - class CacheOnce(DensityFunction): """Caches density computation within a single chunk to avoid redundant sampling.""" @@ -920,26 +835,6 @@ def compute(self, x: float, y: float, z: float, ] -def _spline_interpolate(points: list[tuple[float, float]], value: float) -> float: - """Cubic spline interpolation between control points.""" - if not points: - return 0.0 - if value <= points[0][0]: - return points[0][1] - if value >= points[-1][0]: - return points[-1][1] - for i in range(len(points) - 1): - if points[i][0] <= value <= points[i + 1][0]: - t = (value - points[i][0]) / (points[i + 1][0] - points[i][0]) - # Catmull-Rom cubic - p0 = points[max(0, i - 1)][1] - p1 = points[i][1] - p2 = points[i + 1][1] - p3 = points[min(len(points) - 1, i + 2)][1] - return _catmull_rom(p0, p1, p2, p3, t) - return points[-1][1] - - # ============================================================ # Climate parameter noise configurations (vanilla exact) # ============================================================ @@ -990,10 +885,6 @@ def _span(a: float, b: float) -> ClimateRange: return ClimateRange(b, a) -def _span2(a: ClimateRange, b: ClimateRange) -> ClimateRange: - return ClimateRange(min(a.min_val, b.min_val), max(a.max_val, b.max_val)) - - def _point(v: float) -> ClimateRange: return ClimateRange(v, v) @@ -1347,51 +1238,6 @@ def _add_biomes(self): # Biome height parameters (vanilla-like) # ============================================================ -def _biome_height_params(biome_id: int) -> tuple[float, float]: - """Return (base_height, variation) for a biome, matching vanilla's MultiNoise terrain shaping.""" - E = _BiomeId - mountain = {E.JAGGED_PEAKS, E.FROZEN_PEAKS, E.STONY_PEAKS} - mid_mountain = {E.SNOWY_SLOPES, E.GROVE, E.MEADOW, E.CHERRY_GROVE} - hills = {E.WINDSWEPT_HILLS, E.WINDSWEPT_GRAVELLY_HILLS, E.WINDSWEPT_FOREST} - badlands = {E.BADLANDS, E.ERODED_BADLANDS, E.WOODED_BADLANDS} - flat = {E.PLAINS, E.SUNFLOWER_PLAINS, E.DESERT, E.SNOWY_PLAINS} - forest = {E.FOREST, E.FLOWER_FOREST, E.BIRCH_FOREST, E.DARK_FOREST, - E.OLD_GROWTH_BIRCH_FOREST} - taiga = {E.TAIGA, E.OLD_GROWTH_PINE_TAIGA, E.OLD_GROWTH_SPRUCE_TAIGA, E.SNOWY_TAIGA} - - if biome_id in (E.OCEAN, E.DEEP_OCEAN, E.WARM_OCEAN, E.LUKEWARM_OCEAN, - E.COLD_OCEAN, E.FROZEN_OCEAN, E.DEEP_COLD_OCEAN, - E.DEEP_FROZEN_OCEAN, E.DEEP_LUKEWARM_OCEAN): - return -0.70, 0.15 - if biome_id in (E.RIVER, E.FROZEN_RIVER): - return -0.50, 0.05 - if biome_id in (E.BEACH, E.SNOWY_BEACH): - return -0.05, 0.03 - if biome_id == E.STONY_SHORE: - return 0.10, 0.08 - if biome_id in (E.SWAMP, E.MANGROVE_SWAMP): - return -0.20, 0.08 - if biome_id in mountain: - return 1.30, 0.70 - if biome_id in mid_mountain: - return 0.55, 0.30 - if biome_id in hills: - return 1.00, 0.50 - if biome_id in badlands: - return 0.30, 0.20 - if biome_id == E.SAVANNA_PLATEAU: - return 0.35, 0.20 - if biome_id in flat: - return 0.125, 0.05 - if biome_id in forest: - return 0.10, 0.20 - if biome_id in taiga: - return 0.20, 0.20 - if biome_id == E.ICE_SPIKES: - return 0.45, 0.50 - return 0.125, 0.05 - - # ============================================================ # Vanilla Density Function Tree # ============================================================ @@ -2360,7 +2206,7 @@ def place(self, blocks: list, base_x: int, base_z: int): # VanillaTerrainGenerator # ============================================================ -class VanillaTerrainGenerator: +class VanillaTerrainGenerator(DecorationMixin): """ Vanilla-style approximate terrain generator for Minecraft Java 1.21.1. @@ -2641,43 +2487,6 @@ def _place_decorations(self, blocks, height_map, biome_map, base_x, base_z): elif top_block in (SAND, RED_SAND, GRAVEL, CLAY) and surface_h < SEA_LEVEL: self._place_underwater_decor(blocks, biome, lx, lz, yi, rng) - def _should_place_tree(self, biome: str, surface_h: int, rng: _random.Random) -> bool: - tree_chance = { - "minecraft:plains": 0.015, - "minecraft:forest": 0.08, - "minecraft:flower_forest": 0.07, - "minecraft:birch_forest": 0.08, - "minecraft:dark_forest": 0.09, - "minecraft:jungle": 0.10, - "minecraft:bamboo_jungle": 0.08, - "minecraft:sparse_jungle": 0.05, - "minecraft:taiga": 0.07, - "minecraft:old_growth_pine_taiga": 0.08, - "minecraft:old_growth_spruce_taiga": 0.08, - "minecraft:cherry_grove": 0.06, - "minecraft:savanna": 0.035, - "minecraft:savanna_plateau": 0.03, - "minecraft:windswept_savanna": 0.025, - "minecraft:mangrove_swamp": 0.04, - "minecraft:swamp": 0.03, - }.get(biome, 0.0) - - if surface_h > 130: - tree_chance *= 0.3 - return rng.random() < tree_chance - - def _is_clear_for_tree(self, blocks, lx: int, lz: int, trunk_base_y: int, - radius: int = 2, height: int = 7) -> bool: - for y in range(trunk_base_y, min(trunk_base_y + height, WORLD_HEIGHT)): - for dz in range(-radius, radius + 1): - for dx in range(-radius, radius + 1): - nx, nz = lx + dx, lz + dz - if not (0 <= nx < 16 and 0 <= nz < 16): - return False - if blocks[y][nz][nx] not in (AIR, WATER): - return False - return True - def _place_tree(self, blocks, biome: str, lx: int, lz: int, trunk_base_y: int, rng: _random.Random): log_block = OAK_LOG @@ -2731,69 +2540,6 @@ def _place_tree(self, blocks, biome: str, lx: int, lz: int, if top_y < WORLD_HEIGHT and blocks[top_y][lz][lx] == AIR: blocks[top_y][lz][lx] = leaves_block - def _place_surface_plant(self, blocks, biome: str, lx: int, lz: int, - plant_y: int, rng: _random.Random): - flower_tables = { - "minecraft:flower_forest": [DANDELION, POPPY, ALLIUM, AZURE_BLUET, - RED_TULIP, ORANGE_TULIP, WHITE_TULIP, - PINK_TULIP, OXEYE_DAISY, CORNFLOWER, - LILY_OF_THE_VALLEY], - "minecraft:cherry_grove": [PINK_TULIP, WHITE_TULIP, ALLIUM], - "minecraft:meadow": [ALLIUM, AZURE_BLUET, CORNFLOWER, OXEYE_DAISY], - "minecraft:swamp": [BLUE_ORCHID], - "minecraft:mangrove_swamp": [BLUE_ORCHID], - "minecraft:plains": [DANDELION, POPPY, CORNFLOWER], - "minecraft:sunflower_plains": [DANDELION, POPPY, CORNFLOWER], - } - - if biome in flower_tables and rng.random() < 0.18: - blocks[plant_y][lz][lx] = rng.choice(flower_tables[biome]) - elif biome in {"minecraft:plains", "minecraft:forest", "minecraft:birch_forest", - "minecraft:flower_forest", "minecraft:meadow", "minecraft:taiga", - "minecraft:old_growth_pine_taiga", - "minecraft:old_growth_spruce_taiga"} and rng.random() < 0.35: - blocks[plant_y][lz][lx] = SHORT_GRASS - - def _place_underwater_decor(self, blocks, biome: str, lx: int, lz: int, - floor_y: int, rng: _random.Random): - water_y = floor_y + 1 - if water_y >= WORLD_HEIGHT or blocks[water_y][lz][lx] != WATER: - return - - if biome in {"minecraft:warm_ocean", "minecraft:lukewarm_ocean"} and rng.random() < 0.08: - coral_blocks = [ - TUBE_CORAL_BLOCK, BRAIN_CORAL_BLOCK, BUBBLE_CORAL_BLOCK, - FIRE_CORAL_BLOCK, HORN_CORAL_BLOCK, - ] - coral_fans = [ - TUBE_CORAL_FAN, BRAIN_CORAL_FAN, BUBBLE_CORAL_FAN, - FIRE_CORAL_FAN, HORN_CORAL_FAN, - ] - blocks[floor_y][lz][lx] = rng.choice(coral_blocks) - if water_y < WORLD_HEIGHT and blocks[water_y][lz][lx] == WATER: - blocks[water_y][lz][lx] = rng.choice(coral_fans) - return - - if biome in {"minecraft:ocean", "minecraft:deep_ocean", "minecraft:cold_ocean", - "minecraft:deep_cold_ocean", "minecraft:lukewarm_ocean", - "minecraft:warm_ocean"}: - if rng.random() < 0.22: - height = 1 + rng.randint(0, 4) - for i in range(height): - y = water_y + i - if y >= WORLD_HEIGHT or blocks[y][lz][lx] != WATER: - break - blocks[y][lz][lx] = KELP if i == height - 1 else KELP_PLANT - elif rng.random() < 0.35: - blocks[water_y][lz][lx] = SEAGRASS - - def _block_hash(self, x: int, y: int, z: int) -> float: - """Simple coordinate hash for deterministic randomness.""" - n = x * 374761393 + y * 668265263 + z * 1274126177 + self.seed - n = (n ^ (n >> 13)) * 1103515245 - n = n ^ (n >> 16) - return (n & 0x7FFFFFFF) / 0x7FFFFFFF - def get_height_map(self, chunk_x: int, chunk_z: int) -> list[list[int]]: """Compute height map for a chunk.""" base_x = chunk_x * 16