feat: Fabric 1.21.4 + Baritone 自动铺轨 mod 完整实现
- RailProcess: 点到点铺轨(Yaw 取向前方 2 格、合法右键放置、GoalBlock 行走循环) - 节奏 5 tick(250ms) 适配多人服务器、热键栏切换与 UpdateSelectedSlot 同步 - 悬空自动用圆石垫脚石搭桥、calcFailed 卡死兜底 - 修复 1.21.4 sendMessage 签名编译错误、Gradle 守护进程钉到 JDK 21 - 新增 README 与 .gitignore
这个提交包含在:
+20
@@ -0,0 +1,20 @@
|
||||
# Gradle
|
||||
.gradle/
|
||||
build/
|
||||
out/
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
*.iml
|
||||
.vscode/
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
||||
bin/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# 本地环境
|
||||
*.local
|
||||
@@ -0,0 +1,39 @@
|
||||
# AutoRail — 自动铺铁轨(Fabric 1.21.4 + Baritone API)
|
||||
|
||||
面向方向自动铺设铁轨的 Minecraft 客户端模组。不依赖 Baritone 寻路来规划轨道——
|
||||
它只借 Baritone 的行走能力做“点到点建造”,保证铁轨能铺过悬崖边等寻路会回避的地形。
|
||||
|
||||
## 使用
|
||||
|
||||
1. 安装 [Fabric Loader ≥0.16.9](https://fabricmc.net/use/) 与 [Fabric API](https://modrinth.com/mod/fabric-api),以及 Baritone(1.13.1,兼容 1.21.4 的版本)。
|
||||
2. 把 `autorail-<version>.jar` 放进 `mods/`。
|
||||
3. 进游戏后按 **R** 开启/关闭。背包里要有**铁轨**(垫脚石需要时还要有**圆石**)。
|
||||
4. 按住/调整视角方向→玩家会边走边往正前方铺直轨;手动转 90° 即可转弯(只铺直轨)。
|
||||
5. 前方被阻挡、找不到地面、铁轨耗尽时自动停止并提示。
|
||||
|
||||
## 行为逻辑
|
||||
|
||||
- **取朝向**:读取玩家水平朝向(Yaw),计算正前方 2 格处的地面。
|
||||
- **放置**:切换热键栏到铁轨并同步 `UpdateSelectedSlotC2S`,随后通过
|
||||
`ClientPlayerInteractionManager`(Baritone 的 `IPlayerController`)发送右键放置——
|
||||
**全程合法交互,绝不 `world.setBlockState`**,多人服务器才会承认。
|
||||
- **移动**:放置后设 `GoalBlock` 让玩家走到目标点,循环往复。
|
||||
- **节奏**:每次动作间隔 5 tick(250ms),处于多人服务器建议的 200~300ms 区间。
|
||||
- **垫脚石**:目标列下方悬空/落差超过 2 格时,先拿圆石右键垫补,再接铺铁轨(可选逻辑,已实现)。
|
||||
- **铁轨朝向**:交给原版自动衔接(直轨)。转弯靠玩家手动转视角,开发量减半。
|
||||
|
||||
## 开发
|
||||
|
||||
```bash
|
||||
gradlew build # 产物在 build/libs/autorall-<version>.jar
|
||||
```
|
||||
|
||||
- `src/main/java/com/autorall/AutoRailClient.java` — 入口:按键绑定、进程注册
|
||||
- `src/main/java/com/autorall/process/RailProcess.java` — 铺轨主逻辑(`IBaritoneProcess`)
|
||||
- Baritone API 依赖:`libs/baritone-api-fabric-1.13.1.jar`(本地 `modImplementation`,Loom 自动重映射)
|
||||
|
||||
## 已知限制
|
||||
|
||||
- 只铺普通铁轨(`minecraft:rail`),不支持动力铁轨/探测铁轨。
|
||||
- 只铺直轨;曲线由原版在相邻铁轨存在时自动形成,手动转弯请让两段直线夹角足够清晰。
|
||||
- `isSolidBlock` 等判定基于客户端世界状态;服务器延误时可能出现个别放置失败,会自动重试。
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
plugins {
|
||||
id 'fabric-loom' version '1.9-SNAPSHOT'
|
||||
id 'maven-publish'
|
||||
}
|
||||
|
||||
version = project.mod_version
|
||||
group = project.maven_group
|
||||
|
||||
base {
|
||||
archivesName = project.archives_base_name
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
minecraft "com.mojang:minecraft:${project.minecraft_version}"
|
||||
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
|
||||
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
|
||||
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
|
||||
|
||||
modImplementation files("libs/baritone-api-fabric-${project.baritone_version}.jar")
|
||||
}
|
||||
|
||||
processResources {
|
||||
inputs.property "version", project.version
|
||||
filesMatching("fabric.mod.json") {
|
||||
expand "version": project.version
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
it.options.encoding = "UTF-8"
|
||||
it.options.release = 21
|
||||
}
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_21
|
||||
targetCompatibility = JavaVersion.VERSION_21
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
org.gradle.jvmargs=-Xmx2G
|
||||
org.gradle.parallel=true
|
||||
# Gradle 8.11 不支持 JDK 24+ 作为守护进程(会报 "Type T not present"),固定用 JDK 21
|
||||
org.gradle.java.home=C:/Program Files/Java/jdk-21
|
||||
|
||||
minecraft_version=1.21.4
|
||||
yarn_mappings=1.21.4+build.2
|
||||
loader_version=0.16.9
|
||||
|
||||
fabric_version=0.112.0+1.21.4
|
||||
|
||||
mod_version=1.0.0
|
||||
maven_group=com.autorail
|
||||
archives_base_name=autorail
|
||||
|
||||
baritone_version=1.13.1
|
||||
二进制
二进制文件未显示。
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -0,0 +1,252 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
|
||||
' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
第三方依赖
+94
@@ -0,0 +1,94 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
二进制文件未显示。
+12
@@ -0,0 +1,12 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
maven {
|
||||
name = 'Fabric'
|
||||
url = 'https://maven.fabricmc.net/'
|
||||
}
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = 'autorail'
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.autorail;
|
||||
|
||||
import baritone.api.BaritoneAPI;
|
||||
import com.autorail.process.RailProcess;
|
||||
import net.fabricmc.api.ClientModInitializer;
|
||||
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
|
||||
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.client.option.KeyBinding;
|
||||
import net.minecraft.client.util.InputUtil;
|
||||
import net.minecraft.text.Text;
|
||||
import org.lwjgl.glfw.GLFW;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class AutoRailClient implements ClientModInitializer {
|
||||
|
||||
public static final Logger LOGGER = LoggerFactory.getLogger("autorail");
|
||||
public static final RailProcess RAIL_PROCESS = new RailProcess();
|
||||
|
||||
private static KeyBinding toggleKey;
|
||||
private static boolean registered = false;
|
||||
|
||||
@Override
|
||||
public void onInitializeClient() {
|
||||
toggleKey = KeyBindingHelper.registerKeyBinding(new KeyBinding(
|
||||
"key.autorail.toggle",
|
||||
InputUtil.Type.KEYSYM,
|
||||
GLFW.GLFW_KEY_R,
|
||||
"category.autorail"
|
||||
));
|
||||
|
||||
ClientTickEvents.END_CLIENT_TICK.register(AutoRailClient::onClientTick);
|
||||
}
|
||||
|
||||
private static void onClientTick(MinecraftClient client) {
|
||||
registerIfNeeded(client);
|
||||
|
||||
while (toggleKey.wasPressed()) {
|
||||
if (client.player == null || client.world == null) {
|
||||
sendMessage(client, "请先进入世界再使用");
|
||||
continue;
|
||||
}
|
||||
if (!registered) {
|
||||
sendMessage(client, "未检测到 Baritone,无法启用");
|
||||
continue;
|
||||
}
|
||||
if (RAIL_PROCESS.isActive()) {
|
||||
RAIL_PROCESS.stop();
|
||||
sendMessage(client, "自动铺轨已停止");
|
||||
} else {
|
||||
RAIL_PROCESS.start();
|
||||
sendMessage(client, "自动铺轨已启动(R 停止,只铺直轨,转弯请手动转向)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 进程只需注册一次(Baritone 在同一个游戏会话内跨世界保持存在)。
|
||||
*/
|
||||
private static void registerIfNeeded(MinecraftClient client) {
|
||||
if (registered || client.world == null || !FabricLoader.getInstance().isModLoaded("baritone")) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
BaritoneAPI.getProvider().getPrimaryBaritone()
|
||||
.getPathingControlManager()
|
||||
.registerProcess(RAIL_PROCESS);
|
||||
registered = true;
|
||||
LOGGER.info("AutoRail process registered");
|
||||
} catch (Throwable t) {
|
||||
LOGGER.error("Failed to register AutoRail process", t);
|
||||
}
|
||||
}
|
||||
|
||||
private static void sendMessage(MinecraftClient client, String message) {
|
||||
if (client.player != null) {
|
||||
client.player.sendMessage(Text.literal("[AutoRail] " + message), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package com.autorail.process;
|
||||
|
||||
import baritone.api.BaritoneAPI;
|
||||
import baritone.api.IBaritone;
|
||||
import baritone.api.pathing.goals.GoalBlock;
|
||||
import baritone.api.process.IBaritoneProcess;
|
||||
import baritone.api.process.PathingCommand;
|
||||
import baritone.api.process.PathingCommandType;
|
||||
import baritone.api.utils.IPlayerContext;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.block.Blocks;
|
||||
import net.minecraft.client.network.ClientPlayerEntity;
|
||||
import net.minecraft.entity.player.PlayerInventory;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.Items;
|
||||
import net.minecraft.network.packet.c2s.play.UpdateSelectedSlotC2SPacket;
|
||||
import net.minecraft.text.Text;
|
||||
import net.minecraft.util.Hand;
|
||||
import net.minecraft.util.hit.BlockHitResult;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Direction;
|
||||
import net.minecraft.util.math.MathHelper;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
/**
|
||||
* 点到点自动铺轨进程(不依赖 Baritone 寻路来规划轨道,只借它的行走能力)。
|
||||
*
|
||||
* 每一轮循环:
|
||||
* 1. 取玩家水平朝向 Yaw,算出前方 2 格处的地面(下方扫描实心方块);
|
||||
* 2. 若该列下方悬空/过深,先用圆石垫脚(搭桥);
|
||||
* 3. 否则切换热键栏到铁轨,右键地面放置(完全走合法交互,服务端才会承认);
|
||||
* 4. 设 GoalBlock 让玩家走到目标点,然后重复。
|
||||
*
|
||||
* 只铺直轨:铁轨朝向交给原版自动衔接逻辑,转弯请玩家手动转视角。
|
||||
*/
|
||||
public class RailProcess implements IBaritoneProcess {
|
||||
|
||||
/** 动作间隔(tick)。5 tick = 250ms,处于多人服务器建议的 200~300ms 区间,过快会被踢/回弹。 */
|
||||
private static final int ACTION_INTERVAL_TICKS = 5;
|
||||
/** 超过该 tick 数仍未走到目标时,视为已推进,继续铺下一段(避免永久卡死)。 */
|
||||
private static final long FORCE_PROGRESS_TICKS = 20;
|
||||
/** 目标点与玩家的水平距离(格),规范要求 1.5~2 格。 */
|
||||
private static final double TARGET_DISTANCE = 2.0;
|
||||
/** 允许的自然落差(格)。落差超过该值视为悬空,需要垫脚石。 */
|
||||
private static final int MAX_DROP = 2;
|
||||
/** calcFailed 后的宽限 tick:寻路暂时失败不立即停,超过才判定前方不可通行。 */
|
||||
private static final long CALC_FAILED_GRACE_TICKS = 10;
|
||||
|
||||
private boolean active;
|
||||
private long lastActionTick = Long.MIN_VALUE;
|
||||
private GoalBlock currentGoal;
|
||||
private long goalSetTick;
|
||||
|
||||
@Override
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTemporary() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLostControl() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String displayName0() {
|
||||
return "AutoRail";
|
||||
}
|
||||
|
||||
public void start() {
|
||||
active = true;
|
||||
currentGoal = null;
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
active = false;
|
||||
currentGoal = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PathingCommand onTick(boolean calcFailed, boolean isSafeToCancel) {
|
||||
IBaritone baritone = BaritoneAPI.getProvider().getPrimaryBaritone();
|
||||
if (baritone == null) {
|
||||
return defer();
|
||||
}
|
||||
IPlayerContext ctx = baritone.getPlayerContext();
|
||||
ClientPlayerEntity player = ctx.player();
|
||||
World world = ctx.world();
|
||||
if (player == null || world == null) {
|
||||
return defer();
|
||||
}
|
||||
|
||||
if (!active) {
|
||||
// 关闭时取消路径,让玩家停下
|
||||
return halt();
|
||||
}
|
||||
|
||||
long now = world.getTime();
|
||||
if (lastActionTick != Long.MIN_VALUE && now - lastActionTick < ACTION_INTERVAL_TICKS) {
|
||||
return defer();
|
||||
}
|
||||
|
||||
if (currentGoal != null) {
|
||||
if (calcFailed && now - goalSetTick > CALC_FAILED_GRACE_TICKS && !hasArrived(player, currentGoal, now)) {
|
||||
stop();
|
||||
notify(player, "前方无法通行,已停止(请调整朝向或清理障碍)");
|
||||
return halt();
|
||||
}
|
||||
if (!hasArrived(player, currentGoal, now)) {
|
||||
// 继续走向当前目标,不铺新的
|
||||
return new PathingCommand(currentGoal, PathingCommandType.REVALIDATE_GOAL_AND_PATH);
|
||||
}
|
||||
}
|
||||
|
||||
int railSlot = findSlot(player.getInventory(), Items.RAIL);
|
||||
if (railSlot == -1) {
|
||||
stop();
|
||||
notify(player, "背包里没有铁轨,已停止");
|
||||
return halt();
|
||||
}
|
||||
|
||||
Target target = computeTarget(player, world);
|
||||
if (target == null) {
|
||||
stop();
|
||||
notify(player, "前方没有合适的地面,已停止");
|
||||
return halt();
|
||||
}
|
||||
|
||||
if (target.needBridge) {
|
||||
return doBridge(ctx, player, world, target, now);
|
||||
}
|
||||
|
||||
BlockPos railPos = target.railPos;
|
||||
BlockState atRail = world.getBlockState(railPos);
|
||||
if (atRail.isOf(Blocks.RAIL)) {
|
||||
// 该处已有铁轨,直接走过去铺下一段
|
||||
lastActionTick = now;
|
||||
return moveTo(railPos, now);
|
||||
}
|
||||
if (!atRail.isAir() && !atRail.isReplaceable()) {
|
||||
stop();
|
||||
notify(player, "前方被阻挡,已停止");
|
||||
return halt();
|
||||
}
|
||||
|
||||
// 切换热键栏并同步给服务端(多人必须实时检测背包槽位)
|
||||
selectSlot(player, railSlot);
|
||||
|
||||
// 构造对下方地面的右键命中:命中点在地块上表面中心,面朝上
|
||||
BlockHitResult hit = new BlockHitResult(
|
||||
new Vec3d(railPos.getX() + 0.5, railPos.getY(), railPos.getZ() + 0.5),
|
||||
Direction.UP,
|
||||
railPos.down(),
|
||||
false
|
||||
);
|
||||
ctx.playerController().processRightClickBlock(player, world, Hand.MAIN_HAND, hit);
|
||||
|
||||
lastActionTick = now;
|
||||
return moveTo(railPos, now);
|
||||
}
|
||||
|
||||
/** 垫脚石:目标列下方悬空/太深,拿圆石右键侧面把缺口补上。 */
|
||||
private PathingCommand doBridge(IPlayerContext ctx, ClientPlayerEntity player, World world, Target target, long now) {
|
||||
int bridgeSlot = findSlot(player.getInventory(), Items.COBBLESTONE);
|
||||
if (bridgeSlot == -1) {
|
||||
stop();
|
||||
notify(player, "前方需要垫脚石,但背包里没有圆石,已停止");
|
||||
return halt();
|
||||
}
|
||||
|
||||
BlockHitResult hit = findBridgeHit(player, world);
|
||||
if (hit == null) {
|
||||
stop();
|
||||
notify(player, "无法确定垫脚石位置,已停止");
|
||||
return halt();
|
||||
}
|
||||
|
||||
selectSlot(player, bridgeSlot);
|
||||
ctx.playerController().processRightClickBlock(player, world, Hand.MAIN_HAND, hit);
|
||||
|
||||
lastActionTick = now;
|
||||
// 目标改为垫脚石的位置,让玩家先走到缺口边缘/补块上
|
||||
return moveTo(target.railPos.down(), now);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在玩家前方寻找一个可点击的实心方块侧面,把新方块垫进缺口。
|
||||
* 从远到近找 3 格内的实心方块,点击其朝前的那一面。
|
||||
*/
|
||||
private BlockHitResult findBridgeHit(ClientPlayerEntity player, World world) {
|
||||
double rad = Math.toRadians(player.getYaw());
|
||||
double dx = -Math.sin(rad);
|
||||
double dz = Math.cos(rad);
|
||||
Direction face = forwardDirection(dx, dz);
|
||||
int py = player.getBlockY();
|
||||
|
||||
for (int dist = 3; dist >= 1; dist--) {
|
||||
int ex = MathHelper.floor(player.getX() + dx * dist);
|
||||
int ez = MathHelper.floor(player.getZ() + dz * dist);
|
||||
for (int ey : new int[]{py - 1, py}) {
|
||||
BlockPos edge = new BlockPos(ex, ey, ez);
|
||||
if (isSolid(world, edge)) {
|
||||
Vec3d hitPos = new Vec3d(
|
||||
edge.getX() + 0.5 + face.getOffsetX() * 0.5,
|
||||
edge.getY() + 0.5 + face.getOffsetY() * 0.5,
|
||||
edge.getZ() + 0.5 + face.getOffsetZ() * 0.5);
|
||||
return new BlockHitResult(hitPos, face, edge, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算目标点:玩家前方 TARGET_DISTANCE 处(水平方向)的地面之上放铁轨的位置。
|
||||
* 返回 null 表示前方不可用;target.needBridge=true 表示该列下方悬空/过深。
|
||||
*/
|
||||
private Target computeTarget(ClientPlayerEntity player, World world) {
|
||||
double rad = Math.toRadians(player.getYaw());
|
||||
double dx = -Math.sin(rad);
|
||||
double dz = Math.cos(rad);
|
||||
|
||||
int tx = MathHelper.floor(player.getX() + dx * TARGET_DISTANCE);
|
||||
int tz = MathHelper.floor(player.getZ() + dz * TARGET_DISTANCE);
|
||||
int py = player.getBlockY();
|
||||
|
||||
int groundY = findGroundY(world, tx, tz, py + 1);
|
||||
if (groundY == Integer.MIN_VALUE || groundY < py - MAX_DROP) {
|
||||
// 悬空(虚空)或落差过大 -> 需要垫脚石
|
||||
return new Target(new BlockPos(tx, py, tz), true);
|
||||
}
|
||||
if (groundY > py + 2) {
|
||||
// 前方太高,一步上不去
|
||||
return null;
|
||||
}
|
||||
return new Target(new BlockPos(tx, groundY + 1, tz), false);
|
||||
}
|
||||
|
||||
private int findGroundY(World world, int x, int z, int startY) {
|
||||
int y = startY;
|
||||
while (y > world.getBottomY()) {
|
||||
if (isSolid(world, new BlockPos(x, y, z))) {
|
||||
return y;
|
||||
}
|
||||
y--;
|
||||
}
|
||||
return Integer.MIN_VALUE;
|
||||
}
|
||||
|
||||
/** 判定“实心可站立”的方块:非空气、非流体、不可被替换、且为实心。 */
|
||||
private boolean isSolid(World world, BlockPos pos) {
|
||||
BlockState state = world.getBlockState(pos);
|
||||
return !state.isAir()
|
||||
&& state.getFluidState().isEmpty()
|
||||
&& !state.isReplaceable()
|
||||
&& state.isSolidBlock(world, pos);
|
||||
}
|
||||
|
||||
private boolean hasArrived(ClientPlayerEntity player, GoalBlock goal, long now) {
|
||||
BlockPos feet = player.getBlockPos();
|
||||
int dx = Math.abs(feet.getX() - goal.x);
|
||||
int dz = Math.abs(feet.getZ() - goal.z);
|
||||
if (dx + dz <= 1) {
|
||||
return true;
|
||||
}
|
||||
return now - goalSetTick > FORCE_PROGRESS_TICKS;
|
||||
}
|
||||
|
||||
private PathingCommand moveTo(BlockPos pos, long now) {
|
||||
currentGoal = new GoalBlock(pos);
|
||||
goalSetTick = now;
|
||||
return new PathingCommand(currentGoal, PathingCommandType.CANCEL_AND_SET_GOAL);
|
||||
}
|
||||
|
||||
private PathingCommand defer() {
|
||||
return new PathingCommand(null, PathingCommandType.DEFER);
|
||||
}
|
||||
|
||||
/** 停止路径:CANCEL_AND_SET_GOAL + 空目标 = 取消寻路,让玩家停下。 */
|
||||
private PathingCommand halt() {
|
||||
return new PathingCommand(null, PathingCommandType.CANCEL_AND_SET_GOAL);
|
||||
}
|
||||
|
||||
/** 热键栏(前 9 格)查找指定物品。 */
|
||||
private int findSlot(PlayerInventory inventory, Item item) {
|
||||
for (int i = 0; i < 9; i++) {
|
||||
ItemStack stack = inventory.getStack(i);
|
||||
if (stack.isOf(item)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** 切换选中槽位,并同步 UpdateSelectedSlotC2S 包给服务端。 */
|
||||
private void selectSlot(ClientPlayerEntity player, int slot) {
|
||||
player.getInventory().selectedSlot = slot;
|
||||
if (player.networkHandler != null) {
|
||||
player.networkHandler.sendPacket(new UpdateSelectedSlotC2SPacket(slot));
|
||||
}
|
||||
}
|
||||
|
||||
/** 把水平朝向向量映射到最近的轴方向(用于垫脚石点击的面)。 */
|
||||
private Direction forwardDirection(double dx, double dz) {
|
||||
if (Math.abs(dx) > Math.abs(dz)) {
|
||||
return dx > 0 ? Direction.EAST : Direction.WEST;
|
||||
}
|
||||
return dz > 0 ? Direction.SOUTH : Direction.NORTH;
|
||||
}
|
||||
|
||||
private void notify(ClientPlayerEntity player, String message) {
|
||||
player.sendMessage(Text.literal("[AutoRail] " + message), false);
|
||||
}
|
||||
|
||||
/** 下一步动作的规划结果。 */
|
||||
private static final class Target {
|
||||
final BlockPos railPos; // 铁轨应放的位置;needBridge 时表示需要垫脚石的那一列
|
||||
final boolean needBridge; // 是否需要先垫脚石
|
||||
|
||||
Target(BlockPos railPos, boolean needBridge) {
|
||||
this.railPos = railPos;
|
||||
this.needBridge = needBridge;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"key.autorail.toggle": "Toggle Auto Rail",
|
||||
"category.autorail": "AutoRail"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"key.autorail.toggle": "切换自动铺轨",
|
||||
"category.autorail": "自动铺轨"
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "autorail",
|
||||
"version": "${version}",
|
||||
"name": "AutoRail",
|
||||
"description": "面向方向自动铺设铁轨(基于 Baritone API)。",
|
||||
"authors": [
|
||||
"AutoRail"
|
||||
],
|
||||
"license": "MIT",
|
||||
"environment": "client",
|
||||
"entrypoints": {
|
||||
"client": [
|
||||
"com.autorail.AutoRailClient"
|
||||
]
|
||||
},
|
||||
"depends": {
|
||||
"fabricloader": ">=0.16.9",
|
||||
"minecraft": "~1.21.4",
|
||||
"java": ">=21",
|
||||
"fabric-api": "*"
|
||||
},
|
||||
"suggests": {
|
||||
"baritone": "*"
|
||||
}
|
||||
}
|
||||
在新工单中引用
屏蔽一个用户