refactor: 移除 Baritone 依赖,改为内置 A* 寻路+自动行走铺轨
这个提交包含在:
@@ -1,39 +1,52 @@
|
|||||||
# AutoRail — 自动铺铁轨(Fabric 1.21.4 + Baritone API)
|
# AutoRail — 自动铺铁轨(Fabric 1.21.4,内置寻路)
|
||||||
|
|
||||||
面向方向自动铺设铁轨的 Minecraft 客户端模组。不依赖 Baritone 寻路来规划轨道——
|
按住 **R+T** 打开菜单,输入**起始点**、**目标点**和必经的**途径点**,模组用内置 A* 寻路
|
||||||
它只借 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 的版本)。
|
1. 安装 [Fabric Loader ≥0.16.9](https://fabricmc.net/use/) 与 [Fabric API](https://modrinth.com/mod/fabric-api),把 `autorail-<version>.jar` 放进 `mods/`。
|
||||||
2. 把 `autorail-<version>.jar` 放进 `mods/`。
|
2. 进世界后按住 **R+T** 打开菜单(先按 T 弹出聊天栏也会被菜单替换掉,正常现象)。
|
||||||
3. 进游戏后按 **R** 开启/关闭。背包里要有**铁轨**(垫脚石需要时还要有**圆石**)。
|
3. 起始点留空 = 当前坐标;目标点必填;途径点可添加多个(按顺序经过)。
|
||||||
4. 按住/调整视角方向→玩家会边走边往正前方铺直轨;手动转 90° 即可转弯(只铺直轨)。
|
坐标格式支持:`100 64 -200`(x y z)、`100 -200`(x z,自动找地面)、`~`、`~ 10 ~`、`~-5` 等相对写法。
|
||||||
5. 前方被阻挡、找不到地面、铁轨耗尽时自动停止并提示。
|
4. 点“开始铺轨”:先分片寻路(菜单/聊天栏显示进度,不卡游戏),完成后自动开始铺设(菜单自动关闭)。
|
||||||
|
5. 快捷栏需要**铁轨**;遇到悬空/水面会自动用**圆石**垫脚,没有则提示并停止。
|
||||||
|
6. 铺轨过程中不要打开聊天/背包等界面(行走会暂停);再按 R+T 可查看进度或点“停止”。
|
||||||
|
|
||||||
## 行为逻辑
|
## 内置寻路(A*)
|
||||||
|
|
||||||
- **取朝向**:读取玩家水平朝向(Yaw),计算正前方 2 格处的地面。
|
- 专为铁轨设计:4 向移动、允许 ±1 格坡度、禁止掉头、禁止“转弯+坡度”同格(原版没有斜弯轨)。
|
||||||
- **放置**:切换热键栏到铁轨并同步 `UpdateSelectedSlotC2S`,随后通过
|
- 每个节点校验:上方两格可通行(玩家沿线行走)、下方有实心支撑或可用圆石垫补、避开水面/岩浆。
|
||||||
`ClientPlayerInteractionManager`(Baritone 的 `IPlayerController`)发送右键放置——
|
- 转弯有额外代价(尽量走直线);已有铁轨可复用且有折扣,优先延伸既有线路。
|
||||||
**全程合法交互,绝不 `world.setBlockState`**,多人服务器才会承认。
|
- 分片执行(每 tick 限额展开 4096 节点);搜索范围限制在检查点包围盒外扩 48 格,总展开上限 40 万节点。
|
||||||
- **移动**:放置后设 `GoalBlock` 让玩家走到目标点,循环往复。
|
|
||||||
- **节奏**:每次动作间隔 5 tick(250ms),处于多人服务器建议的 200~300ms 区间。
|
## 铺设(合法交互)
|
||||||
- **垫脚石**:目标列下方悬空/落差超过 2 格时,先拿圆石右键垫补,再接铺铁轨(可选逻辑,已实现)。
|
|
||||||
- **铁轨朝向**:交给原版自动衔接(直轨)。转弯靠玩家手动转视角,开发量减半。
|
- 切换快捷栏 + `processRightClickBlock` 右键放置,**全程合法交互,绝不 `world.setBlockState`**,多人服务器可信任。
|
||||||
|
- 放置节奏 200ms 一次;放置前自动看向目标方块;上坡自动跳跃;卡住自动检测并停止报错。
|
||||||
|
- 行走只用客户端输入(前进/跳跃键 + 平滑转向),路径按“已铺设节点”推进,不会踩空。
|
||||||
|
|
||||||
|
## 代码结构
|
||||||
|
|
||||||
|
```text
|
||||||
|
com.autorail
|
||||||
|
├─ AutoRailClient # 入口:R+T 组合键 + 每 tick 驱动服务
|
||||||
|
├─ gui/AutoRailScreen # 菜单:起点/终点/途径点输入与状态显示
|
||||||
|
├─ service/AutoRailService # 状态机:PLANNING → LAYING → DONE/FAILED
|
||||||
|
├─ service/RailExecutor # 执行器:行走控制 + 合法放置铁轨/圆石
|
||||||
|
└─ pathing/ # 内置寻路:RailPathfinder(A*)、RailStep、CoordParser
|
||||||
|
```
|
||||||
|
|
||||||
## 开发
|
## 开发
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
gradlew build # 产物在 build/libs/autorall-<version>.jar
|
gradlew build # 产物在 build/libs/autorail-<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`),不支持动力铁轨/探测铁轨。
|
- 只铺普通铁轨(`minecraft:rail`),不铺动力铁轨/探测铁轨。
|
||||||
- 只铺直轨;曲线由原版在相邻铁轨存在时自动形成,手动转弯请让两段直线夹角足够清晰。
|
- 不破坏、不放置除铁轨/圆石外的方块:遇到障碍会绕路而不是挖穿。
|
||||||
- `isSolidBlock` 等判定基于客户端世界状态;服务器延误时可能出现个别放置失败,会自动重试。
|
- 起始点必须在玩家附近(水平 6 格、垂直 8 格以内)——本模组不含到远处的自由行走导航。
|
||||||
|
- 遇水会垫圆石架桥,但岩浆列直接视为不可通行。
|
||||||
|
- 基于客户端世界状态判定;服务器延迟时个别放置会失败,会自动重试。
|
||||||
|
|||||||
-2
@@ -19,8 +19,6 @@ dependencies {
|
|||||||
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
|
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
|
||||||
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
|
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
|
||||||
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
|
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
|
||||||
|
|
||||||
modImplementation files("libs/baritone-api-fabric-${project.baritone_version}.jar")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
processResources {
|
processResources {
|
||||||
|
|||||||
@@ -12,5 +12,3 @@ fabric_version=0.112.0+1.21.4
|
|||||||
mod_version=1.0.0
|
mod_version=1.0.0
|
||||||
maven_group=com.autorail
|
maven_group=com.autorail
|
||||||
archives_base_name=autorail
|
archives_base_name=autorail
|
||||||
|
|
||||||
baritone_version=1.13.1
|
|
||||||
|
|||||||
二进制文件未显示。
@@ -1,82 +1,46 @@
|
|||||||
package com.autorail;
|
package com.autorail;
|
||||||
|
|
||||||
import baritone.api.BaritoneAPI;
|
import com.autorail.gui.AutoRailScreen;
|
||||||
import com.autorail.process.RailProcess;
|
import com.autorail.service.AutoRailService;
|
||||||
import net.fabricmc.api.ClientModInitializer;
|
import net.fabricmc.api.ClientModInitializer;
|
||||||
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
|
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.MinecraftClient;
|
||||||
import net.minecraft.client.option.KeyBinding;
|
import net.minecraft.client.gui.screen.ChatScreen;
|
||||||
import net.minecraft.client.util.InputUtil;
|
import net.minecraft.client.util.InputUtil;
|
||||||
import net.minecraft.text.Text;
|
|
||||||
import org.lwjgl.glfw.GLFW;
|
import org.lwjgl.glfw.GLFW;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 入口:按住 R+T 打开铺轨菜单;每 tick 驱动调度服务(寻路 / 铺设)。
|
||||||
|
*/
|
||||||
public class AutoRailClient implements ClientModInitializer {
|
public class AutoRailClient implements ClientModInitializer {
|
||||||
|
|
||||||
public static final Logger LOGGER = LoggerFactory.getLogger("autorail");
|
public static final Logger LOGGER = LoggerFactory.getLogger("autorail");
|
||||||
public static final RailProcess RAIL_PROCESS = new RailProcess();
|
public static final AutoRailService SERVICE = new AutoRailService();
|
||||||
|
|
||||||
private static KeyBinding toggleKey;
|
private boolean comboHeld;
|
||||||
private static boolean registered = false;
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onInitializeClient() {
|
public void onInitializeClient() {
|
||||||
toggleKey = KeyBindingHelper.registerKeyBinding(new KeyBinding(
|
ClientTickEvents.END_CLIENT_TICK.register(this::onClientTick);
|
||||||
"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) {
|
private void onClientTick(MinecraftClient client) {
|
||||||
registerIfNeeded(client);
|
SERVICE.tick(client);
|
||||||
|
|
||||||
while (toggleKey.wasPressed()) {
|
if (client.player == null || client.world == null || client.getWindow() == null) {
|
||||||
if (client.player == null || client.world == null) {
|
comboHeld = false;
|
||||||
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;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
long window = client.getWindow().getHandle();
|
||||||
BaritoneAPI.getProvider().getPrimaryBaritone()
|
boolean combo = InputUtil.isKeyPressed(window, GLFW.GLFW_KEY_R)
|
||||||
.getPathingControlManager()
|
&& InputUtil.isKeyPressed(window, GLFW.GLFW_KEY_T);
|
||||||
.registerProcess(RAIL_PROCESS);
|
boolean edge = combo && !comboHeld;
|
||||||
registered = true;
|
comboHeld = combo;
|
||||||
LOGGER.info("AutoRail process registered");
|
// 允许覆盖聊天界面:先按 T 会弹出聊天栏,R+T 组合时直接换成菜单
|
||||||
} catch (Throwable t) {
|
if (edge && (client.currentScreen == null || client.currentScreen instanceof ChatScreen)) {
|
||||||
LOGGER.error("Failed to register AutoRail process", t);
|
client.setScreen(new AutoRailScreen());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
private static void sendMessage(MinecraftClient client, String message) {
|
|
||||||
if (client.player != null) {
|
|
||||||
client.player.sendMessage(Text.literal("[AutoRail] " + message), false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
package com.autorail.gui;
|
||||||
|
|
||||||
|
import com.autorail.AutoRailClient;
|
||||||
|
import com.autorail.pathing.CoordParser;
|
||||||
|
import com.autorail.service.AutoRailService;
|
||||||
|
import net.minecraft.client.gui.DrawContext;
|
||||||
|
import net.minecraft.client.gui.screen.Screen;
|
||||||
|
import net.minecraft.client.gui.widget.ButtonWidget;
|
||||||
|
import net.minecraft.client.gui.widget.TextFieldWidget;
|
||||||
|
import net.minecraft.text.Text;
|
||||||
|
import net.minecraft.util.math.BlockPos;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自动铺轨菜单:输入起始点、目标点与若干必经途径点,
|
||||||
|
* 点击“开始铺轨”后由 {@link AutoRailService} 先寻路再自动铺设。
|
||||||
|
*/
|
||||||
|
public class AutoRailScreen extends Screen {
|
||||||
|
|
||||||
|
private static final int MAX_WAYPOINTS = 8;
|
||||||
|
private static final int FIELD_W = 220;
|
||||||
|
private static final int FIELD_H = 18;
|
||||||
|
private static final int ROW_STEP = 22;
|
||||||
|
|
||||||
|
private TextFieldWidget startField;
|
||||||
|
private TextFieldWidget destField;
|
||||||
|
private final List<TextFieldWidget> waypointFields = new ArrayList<>();
|
||||||
|
private ButtonWidget beginBtn;
|
||||||
|
private ButtonWidget stopBtn;
|
||||||
|
private ButtonWidget addBtn;
|
||||||
|
|
||||||
|
private String startText = "";
|
||||||
|
private String destText = "";
|
||||||
|
private final List<String> waypointTexts = new ArrayList<>();
|
||||||
|
private Text error;
|
||||||
|
private AutoRailService.State prevState;
|
||||||
|
private int maxVisible;
|
||||||
|
|
||||||
|
// 布局锚点(init 时计算,render 用来画标签)
|
||||||
|
private int startY, destY, wpLabelY, rowsY, addY, btnY, statusY, hintY;
|
||||||
|
|
||||||
|
public AutoRailScreen() {
|
||||||
|
super(Text.translatable("autorail.gui.title"));
|
||||||
|
prevState = AutoRailClient.SERVICE.getState();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void init() {
|
||||||
|
waypointFields.clear();
|
||||||
|
int cx = this.width / 2;
|
||||||
|
int left = cx - FIELD_W / 2;
|
||||||
|
|
||||||
|
startY = 44;
|
||||||
|
startField = addDrawableChild(makeField(left, startY, "autorail.gui.start", "autorail.gui.start.ph"));
|
||||||
|
startField.setText(startText);
|
||||||
|
|
||||||
|
destY = startY + ROW_STEP + 6;
|
||||||
|
destField = addDrawableChild(makeField(left, destY, "autorail.gui.dest", "autorail.gui.dest.ph"));
|
||||||
|
destField.setText(destText);
|
||||||
|
|
||||||
|
wpLabelY = destY + ROW_STEP + 6;
|
||||||
|
rowsY = wpLabelY + 12;
|
||||||
|
maxVisible = Math.max(1, Math.min(MAX_WAYPOINTS, (this.height - rowsY - 130) / ROW_STEP));
|
||||||
|
|
||||||
|
int ry = rowsY;
|
||||||
|
List<String> texts = new ArrayList<>(
|
||||||
|
waypointTexts.size() > maxVisible ? waypointTexts.subList(0, maxVisible) : waypointTexts);
|
||||||
|
for (String t : texts) {
|
||||||
|
TextFieldWidget f = addDrawableChild(makeField(left, ry, "autorail.gui.waypoints", "autorail.gui.wp.ph"));
|
||||||
|
f.setText(t);
|
||||||
|
waypointFields.add(f);
|
||||||
|
int idx = waypointFields.size() - 1;
|
||||||
|
addDrawableChild(ButtonWidget.builder(Text.translatable("autorail.gui.remove"), b -> {
|
||||||
|
saveTexts();
|
||||||
|
if (idx < waypointTexts.size()) {
|
||||||
|
waypointTexts.remove(idx);
|
||||||
|
}
|
||||||
|
clearAndInit();
|
||||||
|
}).dimensions(left + FIELD_W - 20, ry, 20, FIELD_H).build());
|
||||||
|
ry += ROW_STEP;
|
||||||
|
}
|
||||||
|
|
||||||
|
addY = ry + 2;
|
||||||
|
addBtn = addDrawableChild(ButtonWidget.builder(Text.translatable("autorail.gui.add"), b -> {
|
||||||
|
saveTexts();
|
||||||
|
waypointTexts.add("");
|
||||||
|
clearAndInit();
|
||||||
|
}).dimensions(left, addY, 130, FIELD_H).build());
|
||||||
|
|
||||||
|
btnY = this.height - 52;
|
||||||
|
beginBtn = addDrawableChild(ButtonWidget.builder(Text.translatable("autorail.gui.begin"), b -> onBegin())
|
||||||
|
.dimensions(cx - 141, btnY, 90, 20).build());
|
||||||
|
stopBtn = addDrawableChild(ButtonWidget.builder(Text.translatable("autorail.gui.stop"), b -> {
|
||||||
|
AutoRailClient.SERVICE.stop(this.client == null ? null : this.client.player);
|
||||||
|
}).dimensions(cx - 45, btnY, 90, 20).build());
|
||||||
|
addDrawableChild(ButtonWidget.builder(Text.translatable("autorail.gui.close"), b -> close())
|
||||||
|
.dimensions(cx + 51, btnY, 90, 20).build());
|
||||||
|
|
||||||
|
statusY = this.height - 30;
|
||||||
|
hintY = this.height - 18;
|
||||||
|
}
|
||||||
|
|
||||||
|
private TextFieldWidget makeField(int x, int y, String labelKey, String placeholderKey) {
|
||||||
|
TextFieldWidget f = new TextFieldWidget(this.textRenderer, x, y, FIELD_W, FIELD_H,
|
||||||
|
Text.translatable(labelKey));
|
||||||
|
f.setMaxLength(48);
|
||||||
|
f.setPlaceholder(Text.translatable(placeholderKey));
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void tick() {
|
||||||
|
saveTexts();
|
||||||
|
AutoRailService s = AutoRailClient.SERVICE;
|
||||||
|
AutoRailService.State st = s.getState();
|
||||||
|
beginBtn.active = st == AutoRailService.State.IDLE
|
||||||
|
|| st == AutoRailService.State.FAILED
|
||||||
|
|| st == AutoRailService.State.DONE;
|
||||||
|
stopBtn.active = st == AutoRailService.State.PLANNING || st == AutoRailService.State.LAYING;
|
||||||
|
addBtn.active = waypointTexts.size() < Math.min(MAX_WAYPOINTS, Math.max(1, maxVisible));
|
||||||
|
// 寻路完成进入铺设时自动关闭界面(行走需要关闭界面)
|
||||||
|
if (prevState == AutoRailService.State.PLANNING && st == AutoRailService.State.LAYING) {
|
||||||
|
this.client.setScreen(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
prevState = st;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void onBegin() {
|
||||||
|
saveTexts();
|
||||||
|
error = null;
|
||||||
|
if (this.client == null || this.client.player == null || this.client.world == null) {
|
||||||
|
error = Text.translatable("autorail.err.needWorld");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var player = this.client.player;
|
||||||
|
var world = this.client.world;
|
||||||
|
try {
|
||||||
|
BlockPos start = CoordParser.parse(startText.isBlank() ? "~" : startText, player, world);
|
||||||
|
double dx = start.getX() - player.getBlockX();
|
||||||
|
double dz = start.getZ() - player.getBlockZ();
|
||||||
|
if (dx * dx + dz * dz > 36 || Math.abs(start.getY() - player.getBlockY()) > 8) {
|
||||||
|
error = Text.translatable("autorail.err.startFar");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
BlockPos dest = CoordParser.parse(destText, player, world);
|
||||||
|
List<BlockPos> cps = new ArrayList<>();
|
||||||
|
cps.add(start);
|
||||||
|
for (String t : waypointTexts) {
|
||||||
|
if (!t.isBlank()) {
|
||||||
|
cps.add(CoordParser.parse(t, player, world));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cps.add(dest);
|
||||||
|
List<BlockPos> dedup = new ArrayList<>();
|
||||||
|
for (BlockPos c : cps) {
|
||||||
|
if (dedup.isEmpty() || !dedup.get(dedup.size() - 1).equals(c)) {
|
||||||
|
dedup.add(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (dedup.size() < 2) {
|
||||||
|
error = Text.translatable("autorail.err.startEqDest");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
AutoRailClient.SERVICE.begin(world, player, dedup);
|
||||||
|
prevState = AutoRailClient.SERVICE.getState();
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
error = Text.translatable(e.getMessage() == null ? "autorail.err.coordFormat" : e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveTexts() {
|
||||||
|
if (startField != null) {
|
||||||
|
startText = startField.getText();
|
||||||
|
}
|
||||||
|
if (destField != null) {
|
||||||
|
destText = destField.getText();
|
||||||
|
}
|
||||||
|
// 只用可见字段更新对应前若干项;保留因窗口变小而未显示的尾部条目,避免丢失途径点
|
||||||
|
int visible = waypointFields.size();
|
||||||
|
List<String> tail = waypointTexts.size() > visible
|
||||||
|
? new ArrayList<>(waypointTexts.subList(visible, waypointTexts.size()))
|
||||||
|
: List.of();
|
||||||
|
waypointTexts.clear();
|
||||||
|
for (TextFieldWidget f : waypointFields) {
|
||||||
|
waypointTexts.add(f.getText());
|
||||||
|
}
|
||||||
|
waypointTexts.addAll(tail);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void removed() {
|
||||||
|
saveTexts();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
|
||||||
|
super.render(context, mouseX, mouseY, delta);
|
||||||
|
int cx = this.width / 2;
|
||||||
|
int left = cx - FIELD_W / 2;
|
||||||
|
context.drawCenteredTextWithShadow(this.textRenderer, this.title, cx, 16, 0xFFFFFF);
|
||||||
|
context.drawCenteredTextWithShadow(this.textRenderer,
|
||||||
|
Text.translatable("autorail.gui.hint"), cx, 28, 0xA0A0A0);
|
||||||
|
int labelColor = 0xE0E0E0;
|
||||||
|
context.drawTextWithShadow(this.textRenderer,
|
||||||
|
Text.translatable("autorail.gui.start"), left, startY - 11, labelColor);
|
||||||
|
context.drawTextWithShadow(this.textRenderer,
|
||||||
|
Text.translatable("autorail.gui.dest"), left, destY - 11, labelColor);
|
||||||
|
context.drawTextWithShadow(this.textRenderer,
|
||||||
|
Text.translatable("autorail.gui.waypoints"), left, wpLabelY, labelColor);
|
||||||
|
Text st = error != null ? error : AutoRailClient.SERVICE.statusText();
|
||||||
|
context.drawCenteredTextWithShadow(this.textRenderer, st, cx, statusY,
|
||||||
|
error != null ? 0xFF5555 : 0x55FF55);
|
||||||
|
if (AutoRailClient.SERVICE.getState() == AutoRailService.State.LAYING) {
|
||||||
|
context.drawCenteredTextWithShadow(this.textRenderer,
|
||||||
|
Text.translatable("autorail.gui.hint.laying"), cx, hintY, 0xFFAA00);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean shouldPause() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package com.autorail.pathing;
|
||||||
|
|
||||||
|
import net.minecraft.block.BlockState;
|
||||||
|
import net.minecraft.client.network.ClientPlayerEntity;
|
||||||
|
import net.minecraft.client.world.ClientWorld;
|
||||||
|
import net.minecraft.util.math.BlockPos;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 坐标解析:支持 "x y z"、"x z"(自动找地面)、"~" 与 "~±n" 相对玩家。
|
||||||
|
* 解析失败抛 {@link IllegalArgumentException},消息为语言 key。
|
||||||
|
*/
|
||||||
|
public final class CoordParser {
|
||||||
|
|
||||||
|
private CoordParser() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BlockPos parse(String raw, ClientPlayerEntity player, ClientWorld world) {
|
||||||
|
if (raw == null || raw.isBlank()) {
|
||||||
|
throw err("autorail.err.emptyCoord");
|
||||||
|
}
|
||||||
|
String[] parts = raw.trim().split("[,;\\s]+");
|
||||||
|
if (parts.length != 2 && parts.length != 3) {
|
||||||
|
throw err("autorail.err.coordFormat");
|
||||||
|
}
|
||||||
|
// 两段式:x z(y 自动);三段式:x y z
|
||||||
|
int[] v = new int[parts.length];
|
||||||
|
for (int i = 0; i < parts.length; i++) {
|
||||||
|
int axis = parts.length == 3 ? i : (i == 0 ? 0 : 2);
|
||||||
|
v[i] = part(parts[i], player, axis);
|
||||||
|
}
|
||||||
|
if (parts.length == 3) {
|
||||||
|
return new BlockPos(v[0], v[1], v[2]);
|
||||||
|
}
|
||||||
|
int y = findSurfaceY(world, v[0], v[1]);
|
||||||
|
if (y == Integer.MIN_VALUE) {
|
||||||
|
throw err("autorail.err.noGround");
|
||||||
|
}
|
||||||
|
return new BlockPos(v[0], y, v[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IllegalArgumentException err(String key) {
|
||||||
|
return new IllegalArgumentException(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解析单个分量:纯数字,或 ~/~n/~+n/~-n 相对玩家坐标。 */
|
||||||
|
private static int part(String s, ClientPlayerEntity player, int axis) {
|
||||||
|
int base = switch (axis) {
|
||||||
|
case 0 -> player.getBlockX();
|
||||||
|
case 1 -> player.getBlockY();
|
||||||
|
default -> player.getBlockZ();
|
||||||
|
};
|
||||||
|
if (s.equals("~")) {
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
if (s.startsWith("~")) {
|
||||||
|
try {
|
||||||
|
return base + Integer.parseInt(s.substring(1));
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
throw err("autorail.err.coordFormat");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(s);
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
throw err("autorail.err.coordFormat");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从上往下找该列第一个“上方两格可通行”的实心地面,
|
||||||
|
* 返回铁轨可放置的 Y(地面 + 1)。找不到返回 Integer.MIN_VALUE。
|
||||||
|
*/
|
||||||
|
public static int findSurfaceY(ClientWorld world, int x, int z) {
|
||||||
|
for (int y = world.getTopYInclusive() - 2; y > world.getBottomY() + 1; y--) {
|
||||||
|
BlockPos ground = new BlockPos(x, y, z);
|
||||||
|
BlockState g = world.getBlockState(ground);
|
||||||
|
if (g.isAir() || g.isReplaceable() || !g.getFluidState().isEmpty()
|
||||||
|
|| !g.isSolidBlock(world, ground)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (passable(world, ground.up()) && passable(world, ground.up(2))) {
|
||||||
|
return y + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Integer.MIN_VALUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 可通行(放置/行走高度):空气或无流体的可替换方块(如矮草)。 */
|
||||||
|
public static boolean passable(ClientWorld world, BlockPos pos) {
|
||||||
|
BlockState s = world.getBlockState(pos);
|
||||||
|
return s.isAir() || (s.getFluidState().isEmpty() && s.isReplaceable());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
package com.autorail.pathing;
|
||||||
|
|
||||||
|
import net.minecraft.block.BlockState;
|
||||||
|
import net.minecraft.block.Blocks;
|
||||||
|
import net.minecraft.client.world.ClientWorld;
|
||||||
|
import net.minecraft.registry.tag.FluidTags;
|
||||||
|
import net.minecraft.util.math.BlockPos;
|
||||||
|
import net.minecraft.util.math.Direction;
|
||||||
|
|
||||||
|
import java.util.ArrayDeque;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.PriorityQueue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 内置 A* 铁轨寻路(不依赖任何外部寻路模组)。
|
||||||
|
*
|
||||||
|
* 节点 = 铁轨位置 + 进入方向。搜索规则与原版铁轨形状一致:
|
||||||
|
* - 仅 4 向水平移动,禁止 180° 掉头;
|
||||||
|
* - 相邻节点允许 ±1 格坡度,但“转弯 + 坡度”不能发生在同一格(原版没有斜弯轨);
|
||||||
|
* - 每个节点校验:铁轨位为空气/可替换/已有铁轨,上方两格可通行(玩家要沿线走),
|
||||||
|
* 下方有实心支撑(或空气/水——可用圆石垫补,岩浆直接视为不可通行);
|
||||||
|
* - 转弯有额外代价,倾向走直线;已有铁轨可复用且有折扣,优先延伸既有线路。
|
||||||
|
*
|
||||||
|
* 通过 {@link #step(int)} 分片执行(每帧限额展开),不会卡住客户端线程。
|
||||||
|
* 多个检查点(途径点)会被拆成多段依次寻路并拼接。
|
||||||
|
*/
|
||||||
|
public class RailPathfinder {
|
||||||
|
|
||||||
|
public enum State { RUNNING, FOUND, FAILED }
|
||||||
|
|
||||||
|
private static final float COST_TURN = 0.6f;
|
||||||
|
private static final float COST_UP = 1.0f;
|
||||||
|
private static final float COST_DOWN = 0.5f;
|
||||||
|
private static final float COST_SUPPORT = 2.0f;
|
||||||
|
private static final float DISCOUNT_RAIL = 0.5f;
|
||||||
|
/** 搜索区域在检查点包围盒基础上的外扩余量(格)。 */
|
||||||
|
private static final int MARGIN = 48;
|
||||||
|
private static final long MAX_EXPANSIONS = 400_000L;
|
||||||
|
|
||||||
|
private final ClientWorld world;
|
||||||
|
private final ArrayDeque<BlockPos> pending = new ArrayDeque<>();
|
||||||
|
private final List<RailStep> result = new ArrayList<>();
|
||||||
|
|
||||||
|
private State state = State.RUNNING;
|
||||||
|
private String failKey;
|
||||||
|
|
||||||
|
private BlockPos segStart;
|
||||||
|
private BlockPos segGoal;
|
||||||
|
private final PriorityQueue<Node> open = new PriorityQueue<>(Comparator.comparingDouble(n -> n.f));
|
||||||
|
private final Map<NodeKey, Node> best = new HashMap<>();
|
||||||
|
private long expansions;
|
||||||
|
private int opened;
|
||||||
|
|
||||||
|
public RailPathfinder(ClientWorld world, List<BlockPos> checkpoints) {
|
||||||
|
if (checkpoints == null || checkpoints.size() < 2) {
|
||||||
|
throw new IllegalArgumentException("autorail.err.startEqDest");
|
||||||
|
}
|
||||||
|
this.world = world;
|
||||||
|
this.segStart = checkpoints.get(0);
|
||||||
|
for (int i = 1; i < checkpoints.size(); i++) {
|
||||||
|
this.pending.add(checkpoints.get(i));
|
||||||
|
}
|
||||||
|
advanceSegment();
|
||||||
|
}
|
||||||
|
|
||||||
|
public State getState() {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFailKey() {
|
||||||
|
return failKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<RailStep> getResult() {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getOpened() {
|
||||||
|
return opened;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 每帧调用一次,最多展开 budget 个节点。 */
|
||||||
|
public void step(int budget) {
|
||||||
|
if (state != State.RUNNING) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (int b = 0; b < budget; b++) {
|
||||||
|
Node cur = poll();
|
||||||
|
if (cur == null) {
|
||||||
|
fail("autorail.err.pathNotFound");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (cur.pos.equals(segGoal)) {
|
||||||
|
appendSegment(cur);
|
||||||
|
segStart = segGoal;
|
||||||
|
advanceSegment();
|
||||||
|
if (state != State.RUNNING) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
expand(cur);
|
||||||
|
if (++expansions > MAX_EXPANSIONS) {
|
||||||
|
fail("autorail.err.tooFar");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取出优先队列中第一个未过期(仍为该 key 最优)的节点。 */
|
||||||
|
private Node poll() {
|
||||||
|
while (true) {
|
||||||
|
Node n = open.poll();
|
||||||
|
if (n == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (best.get(n.key) == n) {
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void expand(Node cur) {
|
||||||
|
Direction in = cur.dir == NULL_DIR ? null : Direction.byId(cur.dir);
|
||||||
|
for (Direction d : Direction.Type.HORIZONTAL) {
|
||||||
|
if (in != null && d == in.getOpposite()) {
|
||||||
|
continue; // 禁止掉头
|
||||||
|
}
|
||||||
|
boolean turn = in != null && d != in;
|
||||||
|
int[] dys = turn ? new int[]{0} : new int[]{0, 1, -1};
|
||||||
|
for (int dy : dys) {
|
||||||
|
BlockPos next = cur.pos.offset(d).up(dy);
|
||||||
|
if (!inRegion(next)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int sup = checkNode(next);
|
||||||
|
if (sup < 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
float cost = 1.0f;
|
||||||
|
if (dy == 1) {
|
||||||
|
cost += COST_UP;
|
||||||
|
} else if (dy == -1) {
|
||||||
|
cost += COST_DOWN;
|
||||||
|
}
|
||||||
|
if (sup == SUPPORT_BRIDGE) {
|
||||||
|
cost += COST_SUPPORT;
|
||||||
|
} else if (sup == SUPPORT_RAIL) {
|
||||||
|
cost -= DISCOUNT_RAIL;
|
||||||
|
}
|
||||||
|
if (turn) {
|
||||||
|
cost += COST_TURN;
|
||||||
|
}
|
||||||
|
float g = cur.g + cost;
|
||||||
|
NodeKey key = new NodeKey(next.asLong(), (byte) d.getId());
|
||||||
|
Node old = best.get(key);
|
||||||
|
if (old == null || g < old.g - 1.0e-4f) {
|
||||||
|
Node n = new Node(key, next, (byte) d.getId(), cur, g, g + h(next));
|
||||||
|
best.put(key, n);
|
||||||
|
open.add(n);
|
||||||
|
opened++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final byte NULL_DIR = -1;
|
||||||
|
private static final int SUPPORT_GROUND = 0;
|
||||||
|
private static final int SUPPORT_BRIDGE = 1;
|
||||||
|
private static final int SUPPORT_RAIL = 2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验某位置能否作为铁轨节点。
|
||||||
|
*
|
||||||
|
* @return -1 不可用;0 天然支撑;1 需垫圆石;2 已有铁轨可复用
|
||||||
|
*/
|
||||||
|
public int checkNode(BlockPos rail) {
|
||||||
|
BlockState rs = world.getBlockState(rail);
|
||||||
|
if (rs.isOf(Blocks.RAIL)) {
|
||||||
|
return CoordParser.passable(world, rail.up()) && CoordParser.passable(world, rail.up(2))
|
||||||
|
? SUPPORT_RAIL : -1;
|
||||||
|
}
|
||||||
|
if (!(rs.isAir() || (rs.getFluidState().isEmpty() && rs.isReplaceable()))) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
if (!CoordParser.passable(world, rail.up()) || !CoordParser.passable(world, rail.up(2))) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
BlockState sup = world.getBlockState(rail.down());
|
||||||
|
if (sup.getFluidState().isIn(FluidTags.LAVA)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
if (sup.getFluidState().isIn(FluidTags.WATER) || sup.isAir()) {
|
||||||
|
return SUPPORT_BRIDGE;
|
||||||
|
}
|
||||||
|
if (sup.isReplaceable()) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return sup.isSolidBlock(world, rail.down()) ? SUPPORT_GROUND : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void appendSegment(Node goal) {
|
||||||
|
ArrayDeque<RailStep> stack = new ArrayDeque<>();
|
||||||
|
for (Node n = goal; n != null; n = n.parent) {
|
||||||
|
Direction d = n.dir == NULL_DIR ? null : Direction.byId(n.dir);
|
||||||
|
stack.push(new RailStep(n.pos, d));
|
||||||
|
}
|
||||||
|
// 后续段的首节点与上一段终点重复,跳过一个
|
||||||
|
int skip = result.isEmpty() ? 0 : 1;
|
||||||
|
int i = 0;
|
||||||
|
while (!stack.isEmpty()) {
|
||||||
|
RailStep s = stack.pollFirst();
|
||||||
|
if (i++ >= skip) {
|
||||||
|
result.add(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void advanceSegment() {
|
||||||
|
while (!pending.isEmpty() && pending.peekFirst().equals(segStart)) {
|
||||||
|
pending.pollFirst();
|
||||||
|
}
|
||||||
|
if (pending.isEmpty()) {
|
||||||
|
state = State.FOUND;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
segGoal = pending.pollFirst();
|
||||||
|
open.clear();
|
||||||
|
best.clear();
|
||||||
|
computeRegion();
|
||||||
|
if (checkNode(segStart) < 0) {
|
||||||
|
fail("autorail.err.startInvalid");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Node start = new Node(new NodeKey(segStart.asLong(), NULL_DIR), segStart, NULL_DIR, null, 0f, h(segStart));
|
||||||
|
best.put(start.key, start);
|
||||||
|
open.add(start);
|
||||||
|
opened++;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int minX, minY, minZ, maxX, maxY, maxZ;
|
||||||
|
|
||||||
|
private void computeRegion() {
|
||||||
|
minX = Math.min(segStart.getX(), segGoal.getX()) - MARGIN;
|
||||||
|
maxX = Math.max(segStart.getX(), segGoal.getX()) + MARGIN;
|
||||||
|
minZ = Math.min(segStart.getZ(), segGoal.getZ()) - MARGIN;
|
||||||
|
maxZ = Math.max(segStart.getZ(), segGoal.getZ()) + MARGIN;
|
||||||
|
minY = Math.max(world.getBottomY() + 1, Math.min(segStart.getY(), segGoal.getY()) - MARGIN);
|
||||||
|
maxY = Math.min(world.getTopYInclusive() - 3, Math.max(segStart.getY(), segGoal.getY()) + MARGIN);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean inRegion(BlockPos p) {
|
||||||
|
return p.getX() >= minX && p.getX() <= maxX
|
||||||
|
&& p.getY() >= minY && p.getY() <= maxY
|
||||||
|
&& p.getZ() >= minZ && p.getZ() <= maxZ;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 曼哈顿距离 × 0.5,保证在有铁轨复用折扣时仍不高估。 */
|
||||||
|
private float h(BlockPos p) {
|
||||||
|
return 0.5f * (Math.abs(p.getX() - segGoal.getX())
|
||||||
|
+ Math.abs(p.getY() - segGoal.getY())
|
||||||
|
+ Math.abs(p.getZ() - segGoal.getZ()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fail(String key) {
|
||||||
|
failKey = key;
|
||||||
|
state = State.FAILED;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Node {
|
||||||
|
final NodeKey key;
|
||||||
|
final BlockPos pos;
|
||||||
|
final byte dir;
|
||||||
|
final Node parent;
|
||||||
|
final float g;
|
||||||
|
final float f;
|
||||||
|
|
||||||
|
Node(NodeKey key, BlockPos pos, byte dir, Node parent, float g, float f) {
|
||||||
|
this.key = key;
|
||||||
|
this.pos = pos;
|
||||||
|
this.dir = dir;
|
||||||
|
this.parent = parent;
|
||||||
|
this.g = g;
|
||||||
|
this.f = f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private record NodeKey(long pos, byte dir) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.autorail.pathing;
|
||||||
|
|
||||||
|
import net.minecraft.util.math.BlockPos;
|
||||||
|
import net.minecraft.util.math.Direction;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 规划路径上的一个铁轨节点。
|
||||||
|
*
|
||||||
|
* @param railPos 铁轨应放置的位置(其下方一格为支撑方块)
|
||||||
|
* @param dir 进入该节点的行进方向(整条路径的首节点为 null)
|
||||||
|
*/
|
||||||
|
public record RailStep(BlockPos railPos, Direction dir) {
|
||||||
|
}
|
||||||
@@ -1,330 +0,0 @@
|
|||||||
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,118 @@
|
|||||||
|
package com.autorail.service;
|
||||||
|
|
||||||
|
import com.autorail.pathing.RailPathfinder;
|
||||||
|
import com.autorail.pathing.RailStep;
|
||||||
|
import net.minecraft.client.MinecraftClient;
|
||||||
|
import net.minecraft.client.network.ClientPlayerEntity;
|
||||||
|
import net.minecraft.client.world.ClientWorld;
|
||||||
|
import net.minecraft.text.Text;
|
||||||
|
import net.minecraft.util.math.BlockPos;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 铺轨调度服务(单例,GUI 与执行逻辑的桥梁)。
|
||||||
|
* 状态机:PLANNING(分片寻路)→ LAYING(行走铺轨)→ DONE / FAILED。
|
||||||
|
*/
|
||||||
|
public class AutoRailService {
|
||||||
|
|
||||||
|
public enum State { IDLE, PLANNING, LAYING, DONE, FAILED }
|
||||||
|
|
||||||
|
/** 每 tick 寻路展开预算(节点数)。 */
|
||||||
|
private static final int PLAN_BUDGET_PER_TICK = 4096;
|
||||||
|
|
||||||
|
private State state = State.IDLE;
|
||||||
|
private RailPathfinder planner;
|
||||||
|
private RailExecutor executor;
|
||||||
|
private String failKey;
|
||||||
|
|
||||||
|
public State getState() {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void begin(ClientWorld world, ClientPlayerEntity player, List<BlockPos> checkpoints) {
|
||||||
|
planner = new RailPathfinder(world, checkpoints);
|
||||||
|
executor = null;
|
||||||
|
failKey = null;
|
||||||
|
state = State.PLANNING;
|
||||||
|
chat(player, "autorail.msg.plan.start", checkpoints.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void stop(ClientPlayerEntity player) {
|
||||||
|
if (executor != null) {
|
||||||
|
executor.releaseKeys();
|
||||||
|
}
|
||||||
|
boolean wasActive = state == State.PLANNING || state == State.LAYING;
|
||||||
|
planner = null;
|
||||||
|
executor = null;
|
||||||
|
state = State.IDLE;
|
||||||
|
if (wasActive && player != null) {
|
||||||
|
chat(player, "autorail.msg.stopped");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void tick(MinecraftClient client) {
|
||||||
|
if (state != State.PLANNING && state != State.LAYING) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ClientPlayerEntity player = client.player;
|
||||||
|
ClientWorld world = client.world;
|
||||||
|
if (player == null || world == null) {
|
||||||
|
hardStop();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (state == State.PLANNING) {
|
||||||
|
planner.step(PLAN_BUDGET_PER_TICK);
|
||||||
|
if (planner.getState() == RailPathfinder.State.FOUND) {
|
||||||
|
List<RailStep> steps = planner.getResult();
|
||||||
|
executor = new RailExecutor(world, steps);
|
||||||
|
state = State.LAYING;
|
||||||
|
chat(player, "autorail.msg.plan.done", steps.size());
|
||||||
|
} else if (planner.getState() == RailPathfinder.State.FAILED) {
|
||||||
|
failKey = planner.getFailKey();
|
||||||
|
state = State.FAILED;
|
||||||
|
chat(player, failKey);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
executor.tick(client);
|
||||||
|
if (executor.isFinished()) {
|
||||||
|
if (executor.getFailKey() != null) {
|
||||||
|
failKey = executor.getFailKey();
|
||||||
|
state = State.FAILED;
|
||||||
|
chat(player, failKey);
|
||||||
|
} else {
|
||||||
|
state = State.DONE;
|
||||||
|
chat(player, "autorail.msg.lay.done", executor.getTotal());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void hardStop() {
|
||||||
|
if (executor != null) {
|
||||||
|
executor.releaseKeys();
|
||||||
|
}
|
||||||
|
planner = null;
|
||||||
|
executor = null;
|
||||||
|
state = State.IDLE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GUI 底部状态行。 */
|
||||||
|
public Text statusText() {
|
||||||
|
return switch (state) {
|
||||||
|
case IDLE -> Text.translatable("autorail.gui.status.idle");
|
||||||
|
case PLANNING -> Text.translatable("autorail.gui.status.planning",
|
||||||
|
planner == null ? 0 : planner.getOpened());
|
||||||
|
case LAYING -> executor == null ? Text.translatable("autorail.gui.status.idle")
|
||||||
|
: Text.translatable("autorail.gui.status.laying", executor.getPlaced(), executor.getTotal());
|
||||||
|
case DONE -> executor == null ? Text.translatable("autorail.gui.status.idle")
|
||||||
|
: Text.translatable("autorail.gui.status.done", executor.getTotal());
|
||||||
|
case FAILED -> Text.translatable("autorail.gui.status.failed",
|
||||||
|
Text.translatable(failKey == null ? "autorail.err.pathNotFound" : failKey));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void chat(ClientPlayerEntity player, String key, Object... args) {
|
||||||
|
player.sendMessage(Text.literal("[AutoRail] ").append(Text.translatable(key, args)), false);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,362 @@
|
|||||||
|
package com.autorail.service;
|
||||||
|
|
||||||
|
import com.autorail.pathing.RailStep;
|
||||||
|
import net.minecraft.block.BlockState;
|
||||||
|
import net.minecraft.block.Blocks;
|
||||||
|
import net.minecraft.client.MinecraftClient;
|
||||||
|
import net.minecraft.client.network.ClientPlayerEntity;
|
||||||
|
import net.minecraft.client.world.ClientWorld;
|
||||||
|
import net.minecraft.item.Items;
|
||||||
|
import net.minecraft.network.packet.c2s.play.UpdateSelectedSlotC2SPacket;
|
||||||
|
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 java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 铺轨执行器:沿已规划好的路径控制玩家行走,并合法放置铁轨/圆石。
|
||||||
|
*
|
||||||
|
* 行走:平滑转向 + 按下前进/跳跃键(客户端输入,服务端正常结算);
|
||||||
|
* 放置:切换快捷栏 + {@code processRightClickBlock} 右键交互,
|
||||||
|
* 绝不 world.setBlockState,多人服务器可信任。
|
||||||
|
* 玩家只会走在“已完成”的节点上,放置窗口始终领先于行走目标。
|
||||||
|
*/
|
||||||
|
public class RailExecutor {
|
||||||
|
|
||||||
|
/** 放置动作间隔(tick),4 tick = 200ms,符合多人服务器节奏。 */
|
||||||
|
private static final int ACTION_INTERVAL = 4;
|
||||||
|
/** 放置距离的平方(略保守于 4.5 格交互距离)。 */
|
||||||
|
private static final double REACH_SQ = 4.2 * 4.2;
|
||||||
|
/** 一次尝试放置的路径窗口(节点数)。 */
|
||||||
|
private static final int PLACE_WINDOW = 4;
|
||||||
|
/** 行走目标领先玩家所在节点的格数。 */
|
||||||
|
private static final int WALK_AHEAD = 2;
|
||||||
|
/** 原地卡住判定(tick)。 */
|
||||||
|
private static final int STUCK_FAIL_TICKS = 120;
|
||||||
|
/** 总进度停滞判定(tick)。 */
|
||||||
|
private static final int STALL_FAIL_TICKS = 300;
|
||||||
|
/** 每 tick 最大转角(度)。 */
|
||||||
|
private static final float MAX_TURN_PER_TICK = 60.0f;
|
||||||
|
|
||||||
|
private final ClientWorld world;
|
||||||
|
private final List<RailStep> path;
|
||||||
|
private int cursor;
|
||||||
|
private int standIndex;
|
||||||
|
private long tickCounter;
|
||||||
|
// 初始化为 -ACTION_INTERVAL-1:tickCounter 从 1 开始时 1-(-5)=6 >= ACTION_INTERVAL,
|
||||||
|
// 第一次满足距离条件即可放置;绝不能用 Long.MIN_VALUE,否则 long 减法溢出得到大负数,
|
||||||
|
// “上次放置至今”恒为负,放置动作永远不会触发。
|
||||||
|
private long lastActionTick = -ACTION_INTERVAL - 1L;
|
||||||
|
private long stuckSince = -1;
|
||||||
|
private int stallTicks;
|
||||||
|
private int lastCursor;
|
||||||
|
private int jumpTicks;
|
||||||
|
private boolean lastNeedMove;
|
||||||
|
private String failKey;
|
||||||
|
private boolean finished;
|
||||||
|
|
||||||
|
public RailExecutor(ClientWorld world, List<RailStep> path) {
|
||||||
|
this.world = world;
|
||||||
|
this.path = path;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isFinished() {
|
||||||
|
return finished || failKey != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFailKey() {
|
||||||
|
return failKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getTotal() {
|
||||||
|
return path.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPlaced() {
|
||||||
|
return cursor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void tick(MinecraftClient client) {
|
||||||
|
if (finished || failKey != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ClientPlayerEntity player = client.player;
|
||||||
|
if (player == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tickCounter++;
|
||||||
|
|
||||||
|
// 1) 推进已完成(已有铁轨)的节点
|
||||||
|
while (cursor < path.size() && isDone(path.get(cursor))) {
|
||||||
|
cursor++;
|
||||||
|
}
|
||||||
|
if (cursor >= path.size()) {
|
||||||
|
finished = true;
|
||||||
|
releaseKeys();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) 行走(放置阶段会再覆盖朝向到交互点)
|
||||||
|
standIndex = findStandIndex(player);
|
||||||
|
move(client, player);
|
||||||
|
|
||||||
|
// 3) 放置:窗口内第一个“可达且未完成”的节点
|
||||||
|
if (tickCounter - lastActionTick >= ACTION_INTERVAL) {
|
||||||
|
for (int i = cursor; i < Math.min(cursor + PLACE_WINDOW, path.size()); i++) {
|
||||||
|
RailStep s = path.get(i);
|
||||||
|
if (isDone(s)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (player.getEyePos().squaredDistanceTo(Vec3d.ofCenter(s.railPos())) > REACH_SQ) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
attemptPlace(client, player, i);
|
||||||
|
lastActionTick = tickCounter;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4) 卡住 / 停滞检测
|
||||||
|
if (lastNeedMove && player.isOnGround() && speedSq(player) < 2.0e-4) {
|
||||||
|
if (stuckSince < 0) {
|
||||||
|
stuckSince = tickCounter;
|
||||||
|
} else if (tickCounter - stuckSince > 20) {
|
||||||
|
jumpTicks = Math.max(jumpTicks, 6); // 先尝试跳一下
|
||||||
|
}
|
||||||
|
if (tickCounter - stuckSince > STUCK_FAIL_TICKS) {
|
||||||
|
fail("autorail.err.stuck");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
stuckSince = -1;
|
||||||
|
}
|
||||||
|
if (cursor == lastCursor) {
|
||||||
|
if (++stallTicks > STALL_FAIL_TICKS) {
|
||||||
|
fail("autorail.err.stuck");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
lastCursor = cursor;
|
||||||
|
stallTicks = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 行走控制:朝已铺设前方的节点平滑转向并前进,需要上坡时自动跳跃。 */
|
||||||
|
private void move(MinecraftClient client, ClientPlayerEntity player) {
|
||||||
|
int frontier = cursor - 1; // 最高已完成节点
|
||||||
|
int walkIdx = Math.min(Math.max(frontier, 0), Math.min(standIndex + WALK_AHEAD, path.size() - 1));
|
||||||
|
BlockPos t = path.get(walkIdx).railPos();
|
||||||
|
Vec3d center = new Vec3d(t.getX() + 0.5, t.getY(), t.getZ() + 0.5);
|
||||||
|
double dx = center.x - player.getX();
|
||||||
|
double dz = center.z - player.getZ();
|
||||||
|
double hSq = dx * dx + dz * dz;
|
||||||
|
lastNeedMove = hSq > 0.6;
|
||||||
|
if (lastNeedMove) {
|
||||||
|
aimAt(player, center.add(0, 0.5, 0));
|
||||||
|
client.options.forwardKey.setPressed(true);
|
||||||
|
} else {
|
||||||
|
client.options.forwardKey.setPressed(false);
|
||||||
|
}
|
||||||
|
if (t.getY() > player.getBlockY() && hSq < 9.0) {
|
||||||
|
jumpTicks = 6;
|
||||||
|
}
|
||||||
|
if (jumpTicks > 0) {
|
||||||
|
client.options.jumpKey.setPressed(true);
|
||||||
|
jumpTicks--;
|
||||||
|
} else {
|
||||||
|
client.options.jumpKey.setPressed(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void attemptPlace(MinecraftClient client, ClientPlayerEntity player, int i) {
|
||||||
|
RailStep s = path.get(i);
|
||||||
|
BlockPos rail = s.railPos();
|
||||||
|
BlockState at = world.getBlockState(rail);
|
||||||
|
if (!at.isAir() && !at.isReplaceable() && !at.isOf(Blocks.RAIL)) {
|
||||||
|
fail("autorail.err.blocked");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
BlockPos support = rail.down();
|
||||||
|
BlockState sup = world.getBlockState(support);
|
||||||
|
if (!sup.isSolidBlock(world, support) || !sup.getFluidState().isEmpty()) {
|
||||||
|
// 支撑缺失(悬空/水中):先垫圆石
|
||||||
|
int slot = findSlot(player, Items.COBBLESTONE);
|
||||||
|
if (slot < 0) {
|
||||||
|
fail("autorail.err.noCobble");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
BlockHitResult hit = findSupportHit(player, i, support);
|
||||||
|
if (hit == null) {
|
||||||
|
fail("autorail.err.noHit");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
selectSlot(player, slot);
|
||||||
|
aimAt(player, hit.getPos());
|
||||||
|
client.interactionManager.interactBlock(player, Hand.MAIN_HAND, hit);
|
||||||
|
player.swingHand(Hand.MAIN_HAND);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int slot = findSlot(player, Items.RAIL);
|
||||||
|
if (slot < 0) {
|
||||||
|
fail("autorail.err.noRail");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
BlockHitResult hit = new BlockHitResult(
|
||||||
|
new Vec3d(support.getX() + 0.5, support.getY() + 1.0, support.getZ() + 0.5),
|
||||||
|
Direction.UP, support, false);
|
||||||
|
selectSlot(player, slot);
|
||||||
|
aimAt(player, hit.getPos());
|
||||||
|
client.interactionManager.interactBlock(player, Hand.MAIN_HAND, hit);
|
||||||
|
player.swingHand(Hand.MAIN_HAND);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 找一个可点击的实心面,把圆石垫进 support 位置。优先用上一节点的支撑侧面。 */
|
||||||
|
private BlockHitResult findSupportHit(ClientPlayerEntity player, int i, BlockPos support) {
|
||||||
|
if (i > 0) {
|
||||||
|
BlockPos prevRail = path.get(i - 1).railPos();
|
||||||
|
BlockPos prevSupport = prevRail.down();
|
||||||
|
if (isSolid(prevSupport)) {
|
||||||
|
Direction face = horizontalDirection(prevRail, path.get(i).railPos());
|
||||||
|
if (face != null) {
|
||||||
|
return faceHit(prevSupport, face);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
double best = Double.MAX_VALUE;
|
||||||
|
BlockHitResult bestHit = null;
|
||||||
|
Vec3d eye = player.getEyePos();
|
||||||
|
for (Direction face : Direction.values()) {
|
||||||
|
BlockPos nb = support.offset(face.getOpposite());
|
||||||
|
if (!isSolid(nb)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
BlockHitResult h = faceHit(nb, face);
|
||||||
|
double d = eye.squaredDistanceTo(h.getPos());
|
||||||
|
if (d < best) {
|
||||||
|
best = d;
|
||||||
|
bestHit = h;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bestHit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 点击 block 的 face 面(新方块会出现在 support 一侧)。 */
|
||||||
|
private static BlockHitResult faceHit(BlockPos block, Direction face) {
|
||||||
|
Vec3d p = new Vec3d(
|
||||||
|
block.getX() + 0.5 + face.getOffsetX() * 0.5,
|
||||||
|
block.getY() + 0.5 + face.getOffsetY() * 0.5,
|
||||||
|
block.getZ() + 0.5 + face.getOffsetZ() * 0.5);
|
||||||
|
return new BlockHitResult(p, face, block, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Direction horizontalDirection(BlockPos from, BlockPos to) {
|
||||||
|
int dx = to.getX() - from.getX();
|
||||||
|
int dz = to.getZ() - from.getZ();
|
||||||
|
if (Math.abs(dx) > Math.abs(dz)) {
|
||||||
|
return dx > 0 ? Direction.EAST : Direction.WEST;
|
||||||
|
}
|
||||||
|
if (dz != 0) {
|
||||||
|
return dz > 0 ? Direction.SOUTH : Direction.NORTH;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 在窗口内寻找离玩家最近的路径节点索引。 */
|
||||||
|
private int findStandIndex(ClientPlayerEntity player) {
|
||||||
|
int from = Math.max(0, standIndex - 4);
|
||||||
|
int to = Math.min(path.size() - 1, standIndex + 48);
|
||||||
|
int bestI = standIndex;
|
||||||
|
double bestD = Double.MAX_VALUE;
|
||||||
|
double px = player.getX();
|
||||||
|
double pz = player.getZ();
|
||||||
|
for (int i = from; i <= to; i++) {
|
||||||
|
BlockPos r = path.get(i).railPos();
|
||||||
|
double dx = r.getX() + 0.5 - px;
|
||||||
|
double dz = r.getZ() + 0.5 - pz;
|
||||||
|
double d = dx * dx + dz * dz;
|
||||||
|
if (d < bestD) {
|
||||||
|
bestD = d;
|
||||||
|
bestI = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bestI;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isDone(RailStep s) {
|
||||||
|
return world.getBlockState(s.railPos()).isOf(Blocks.RAIL);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isSolid(BlockPos pos) {
|
||||||
|
BlockState state = world.getBlockState(pos);
|
||||||
|
return !state.isAir()
|
||||||
|
&& state.getFluidState().isEmpty()
|
||||||
|
&& !state.isReplaceable()
|
||||||
|
&& state.isSolidBlock(world, pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double speedSq(ClientPlayerEntity player) {
|
||||||
|
Vec3d v = player.getVelocity();
|
||||||
|
return v.x * v.x + v.z * v.z;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把视线转向目标点(限制每 tick 转角,避免瞬移式甩头)。 */
|
||||||
|
private static void aimAt(ClientPlayerEntity player, Vec3d target) {
|
||||||
|
Vec3d eye = player.getEyePos();
|
||||||
|
double dx = target.x - eye.x;
|
||||||
|
double dy = target.y - eye.y;
|
||||||
|
double dz = target.z - eye.z;
|
||||||
|
double h = Math.sqrt(dx * dx + dz * dz);
|
||||||
|
float yaw = (float) Math.toDegrees(Math.atan2(-dx, dz));
|
||||||
|
float pitch = (float) -Math.toDegrees(Math.atan2(dy, h));
|
||||||
|
player.setYaw(stepAngle(player.getYaw(), yaw));
|
||||||
|
player.setPitch(stepAngle(player.getPitch(), pitch));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static float stepAngle(float cur, float target) {
|
||||||
|
float d = MathHelper.wrapDegrees(target - cur);
|
||||||
|
if (d > MAX_TURN_PER_TICK) {
|
||||||
|
d = MAX_TURN_PER_TICK;
|
||||||
|
} else if (d < -MAX_TURN_PER_TICK) {
|
||||||
|
d = -MAX_TURN_PER_TICK;
|
||||||
|
}
|
||||||
|
return MathHelper.wrapDegrees(cur + d);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 快捷栏查找指定物品。 */
|
||||||
|
private static int findSlot(ClientPlayerEntity player, net.minecraft.item.Item item) {
|
||||||
|
for (int i = 0; i < 9; i++) {
|
||||||
|
if (player.getInventory().getStack(i).isOf(item)) {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 切换选中槽位并同步给服务端。 */
|
||||||
|
private static void selectSlot(ClientPlayerEntity player, int slot) {
|
||||||
|
player.getInventory().selectedSlot = slot;
|
||||||
|
if (player.networkHandler != null) {
|
||||||
|
player.networkHandler.sendPacket(new UpdateSelectedSlotC2SPacket(slot));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fail(String key) {
|
||||||
|
failKey = key;
|
||||||
|
releaseKeys();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void releaseKeys() {
|
||||||
|
MinecraftClient mc = MinecraftClient.getInstance();
|
||||||
|
if (mc == null || mc.options == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
mc.options.forwardKey.setPressed(false);
|
||||||
|
mc.options.jumpKey.setPressed(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,39 @@
|
|||||||
{
|
{
|
||||||
"key.autorail.toggle": "Toggle Auto Rail",
|
"autorail.gui.title": "AutoRail",
|
||||||
"category.autorail": "AutoRail"
|
"autorail.gui.hint": "Format: x y z (or x z for auto height). ~ = current, supports ~5 / ~-3 offsets",
|
||||||
|
"autorail.gui.hint.laying": "Laying in progress: close this screen so the player keeps walking",
|
||||||
|
"autorail.gui.start": "Start",
|
||||||
|
"autorail.gui.start.ph": "Empty = current position",
|
||||||
|
"autorail.gui.dest": "Destination",
|
||||||
|
"autorail.gui.dest.ph": "e.g. 100 64 -200",
|
||||||
|
"autorail.gui.waypoints": "Waypoints (visited in order)",
|
||||||
|
"autorail.gui.wp.ph": "e.g. ~ 100",
|
||||||
|
"autorail.gui.add": "+ Add waypoint",
|
||||||
|
"autorail.gui.remove": "X",
|
||||||
|
"autorail.gui.begin": "Start laying",
|
||||||
|
"autorail.gui.stop": "Stop",
|
||||||
|
"autorail.gui.close": "Close",
|
||||||
|
"autorail.gui.status.idle": "Idle",
|
||||||
|
"autorail.gui.status.planning": "Pathfinding… {0} nodes opened",
|
||||||
|
"autorail.gui.status.laying": "Laying rails… {0} / {1}",
|
||||||
|
"autorail.gui.status.done": "Done! {0} rails placed",
|
||||||
|
"autorail.gui.status.failed": "Failed: {0}",
|
||||||
|
"autorail.err.needWorld": "Enter a world first",
|
||||||
|
"autorail.err.emptyCoord": "Coordinate is empty",
|
||||||
|
"autorail.err.coordFormat": "Bad coordinate format (e.g. 100 64 -200 or ~ 10 ~)",
|
||||||
|
"autorail.err.noGround": "No usable ground in that column",
|
||||||
|
"autorail.err.startFar": "Start must be near the player (within 6 blocks horizontal, 8 vertical)",
|
||||||
|
"autorail.err.startEqDest": "Start and destination are the same",
|
||||||
|
"autorail.err.startInvalid": "Cannot place a rail at the start (check headroom and support)",
|
||||||
|
"autorail.err.pathNotFound": "No rail-able path found (try adding waypoints)",
|
||||||
|
"autorail.err.tooFar": "Too far or too complex for the pathfinder",
|
||||||
|
"autorail.err.noRail": "No rails left in the hotbar",
|
||||||
|
"autorail.err.noCobble": "Bridging needs cobblestone in the hotbar",
|
||||||
|
"autorail.err.noHit": "No clickable block to place against",
|
||||||
|
"autorail.err.blocked": "Path blocked (cannot place a rail there)",
|
||||||
|
"autorail.err.stuck": "Player stuck - clear the obstacle and retry",
|
||||||
|
"autorail.msg.plan.start": "Pathfinding ({0} checkpoints)…",
|
||||||
|
"autorail.msg.plan.done": "Path found: {0} blocks. Laying rails - avoid opening other screens",
|
||||||
|
"autorail.msg.lay.done": "Done! {0} rails placed",
|
||||||
|
"autorail.msg.stopped": "Stopped"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,39 @@
|
|||||||
{
|
{
|
||||||
"key.autorail.toggle": "切换自动铺轨",
|
"autorail.gui.title": "AutoRail 自动铺轨",
|
||||||
"category.autorail": "自动铺轨"
|
"autorail.gui.hint": "坐标格式:x y z(或 x z 自动取地面);~ 表示当前,支持 ~5 / ~-3 偏移",
|
||||||
|
"autorail.gui.hint.laying": "铺轨进行中:关闭此界面玩家才会继续行走",
|
||||||
|
"autorail.gui.start": "起始点",
|
||||||
|
"autorail.gui.start.ph": "留空 = 当前位置",
|
||||||
|
"autorail.gui.dest": "目标点",
|
||||||
|
"autorail.gui.dest.ph": "例如 100 64 -200",
|
||||||
|
"autorail.gui.waypoints": "途径点(按顺序经过,可留空)",
|
||||||
|
"autorail.gui.wp.ph": "例如 ~ 100",
|
||||||
|
"autorail.gui.add": "+ 添加途径点",
|
||||||
|
"autorail.gui.remove": "✕",
|
||||||
|
"autorail.gui.begin": "开始铺轨",
|
||||||
|
"autorail.gui.stop": "停止",
|
||||||
|
"autorail.gui.close": "关闭",
|
||||||
|
"autorail.gui.status.idle": "待机中",
|
||||||
|
"autorail.gui.status.planning": "寻路中… 已展开 {0} 个节点",
|
||||||
|
"autorail.gui.status.laying": "铺轨中… {0} / {1}",
|
||||||
|
"autorail.gui.status.done": "完成!共铺设 {0} 格铁轨",
|
||||||
|
"autorail.gui.status.failed": "失败:{0}",
|
||||||
|
"autorail.err.needWorld": "请先进入世界",
|
||||||
|
"autorail.err.emptyCoord": "坐标不能为空",
|
||||||
|
"autorail.err.coordFormat": "坐标格式错误(示例:100 64 -200 或 ~ 10 ~)",
|
||||||
|
"autorail.err.noGround": "该坐标列找不到可用的地面",
|
||||||
|
"autorail.err.startFar": "起始点必须在玩家附近(水平 6 格、垂直 8 格以内)",
|
||||||
|
"autorail.err.startEqDest": "起始点和目标点相同",
|
||||||
|
"autorail.err.startInvalid": "起始点无法放置铁轨(检查上方空间与下方支撑)",
|
||||||
|
"autorail.err.pathNotFound": "找不到可铺轨的路径(试试增加途径点绕行)",
|
||||||
|
"autorail.err.tooFar": "距离太远或地形太复杂,超出寻路上限",
|
||||||
|
"autorail.err.noRail": "快捷栏里没有铁轨了",
|
||||||
|
"autorail.err.noCobble": "前方需要垫脚,但快捷栏里没有圆石",
|
||||||
|
"autorail.err.noHit": "找不到可交互的方块来放置",
|
||||||
|
"autorail.err.blocked": "路径被阻挡(该位置无法放置铁轨)",
|
||||||
|
"autorail.err.stuck": "玩家卡住了,请清理障碍后重试",
|
||||||
|
"autorail.msg.plan.start": "开始寻路({0} 个检查点)…",
|
||||||
|
"autorail.msg.plan.done": "路径规划完成:{0} 格,开始铺轨(请勿打开其他界面)",
|
||||||
|
"autorail.msg.lay.done": "铺轨完成!共 {0} 格",
|
||||||
|
"autorail.msg.stopped": "已停止"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"id": "autorail",
|
"id": "autorail",
|
||||||
"version": "${version}",
|
"version": "${version}",
|
||||||
"name": "AutoRail",
|
"name": "AutoRail",
|
||||||
"description": "面向方向自动铺设铁轨(基于 Baritone API)。",
|
"description": "自动铺铁轨模组:内置 A* 寻路规划可铺轨路线,控制玩家边走边合法右键放置铁轨/圆石,不依赖 Baritone。",
|
||||||
"authors": [
|
"authors": [
|
||||||
"AutoRail"
|
"AutoRail"
|
||||||
],
|
],
|
||||||
@@ -19,8 +19,5 @@
|
|||||||
"minecraft": "~1.21.4",
|
"minecraft": "~1.21.4",
|
||||||
"java": ">=21",
|
"java": ">=21",
|
||||||
"fabric-api": "*"
|
"fabric-api": "*"
|
||||||
},
|
|
||||||
"suggests": {
|
|
||||||
"baritone": "*"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
在新工单中引用
屏蔽一个用户