commit b26dfbbade1e32ae2663ff6891951369c10c171b Author: loki5512344 Date: Fri Oct 16 10:21:20 2026 +0200 Satura: каркас мода, ядро, селекция, план, рендер, стратегии постановки и движок Фазы 0-5: сборка Gradle/Loom, core (события, команды, конфиг), selection/plan/scan, рендер (перенесён из Atheryx, см. NOTICE.md), стратегии ColumnDrop/BandStack, HotbarRefill/ClickScheduler, BuildEngine и команды .build. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c14c82f --- /dev/null +++ b/.gitignore @@ -0,0 +1,30 @@ +# Gradle +.gradle/ +build/ +run/ +remappedSrc/ + +# IDE +.idea/ +*.iml +.vscode/ +.settings/ +.classpath +.project +bin/ + +# OS +.DS_Store + +# Чужие референсы и распаковки (343M, чужой код) +ref/ + +# Логи и локальные данные +*.log +hs_err_pid* +logs/ +todo.md + +# Локальные заметки +NOTICE.md +todo.md diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..2a8ac87 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,76 @@ +plugins { + id("fabric-loom") version "1.18.4" + java + checkstyle + pmd +} + +version = property("mod_version") as String +group = property("maven_group") as String + +base { + archivesName.set(property("archives_base_name") as String) +} + +repositories { + // nether-pathfinder — рантайм-зависимость Baritone (Aethereal) для dev-запусков + maven("https://babbaj.github.io/maven/") { + name = "Babbaj" + } +} + +dependencies { + minecraft("com.mojang:minecraft:${property("minecraft_version")}") + mappings("net.fabricmc:yarn:${property("yarn_mappings")}:v2") + modImplementation("net.fabricmc:fabric-loader:${property("loader_version")}") + modImplementation("net.fabricmc.fabric-api:fabric-api:${property("fabric_version")}") + + // Baritone (Aethereal): API для компиляции + сам мод в dev-рантайме + compileOnly(files("libs/aethereal-1.21.11.jar")) + modLocalRuntime(files("libs/aethereal-1.21.11.jar")) + modLocalRuntime("dev.babbaj:nether-pathfinder:1.4.1") + + testImplementation(platform("org.junit:junit-bom:5.11.4")) + testImplementation("org.junit.jupiter:junit-jupiter") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} + +java { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 + withSourcesJar() +} + +tasks.withType().configureEach { + options.encoding = "UTF-8" + options.release.set(21) +} + +tasks.processResources { + inputs.property("version", project.version) + filesMatching("fabric.mod.json") { + expand("version" to project.version) + } +} + +// Правило проекта: файл максимум 200 строк — FileLength (severity=error валит check) +checkstyle { + toolVersion = "10.21.2" + configFile = rootProject.file("config/checkstyle/checkstyle.xml") +} + +pmd { + toolVersion = "7.9.0" + isConsoleOutput = true + ruleSetFiles = rootProject.files("config/pmd/pmd.xml") + ruleSets = mutableListOf() +} + +tasks.test { + useJUnitPlatform() +} + +// Тесты — шумные правила JUnit в PMD (assert-сообщения, число assert) не применяем +tasks.named("pmdTest") { + enabled = false +} diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 0000000..b39458a --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/pmd/pmd.xml b/config/pmd/pmd.xml new file mode 100644 index 0000000..4577da7 --- /dev/null +++ b/config/pmd/pmd.xml @@ -0,0 +1,25 @@ + + + + Satura base ruleset: errorprone + bestpractices + design (без шума) + + + + + + + + + + + + + + + + + diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..6149ebd --- /dev/null +++ b/gradle.properties @@ -0,0 +1,15 @@ +# Gradle +org.gradle.jvmargs=-Xmx2G +org.gradle.parallel=true + +# Fabric / Minecraft (проверены: meta.fabricmc.net + Modrinth) +minecraft_version=1.21.11 +yarn_mappings=1.21.11+build.6 +loader_version=0.20.1 +fabric_version=0.141.6+1.21.11 + +# Мод +mod_version=0.1.0 +maven_group=dev.loki +archives_base_name=satura +org.gradle.java.home=/usr/lib/jvm/java-25-openjdk diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..9fa7f28 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..91c4fc6 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..379a658 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 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 +# + +############################################################################## +# +# gradlew 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 gradlew +# +# 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//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\n' "$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 + + + +# 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" ) + + 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='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_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" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# 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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..03754c4 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,112 @@ +@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 gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet + +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="-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 + +1>&2 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. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +1>&2 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. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel + +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/libs/aethereal-1.21.11.jar b/libs/aethereal-1.21.11.jar new file mode 100644 index 0000000..e84897b Binary files /dev/null and b/libs/aethereal-1.21.11.jar differ diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..4cd6c8b --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,11 @@ +pluginManagement { + repositories { + maven("https://maven.fabricmc.net/") { + name = "Fabric" + } + mavenCentral() + gradlePluginPortal() + } +} + +rootProject.name = "satura" diff --git a/src/main/java/dev/loki/satura/SaturaClient.java b/src/main/java/dev/loki/satura/SaturaClient.java new file mode 100644 index 0000000..dfec8c1 --- /dev/null +++ b/src/main/java/dev/loki/satura/SaturaClient.java @@ -0,0 +1,44 @@ +package dev.loki.satura; + +import dev.loki.satura.core.CoreServices; +import dev.loki.satura.core.command.CommandRegistry; +import dev.loki.satura.core.command.builtin.HelpCommand; +import dev.loki.satura.core.config.ConfigStore; +import dev.loki.satura.core.event.EventBus; +import dev.loki.satura.feature.builder.BuilderFeature; +import dev.loki.satura.render.RenderDebug; +import dev.loki.satura.render.Renderer; +import dev.loki.satura.render.world.Marks; +import dev.loki.satura.render.world.SelectionRenderer; +import dev.loki.satura.util.ChatOut; +import net.fabricmc.api.ClientModInitializer; +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; +import net.fabricmc.loader.api.FabricLoader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Точка входа клиента. Только сборка компонентов — вся логика в feature-пакетах. + */ +public final class SaturaClient implements ClientModInitializer { + + public static final String MOD_ID = "satura"; + private static final boolean SELECTION_SEE_THROUGH = true; + + public static final Logger LOG = LoggerFactory.getLogger(MOD_ID); + + @Override + public void onInitializeClient() { + CommandRegistry commands = new CommandRegistry(new ChatOut()); + commands.register(new HelpCommand(commands)); + EventBus events = new EventBus(); + ConfigStore config = new ConfigStore(FabricLoader.getInstance().getConfigDir().resolve(MOD_ID)); + BuilderFeature builder = BuilderFeature.create(commands, events, config); + CoreServices.install(new CoreServices(events, commands, config)); + ClientTickEvents.END_CLIENT_TICK.register(client -> builder.tick()); + RenderDebug.installIfEnabled(Renderer.shared()); + new SelectionRenderer(() -> new Marks(builder.selection().pos1(), builder.selection().pos2()), + SELECTION_SEE_THROUGH).register(); + LOG.info("[satura] client init"); + } +} diff --git a/src/main/java/dev/loki/satura/core/CoreServices.java b/src/main/java/dev/loki/satura/core/CoreServices.java new file mode 100644 index 0000000..5cd2256 --- /dev/null +++ b/src/main/java/dev/loki/satura/core/CoreServices.java @@ -0,0 +1,20 @@ +package dev.loki.satura.core; + +import dev.loki.satura.core.command.CommandRegistry; +import dev.loki.satura.core.config.ConfigStore; +import dev.loki.satura.core.event.EventBus; + +/** Собранное ядро; доступ для миксинов (они не могут получить зависимости через конструктор). */ +public record CoreServices(EventBus events, CommandRegistry commands, ConfigStore config) { + + private static CoreServices current; + + public static void install(CoreServices services) { + current = services; + } + + /** Ядро или null, если мод ещё не инициализирован. */ + public static CoreServices get() { + return current; + } +} diff --git a/src/main/java/dev/loki/satura/core/command/Command.java b/src/main/java/dev/loki/satura/core/command/Command.java new file mode 100644 index 0000000..2ab0ea7 --- /dev/null +++ b/src/main/java/dev/loki/satura/core/command/Command.java @@ -0,0 +1,29 @@ +package dev.loki.satura.core.command; + +import java.util.List; +import java.util.function.Consumer; + +/** Чат-команда с префиксом {@code .}. */ +public interface Command { + + String name(); + + String description(); + + /** + * Выполнить команду. + * + * @param args токены после имени + * @param reply куда писать ответ пользователю + */ + void execute(List args, Consumer reply); + + /** + * Кандидаты для последнего (редактируемого) токена. + * + * @param args токены после имени; последний — недописанный (может быть пустым) + */ + default List suggest(List args) { + return List.of(); + } +} diff --git a/src/main/java/dev/loki/satura/core/command/CommandParser.java b/src/main/java/dev/loki/satura/core/command/CommandParser.java new file mode 100644 index 0000000..834286c --- /dev/null +++ b/src/main/java/dev/loki/satura/core/command/CommandParser.java @@ -0,0 +1,38 @@ +package dev.loki.satura.core.command; + +import java.util.ArrayList; +import java.util.List; + +/** Разбиение строки на токены по пробелам; кавычки группируют; хвостовой пробел даёт пустой токен. */ +final class CommandParser { + + private static final char QUOTE = '"'; + private static final char SEPARATOR = ' '; + + private CommandParser() { + } + + static List tokenize(String line) { + List tokens = new ArrayList<>(); + StringBuilder cur = new StringBuilder(); + boolean quoted = false; + for (char ch : line.toCharArray()) { + if (ch == QUOTE) { + quoted = !quoted; + } else if (ch == SEPARATOR && !quoted) { + flush(tokens, cur); + } else { + cur.append(ch); + } + } + tokens.add(cur.toString()); + return tokens; + } + + private static void flush(List tokens, StringBuilder cur) { + if (!cur.isEmpty()) { + tokens.add(cur.toString()); + cur.setLength(0); + } + } +} diff --git a/src/main/java/dev/loki/satura/core/command/CommandRegistry.java b/src/main/java/dev/loki/satura/core/command/CommandRegistry.java new file mode 100644 index 0000000..bbf7254 --- /dev/null +++ b/src/main/java/dev/loki/satura/core/command/CommandRegistry.java @@ -0,0 +1,62 @@ +package dev.loki.satura.core.command; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.TreeMap; +import java.util.function.Consumer; + +/** Реестр команд: регистрация, выполнение строки и подсказки. */ +@SuppressWarnings({"PMD.LooseCoupling", "PMD.AvoidCatchingGenericException"}) +public final class CommandRegistry { + + private static final int COMMAND_ONLY = 1; + + private final Map commands = new TreeMap<>(); + private final Consumer reply; + + public CommandRegistry(Consumer reply) { + this.reply = reply; + } + + public void register(Command command) { + commands.put(command.name().toLowerCase(Locale.ROOT), command); + } + + public Collection all() { + return commands.values(); + } + + /** Выполняет строку без префикса, например {@code "help"}. */ + public void execute(String line) { + List tokens = CommandParser.tokenize(line.strip()); + Command command = commands.get(tokens.get(0).toLowerCase(Locale.ROOT)); + if (command == null) { + reply.accept("Неизвестная команда: " + tokens.get(0) + " (.help)"); + return; + } + try { + command.execute(tokens.subList(1, tokens.size()), reply); + } catch (RuntimeException e) { + reply.accept("Ошибка: " + e.getMessage()); + } + } + + /** Подсказки для текста до курсора (с префиксом). */ + public List suggest(String toCursor) { + String body = toCursor.startsWith(SuggestHelper.PREFIX) + ? toCursor.substring(SuggestHelper.PREFIX.length()) : toCursor; + List tokens = CommandParser.tokenize(body); + String current = tokens.get(tokens.size() - 1); + if (tokens.size() == COMMAND_ONLY) { + return SuggestHelper.filter(current, new ArrayList<>(commands.keySet())); + } + Command command = commands.get(tokens.get(0).toLowerCase(Locale.ROOT)); + if (command == null) { + return List.of(); + } + return SuggestHelper.filter(current, command.suggest(tokens.subList(1, tokens.size()))); + } +} diff --git a/src/main/java/dev/loki/satura/core/command/SuggestHelper.java b/src/main/java/dev/loki/satura/core/command/SuggestHelper.java new file mode 100644 index 0000000..7d48b4a --- /dev/null +++ b/src/main/java/dev/loki/satura/core/command/SuggestHelper.java @@ -0,0 +1,34 @@ +package dev.loki.satura.core.command; + +import java.util.List; +import java.util.Locale; + +/** Фильтрация подсказок по префиксу и позиция начала редактируемого токена. */ +public final class SuggestHelper { + + public static final String PREFIX = "."; + private static final char SEPARATOR = ' '; + + private SuggestHelper() { + } + + public static boolean isCommand(String text) { + return text.startsWith(PREFIX); + } + + public static int tokenStart(String toCursor) { + int lastSpace = toCursor.lastIndexOf(SEPARATOR); + if (lastSpace >= 0) { + return lastSpace + 1; + } + return isCommand(toCursor) ? PREFIX.length() : 0; + } + + public static List filter(String prefix, List options) { + String key = prefix.toLowerCase(Locale.ROOT); + return options.stream() + .filter(o -> o.toLowerCase(Locale.ROOT).startsWith(key)) + .distinct() + .toList(); + } +} diff --git a/src/main/java/dev/loki/satura/core/command/builtin/HelpCommand.java b/src/main/java/dev/loki/satura/core/command/builtin/HelpCommand.java new file mode 100644 index 0000000..94f697e --- /dev/null +++ b/src/main/java/dev/loki/satura/core/command/builtin/HelpCommand.java @@ -0,0 +1,35 @@ +package dev.loki.satura.core.command.builtin; + +import dev.loki.satura.core.command.Command; +import dev.loki.satura.core.command.CommandRegistry; +import dev.loki.satura.core.command.SuggestHelper; +import java.util.List; +import java.util.function.Consumer; + +/** {@code .help} — список зарегистрированных команд. */ +public final class HelpCommand implements Command { + + private final CommandRegistry registry; + + public HelpCommand(CommandRegistry registry) { + this.registry = registry; + } + + @Override + public String name() { + return "help"; + } + + @Override + public String description() { + return "список команд"; + } + + @Override + public void execute(List args, Consumer reply) { + reply.accept("Команды Satura:"); + for (Command c : registry.all()) { + reply.accept(SuggestHelper.PREFIX + c.name() + " — " + c.description()); + } + } +} diff --git a/src/main/java/dev/loki/satura/core/config/ConfigStore.java b/src/main/java/dev/loki/satura/core/config/ConfigStore.java new file mode 100644 index 0000000..681fa31 --- /dev/null +++ b/src/main/java/dev/loki/satura/core/config/ConfigStore.java @@ -0,0 +1,60 @@ +package dev.loki.satura.core.config; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +/** Хранение профилей как json-файлов в каталоге (config/satura/). */ +public final class ConfigStore { + + private static final String EXTENSION = ".json"; + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + private final Path dir; + + public ConfigStore(Path dir) { + this.dir = dir; + } + + public void save(Profile profile) throws IOException { + Files.createDirectories(dir); + try (Writer w = Files.newBufferedWriter(file(profile.name()), StandardCharsets.UTF_8)) { + GSON.toJson(profile, w); + } + } + + public Optional load(String name) throws IOException { + Path file = file(name); + if (!Files.exists(file)) { + return Optional.empty(); + } + try (Reader r = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { + return Optional.ofNullable(GSON.fromJson(r, Profile.class)); + } + } + + public List list() throws IOException { + if (!Files.isDirectory(dir)) { + return List.of(); + } + try (Stream files = Files.list(dir)) { + return files.map(p -> p.getFileName().toString()) + .filter(n -> n.endsWith(EXTENSION)) + .map(n -> n.substring(0, n.length() - EXTENSION.length())) + .sorted() + .toList(); + } + } + + private Path file(String name) { + return dir.resolve(name + EXTENSION); + } +} diff --git a/src/main/java/dev/loki/satura/core/config/Profile.java b/src/main/java/dev/loki/satura/core/config/Profile.java new file mode 100644 index 0000000..bf7b84f --- /dev/null +++ b/src/main/java/dev/loki/satura/core/config/Profile.java @@ -0,0 +1,34 @@ +package dev.loki.satura.core.config; + +import java.util.HashMap; +import java.util.Map; + +/** + * Иммутабельный профиль настроек. + * + * @param name имя профиля (имя файла) + * @param settings ключ → значение + */ +@SuppressWarnings("PMD.LooseCoupling") +public record Profile(String name, Map settings) { + + public static final String DEFAULT_NAME = "default"; + + public Profile { + settings = Map.copyOf(settings); + } + + public static Profile empty(String name) { + return new Profile(name, Map.of()); + } + + public String get(String key, String fallback) { + return settings.getOrDefault(key, fallback); + } + + public Profile with(String key, String value) { + Map copy = new HashMap<>(settings); + copy.put(key, value); + return new Profile(name, copy); + } +} diff --git a/src/main/java/dev/loki/satura/core/event/Cancellable.java b/src/main/java/dev/loki/satura/core/event/Cancellable.java new file mode 100644 index 0000000..bef2783 --- /dev/null +++ b/src/main/java/dev/loki/satura/core/event/Cancellable.java @@ -0,0 +1,9 @@ +package dev.loki.satura.core.event; + +/** Событие, обработку которого можно отменить; после отмены цепочка слушателей прерывается. */ +public interface Cancellable extends Event { + + boolean isCancelled(); + + void cancel(); +} diff --git a/src/main/java/dev/loki/satura/core/event/Event.java b/src/main/java/dev/loki/satura/core/event/Event.java new file mode 100644 index 0000000..486e9cb --- /dev/null +++ b/src/main/java/dev/loki/satura/core/event/Event.java @@ -0,0 +1,5 @@ +package dev.loki.satura.core.event; + +/** Маркер события. Тип события = его класс. */ +public interface Event { +} diff --git a/src/main/java/dev/loki/satura/core/event/EventBus.java b/src/main/java/dev/loki/satura/core/event/EventBus.java new file mode 100644 index 0000000..e16878f --- /dev/null +++ b/src/main/java/dev/loki/satura/core/event/EventBus.java @@ -0,0 +1,48 @@ +package dev.loki.satura.core.event; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + +/** Шина событий: подписка с приоритетами, отписка, остановка цепочки на отменённом событии. */ +@SuppressWarnings("PMD.LooseCoupling") +public final class EventBus { + + private static final Comparator> BY_PRIORITY = Comparator.comparingInt(Listener::priority); + + private final Map, List>> registry = new ConcurrentHashMap<>(); + + public Listener subscribe(Listener listener) { + registry.computeIfAbsent(listener.type(), k -> new CopyOnWriteArrayList<>()).add(listener); + registry.get(listener.type()).sort(BY_PRIORITY); + return listener; + } + + public Listener subscribe(Class type, java.util.function.Consumer handler) { + return subscribe(Listener.of(type, handler)); + } + + public void unsubscribe(Listener listener) { + List> list = registry.get(listener.type()); + if (list != null) { + list.remove(listener); + } + } + + public T post(T event) { + List> list = registry.get(event.getClass()); + if (list == null) { + return event; + } + for (Listener listener : new ArrayList<>(list)) { + listener.accept(event); + if (event instanceof Cancellable c && c.isCancelled()) { + break; + } + } + return event; + } +} diff --git a/src/main/java/dev/loki/satura/core/event/Listener.java b/src/main/java/dev/loki/satura/core/event/Listener.java new file mode 100644 index 0000000..1a6cfa3 --- /dev/null +++ b/src/main/java/dev/loki/satura/core/event/Listener.java @@ -0,0 +1,24 @@ +package dev.loki.satura.core.event; + +import java.util.function.Consumer; + +/** + * Подписка на событие. Меньший priority вызывается раньше. + * + * @param type класс события + * @param priority порядок вызова + * @param handler обработчик + * @param тип события + */ +public record Listener(Class type, int priority, Consumer handler) { + + public static final int DEFAULT_PRIORITY = 0; + + public static Listener of(Class type, Consumer handler) { + return new Listener<>(type, DEFAULT_PRIORITY, handler); + } + + void accept(Event event) { + handler.accept(type.cast(event)); + } +} diff --git a/src/main/java/dev/loki/satura/core/event/world/BlockChangeEvent.java b/src/main/java/dev/loki/satura/core/event/world/BlockChangeEvent.java new file mode 100644 index 0000000..7c2e0ce --- /dev/null +++ b/src/main/java/dev/loki/satura/core/event/world/BlockChangeEvent.java @@ -0,0 +1,8 @@ +package dev.loki.satura.core.event.world; + +import dev.loki.satura.core.event.Event; +import net.minecraft.util.math.BlockPos; + +/** В клиентском мире изменился блок. */ +public record BlockChangeEvent(BlockPos pos) implements Event { +} diff --git a/src/main/java/dev/loki/satura/feature/builder/BuildSettings.java b/src/main/java/dev/loki/satura/feature/builder/BuildSettings.java new file mode 100644 index 0000000..12dd17c --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/BuildSettings.java @@ -0,0 +1,151 @@ +package dev.loki.satura.feature.builder; + +import dev.loki.satura.core.config.Profile; +import dev.loki.satura.feature.builder.plan.Planner; +import dev.loki.satura.feature.builder.plan.shape.BoxShape; +import dev.loki.satura.feature.builder.plan.shape.CheckerShape; +import dev.loki.satura.feature.builder.plan.shape.Shape; +import dev.loki.satura.feature.builder.plan.shape.WallsShape; +import dev.loki.satura.interaction.place.PlaceStrategy; +import dev.loki.satura.interaction.place.option.CommonOptions; +import dev.loki.satura.interaction.place.option.Option; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** Настройки билдера; читаются из {@link Profile} и в него же сериализуются. */ +@SuppressWarnings({"PMD.LooseCoupling", "PMD.AvoidFieldNameMatchingMethodName"}) +public final class BuildSettings { + + static final String KEY_BLOCK = "block"; + static final String KEY_SHAPE = "shape"; + static final String KEY_LAYERS = "layers"; + static final String KEY_STRATEGY = "strategy"; + private static final String OPT_PREFIX = "opt."; + private static final String DEFAULT_BLOCK = "hand"; + private static final String DEFAULT_SHAPE = "box"; + + private final Map shapes = new LinkedHashMap<>(); + private final Map strategies = new LinkedHashMap<>(); + private String block; + private String shape; + private String strategy; + private int layers; + + public BuildSettings(final Profile profile, final List available) { + shapes.put("box", new BoxShape()); + shapes.put("checker", new CheckerShape()); + shapes.put("walls", new WallsShape()); + for (final PlaceStrategy s : available) { + strategies.put(s.id(), s); + } + block = profile.get(KEY_BLOCK, DEFAULT_BLOCK); + shape = shapes.containsKey(profile.get(KEY_SHAPE, "")) ? profile.get(KEY_SHAPE, "") : DEFAULT_SHAPE; + strategy = strategies.containsKey(profile.get(KEY_STRATEGY, "")) + ? profile.get(KEY_STRATEGY, "") : available.get(0).id(); + layers = parseLayers(profile.get(KEY_LAYERS, "2")); + strategies.values().forEach(s -> loadOptions(profile, s)); + } + + public String block() { + return block; + } + + public void setBlock(final String id) { + block = id; + } + + public String shapeId() { + return shape; + } + + public Shape shape() { + return shapes.get(shape); + } + + public List shapeIds() { + return List.copyOf(shapes.keySet()); + } + + public void setShape(final String id) { + final String key = id.toLowerCase(Locale.ROOT); + require(shapes.containsKey(key), "форма: " + shapeIds()); + shape = key; + } + + public PlaceStrategy strategy() { + return strategies.get(strategy); + } + + public List strategyIds() { + return List.copyOf(strategies.keySet()); + } + + public void setStrategy(final String id) { + require(strategies.containsKey(id), "стратегия: " + strategyIds()); + strategy = id; + } + + /** Слоёв за проход: значение опции стратегии bandLayers, если она её объявляет. */ + public int layers() { + final PlaceStrategy s = strategy(); + return s.options().contains(CommonOptions.BAND_LAYERS) + ? s.values().getInt(CommonOptions.BAND_LAYERS) : layers; + } + + public void setLayers(final int value) { + require(value >= Planner.MIN_BAND_LAYERS && value <= Planner.MAX_BAND_LAYERS, "слои: 1-3"); + layers = value; + strategies.values().stream().filter(s -> s.options().contains(CommonOptions.BAND_LAYERS)) + .forEach(s -> s.values().set(CommonOptions.BAND_LAYERS.key(), value)); + } + + public List optionKeys() { + return strategy().options().stream().map(Option::key).toList(); + } + + public void setOption(final String key, final String value) { + final double number; + try { + number = Double.parseDouble(value); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("не число: " + value, e); + } + require(strategy().values().set(key, number), "параметр: " + optionKeys()); + if (CommonOptions.BAND_LAYERS.key().equals(key)) { + layers = strategy().values().getInt(CommonOptions.BAND_LAYERS); + } + } + + public Profile toProfile(final String name) { + Profile p = Profile.empty(name).with(KEY_BLOCK, block).with(KEY_SHAPE, shape) + .with(KEY_STRATEGY, strategy).with(KEY_LAYERS, String.valueOf(layers)); + for (final PlaceStrategy s : strategies.values()) { + for (final Option o : s.options()) { + p = p.with(OPT_PREFIX + s.id() + "." + o.key(), String.valueOf(s.values().get(o))); + } + } + return p; + } + + private static void loadOptions(final Profile profile, final PlaceStrategy s) { + for (final Option o : s.options()) { + final String raw = profile.get(OPT_PREFIX + s.id() + "." + o.key(), ""); + if (!raw.isEmpty()) { + s.values().set(o.key(), Double.parseDouble(raw)); + } + } + } + + private static int parseLayers(final String raw) { + final int v = Integer.parseInt(raw); + return Math.max(Planner.MIN_BAND_LAYERS, Math.min(Planner.MAX_BAND_LAYERS, v)); + } + + private static void require(final boolean ok, final String message) { + if (!ok) { + throw new IllegalArgumentException(message); + } + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/BuilderFeature.java b/src/main/java/dev/loki/satura/feature/builder/BuilderFeature.java new file mode 100644 index 0000000..04b3bb3 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/BuilderFeature.java @@ -0,0 +1,200 @@ +package dev.loki.satura.feature.builder; + +import dev.loki.satura.core.command.CommandRegistry; +import dev.loki.satura.core.config.ConfigStore; +import dev.loki.satura.core.config.Profile; +import dev.loki.satura.core.event.EventBus; +import dev.loki.satura.feature.builder.commands.BuildCommand; +import dev.loki.satura.feature.builder.commands.BuildControl; +import dev.loki.satura.feature.builder.engine.BuildEngine; +import dev.loki.satura.feature.builder.engine.Stage; +import dev.loki.satura.feature.builder.engine.walk.NoWalker; +import dev.loki.satura.feature.builder.engine.walk.Walker; +import dev.loki.satura.feature.builder.selection.Area; +import dev.loki.satura.feature.builder.selection.PosCommand; +import dev.loki.satura.feature.builder.selection.SelCommand; +import dev.loki.satura.feature.builder.selection.Selection; +import dev.loki.satura.interaction.place.PlaceStrategy; +import dev.loki.satura.interaction.place.strategy.BandStack; +import dev.loki.satura.interaction.place.strategy.ColumnDrop; +import dev.loki.satura.interaction.place.support.BlockPlacer; +import dev.loki.satura.interaction.place.support.Cooldown; +import dev.loki.satura.interaction.place.support.SupportFinder; +import dev.loki.satura.util.ActionBarOut; +import dev.loki.satura.util.ChatOut; +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.Supplier; +import net.minecraft.client.MinecraftClient; +import net.minecraft.util.math.BlockPos; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Фасад фичи «авто-билдер»: единственная точка входа для GUI, команд и рендера. */ +@SuppressWarnings({"PMD.AvoidCatchingGenericException", "PMD.GuardLogStatement"}) +public final class BuilderFeature implements BuildControl { + + private static final Logger LOG = LoggerFactory.getLogger(BuilderFeature.class); + + private final Selection current = new Selection(); + private final BuildSettings settings; + private final EngineAssembler assembler; + private final Consumer persist; + private BuildEngine engine; + + public BuilderFeature(final CommandRegistry commands, final Supplier feet, + final EngineAssembler assembler, final BuildSettings settings, + final Consumer persist) { + this.assembler = assembler; + this.settings = settings; + this.persist = persist; + commands.register(new PosCommand("pos1", current, feet, Selection::setPos1)); + commands.register(new PosCommand("pos2", current, feet, Selection::setPos2)); + commands.register(new SelCommand(current)); + commands.register(new BuildCommand(this)); + } + + /** Фасад на клиенте Minecraft; ходок «нет» (мост Baritone подключается через перегрузку). */ + public static BuilderFeature create(final CommandRegistry commands, final EventBus events, + final ConfigStore store) { + return create(commands, events, store, new NoWalker()); + } + + @SuppressWarnings("PMD.CloseResource") + public static BuilderFeature create(final CommandRegistry commands, final EventBus events, + final ConfigStore store, final Walker walker) { + final MinecraftClient client = MinecraftClient.getInstance(); + final BlockPlacer placer = new BlockPlacer(new SupportFinder(), new Cooldown()); + final List strategies = List.of(new BandStack(placer), new ColumnDrop(placer)); + final Profile profile = load(store); + return new BuilderFeature(commands, () -> client.player == null ? null : client.player.getBlockPos(), + new EngineAssembler(client, events, walker, new ChatOut(), new ActionBarOut()), + new BuildSettings(profile, strategies), p -> save(store, p)); + } + + public Selection selection() { + return current; + } + + /** Вызывать каждый клиентский тик. */ + public void tick() { + if (engine != null) { + engine.tick(); + } + } + + @Override + public String start() { + final Area area = current.area().orElseThrow(() -> new IllegalStateException("задай .pos1 и .pos2")); + stop(); + engine = assembler.assemble(settings, area); + engine.start(); + return "Старт: " + area.volume() + " блоков в области, стратегия " + settings.strategy().label(); + } + + @Override + public String pause() { + active().pause(); + return "Пауза"; + } + + @Override + public String resume() { + active().resume(); + return "Продолжаю"; + } + + @Override + public String stop() { + if (engine != null) { + engine.stop(); + } + return "Остановлено"; + } + + @Override + public String status() { + return engine == null ? "IDLE" : engine.snapshot().describe(); + } + + @Override + public String setBlock(final String id) { + assembler.blocks().resolve(id); + settings.setBlock(id); + return changed("Блок: " + id); + } + + @Override + public String setStrategy(final String id) { + settings.setStrategy(id); + return changed("Стратегия: " + id + ", параметры: " + settings.optionKeys()); + } + + @Override + public String setOption(final String key, final String value) { + settings.setOption(key, value); + return changed(key + " = " + value); + } + + @Override + public String setShape(final String id) { + settings.setShape(id); + return changed("Форма: " + settings.shapeId()); + } + + @Override + public String setLayers(final int layers) { + settings.setLayers(layers); + return changed("Слоёв за проход: " + layers); + } + + @Override + public List blockIds() { + return assembler.blocks().ids(); + } + + @Override + public List strategyIds() { + return settings.strategyIds(); + } + + @Override + public List optionKeys() { + return settings.optionKeys(); + } + + @Override + public List shapeIds() { + return settings.shapeIds(); + } + + private BuildEngine active() { + final Optional running = Optional.ofNullable(engine) + .filter(e -> e.stage() == Stage.BUILD || e.stage() == Stage.PAUSED); + return running.orElseThrow(() -> new IllegalStateException("билд не запущен")); + } + + private String changed(final String message) { + persist.accept(settings.toProfile(Profile.DEFAULT_NAME)); + return message; + } + + private static Profile load(final ConfigStore store) { + try { + return store.load(Profile.DEFAULT_NAME).orElse(Profile.empty(Profile.DEFAULT_NAME)); + } catch (IOException | RuntimeException e) { + LOG.warn("[satura] профиль не загружен: {}", e.toString()); + return Profile.empty(Profile.DEFAULT_NAME); + } + } + + private static void save(final ConfigStore store, final Profile profile) { + try { + store.save(profile); + } catch (IOException e) { + LOG.warn("[satura] профиль не сохранён: {}", e.toString()); + } + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/EngineAssembler.java b/src/main/java/dev/loki/satura/feature/builder/EngineAssembler.java new file mode 100644 index 0000000..b4ade9a --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/EngineAssembler.java @@ -0,0 +1,66 @@ +package dev.loki.satura.feature.builder; + +import dev.loki.satura.core.event.EventBus; +import dev.loki.satura.feature.builder.engine.BuildEngine; +import dev.loki.satura.feature.builder.engine.RepairTracker; +import dev.loki.satura.feature.builder.engine.host.EngineDeps; +import dev.loki.satura.feature.builder.engine.host.MinecraftBlocks; +import dev.loki.satura.feature.builder.engine.host.MinecraftGameState; +import dev.loki.satura.feature.builder.engine.walk.Walker; +import dev.loki.satura.feature.builder.plan.Planner; +import dev.loki.satura.feature.builder.scan.ColumnCache; +import dev.loki.satura.feature.builder.scan.WorldBlockProbe; +import dev.loki.satura.feature.builder.selection.Area; +import dev.loki.satura.interaction.click.ClickConfig; +import dev.loki.satura.interaction.click.ClickScheduler; +import dev.loki.satura.interaction.click.Clock; +import dev.loki.satura.interaction.inventory.HotbarRefill; +import dev.loki.satura.interaction.inventory.MinecraftInventoryView; +import dev.loki.satura.interaction.place.client.MinecraftPlaceContext; +import java.util.function.Consumer; +import java.util.random.RandomGenerator; +import net.minecraft.block.Block; +import net.minecraft.client.MinecraftClient; + +@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName") +/** Тонкий сборщик движка из настроек и клиента Minecraft. */ +public final class EngineAssembler { + + private final MinecraftClient client; + private final EventBus events; + private final Walker walker; + private final Consumer chat; + private final Consumer bar; + private final MinecraftBlocks blocks; + + public EngineAssembler(final MinecraftClient client, final EventBus events, final Walker walker, + final Consumer chat, final Consumer bar) { + this.client = client; + this.events = events; + this.walker = walker; + this.chat = chat; + this.bar = bar; + this.blocks = new MinecraftBlocks(client); + } + + public MinecraftBlocks blocks() { + return blocks; + } + + public BuildEngine assemble(final BuildSettings s, final Area area) { + if (client.player == null || client.world == null) { + throw new IllegalStateException("зайди в мир"); + } + final Block block = blocks.resolve(s.block()); + final ColumnCache cache = new ColumnCache(area, s.shape(), new WorldBlockProbe(() -> client.world)); + final RepairTracker tracker = new RepairTracker(RepairTracker.MAX_PASSES); + final Planner planner = new Planner(area, s.shape(), s.layers(), + pos -> cache.isDone(pos) || tracker.skipped(pos)); + final ClickScheduler clicks = new ClickScheduler(ClickConfig.DEFAULT, Clock.SYSTEM, + RandomGenerator.getDefault()); + final HotbarRefill refill = new HotbarRefill(new MinecraftInventoryView(client, block), clicks); + return new BuildEngine(new EngineDeps(planner, cache, tracker, s.strategy(), + new MinecraftPlaceContext(client), refill, clicks, new MinecraftGameState(client), + walker, Clock.SYSTEM, events, chat, bar)); + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneBridge.java b/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneBridge.java new file mode 100644 index 0000000..d49ebd0 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneBridge.java @@ -0,0 +1,105 @@ +package dev.loki.satura.feature.builder.baritone; + +import java.util.function.BooleanSupplier; +import net.fabricmc.loader.api.FabricLoader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Мост к Baritone (Aethereal): только рефлексия, любая ошибка отключает мост одной записью в лог. */ +@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.AvoidCatchingGenericException", "PMD.GuardLogStatement"}) +public final class BaritoneBridge implements WalkerPort { + + static final String MOD_ID = "baritone-meteor"; + private static final Logger LOG = LoggerFactory.getLogger(BaritoneBridge.class); + + private final BooleanSupplier modLoaded; + private BaritoneLink link; + private boolean initTried; + private boolean failed; + + public BaritoneBridge(BooleanSupplier modLoaded) { + this.modLoaded = modLoaded; + } + + public static BaritoneBridge create() { + return new BaritoneBridge(() -> FabricLoader.getInstance().isModLoaded(MOD_ID)); + } + + public boolean present() { + return link() != null; + } + + @Override + public boolean walkTo(double x, double z) { + BaritoneLink l = link(); + if (l == null) { + return false; + } + try { + l.walkTo((int) Math.floor(x), (int) Math.floor(z)); + return true; + } catch (ReflectiveOperationException | RuntimeException e) { + fail(e); + return false; + } + } + + @Override + public void cancel() { + BaritoneLink l = link(); + if (l == null) { + return; + } + try { + l.cancel(); + } catch (ReflectiveOperationException | RuntimeException e) { + fail(e); + } + } + + @Override + public boolean isActive() { + BaritoneLink l = link(); + if (l == null) { + return false; + } + try { + return l.isActive(); + } catch (ReflectiveOperationException | RuntimeException e) { + fail(e); + return false; + } + } + + private BaritoneLink link() { + if (failed) { + return null; + } + if (!initTried) { + initTried = true; + init(); + } + return failed ? null : link; + } + + private void init() { + if (!modLoaded.getAsBoolean()) { + failed = true; + return; + } + try { + BaritoneLink created = new BaritoneLink(BaritoneBridge.class.getClassLoader()); + created.applySettings(); + link = created; + } catch (ReflectiveOperationException | RuntimeException | LinkageError e) { + fail(e); + } + } + + private void fail(Throwable e) { + if (!failed) { + LOG.warn("Baritone bridge disabled: {}", e.toString()); + } + failed = true; + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneLink.java b/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneLink.java new file mode 100644 index 0000000..cc27fc9 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneLink.java @@ -0,0 +1,79 @@ +package dev.loki.satura.feature.builder.baritone; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.List; + +/** Кэш рефлексивных дескрипторов Baritone API; создаётся один раз. */ +final class BaritoneLink { + + private static final String PKG = "baritone.api."; + private static final List WALK_ONLY_FALSE = List.of("allowBreak", "allowPlace", "allowInventory"); + private static final List TRUE_FLAGS = List.of("freeLook", "allowSprint"); + + private final Method getProvider; + private final Method getPrimary; + private final Method customGoal; + private final Method pathingBehavior; + private final Method setGoal; + private final Method path; + private final Method processActive; + private final Method cancelEverything; + private final Constructor goalXz; + private final Object settings; + private final Field settingValue; + private final Class settingsClass; + + BaritoneLink(ClassLoader loader) throws ReflectiveOperationException { + Class api = Class.forName(PKG + "BaritoneAPI", true, loader); + Class baritone = Class.forName(PKG + "IBaritone", true, loader); + Class goal = Class.forName(PKG + "pathing.goals.Goal", true, loader); + Class goalProcess = Class.forName(PKG + "process.ICustomGoalProcess", true, loader); + Class process = Class.forName(PKG + "process.IBaritoneProcess", true, loader); + Class behavior = Class.forName(PKG + "behavior.IPathingBehavior", true, loader); + settingsClass = Class.forName(PKG + "Settings", true, loader); + getProvider = api.getMethod("getProvider"); + getPrimary = getProvider.getReturnType().getMethod("getPrimaryBaritone"); + customGoal = baritone.getMethod("getCustomGoalProcess"); + pathingBehavior = baritone.getMethod("getPathingBehavior"); + setGoal = goalProcess.getMethod("setGoal", goal); + path = goalProcess.getMethod("path"); + processActive = process.getMethod("isActive"); + cancelEverything = behavior.getMethod("cancelEverything"); + goalXz = Class.forName(PKG + "pathing.goals.GoalXZ", true, loader).getConstructor(int.class, int.class); + settings = api.getMethod("getSettings").invoke(null); + settingValue = Class.forName(PKG + "Settings$Setting", true, loader).getField("value"); + } + + void applySettings() throws ReflectiveOperationException { + for (String name : WALK_ONLY_FALSE) { + set(name, Boolean.FALSE); + } + for (String name : TRUE_FLAGS) { + set(name, Boolean.TRUE); + } + } + + void walkTo(int x, int z) throws ReflectiveOperationException { + Object process = customGoal.invoke(primary()); + setGoal.invoke(process, goalXz.newInstance(x, z)); + path.invoke(process); + } + + boolean isActive() throws ReflectiveOperationException { + return (Boolean) processActive.invoke(customGoal.invoke(primary())); + } + + void cancel() throws ReflectiveOperationException { + cancelEverything.invoke(pathingBehavior.invoke(primary())); + } + + private Object primary() throws ReflectiveOperationException { + return getPrimary.invoke(getProvider.invoke(null)); + } + + private void set(String name, Object value) throws ReflectiveOperationException { + settingValue.set(settingsClass.getField(name).get(settings), value); + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/baritone/WalkerPort.java b/src/main/java/dev/loki/satura/feature/builder/baritone/WalkerPort.java new file mode 100644 index 0000000..5ba9870 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/baritone/WalkerPort.java @@ -0,0 +1,12 @@ +package dev.loki.satura.feature.builder.baritone; + +/** Порт перемещения: движок видит только его, а не Baritone. */ +public interface WalkerPort { + + /** Начать путь к точке (x, z); false — ходок недоступен или команда не принята. */ + boolean walkTo(double x, double z); + + void cancel(); + + boolean isActive(); +} diff --git a/src/main/java/dev/loki/satura/feature/builder/commands/BuildCommand.java b/src/main/java/dev/loki/satura/feature/builder/commands/BuildCommand.java new file mode 100644 index 0000000..58eb341 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/commands/BuildCommand.java @@ -0,0 +1,55 @@ +package dev.loki.satura.feature.builder.commands; + +import dev.loki.satura.core.command.Command; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +/** {@code .build} — диспетчер подкоманд. */ +@SuppressWarnings("PMD.LooseCoupling") +public final class BuildCommand implements Command { + + private static final int NAME_ONLY = 1; + + private final Map subs = new LinkedHashMap<>(); + + public BuildCommand(final BuildControl control) { + for (final SubCommand sub : BuildSubs.of(control)) { + subs.put(sub.name(), sub); + } + } + + @Override + public String name() { + return "build"; + } + + @Override + public String description() { + return "билдер: " + String.join("|", subs.keySet()); + } + + @Override + public void execute(final List args, final Consumer reply) { + final SubCommand sub = args.isEmpty() ? null : subs.get(args.get(0).toLowerCase(Locale.ROOT)); + if (sub == null) { + reply.accept("Использование: .build " + subs.values().stream() + .map(s -> (s.name() + " " + s.usage()).strip()) + .collect(Collectors.joining(" | "))); + return; + } + reply.accept(sub.run().apply(args.subList(1, args.size()))); + } + + @Override + public List suggest(final List args) { + if (args.size() <= NAME_ONLY) { + return List.copyOf(subs.keySet()); + } + final SubCommand sub = subs.get(args.get(0).toLowerCase(Locale.ROOT)); + return sub == null ? List.of() : sub.options().apply(args.size() - 2); + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/commands/BuildControl.java b/src/main/java/dev/loki/satura/feature/builder/commands/BuildControl.java new file mode 100644 index 0000000..c7e18b0 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/commands/BuildControl.java @@ -0,0 +1,35 @@ +package dev.loki.satura.feature.builder.commands; + +import java.util.List; + +/** Что команды {@code .build} умеют просить у фичи. Ошибки — исключения с текстом для пользователя. */ +public interface BuildControl { + + String start(); + + String pause(); + + String resume(); + + String stop(); + + String status(); + + String setBlock(String id); + + String setStrategy(String id); + + String setOption(String key, String value); + + String setShape(String id); + + String setLayers(int layers); + + List blockIds(); + + List strategyIds(); + + List optionKeys(); + + List shapeIds(); +} diff --git a/src/main/java/dev/loki/satura/feature/builder/commands/BuildSubs.java b/src/main/java/dev/loki/satura/feature/builder/commands/BuildSubs.java new file mode 100644 index 0000000..890ca7d --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/commands/BuildSubs.java @@ -0,0 +1,51 @@ +package dev.loki.satura.feature.builder.commands; + +import java.util.List; + +/** Набор подкоманд {@code .build}, привязанных к {@link BuildControl}. */ +final class BuildSubs { + + private static final int SET_ARGS = 2; + private static final String LAYERS_USAGE = "слои: 1-3"; + + private BuildSubs() { + } + + static List of(final BuildControl c) { + return List.of( + SubCommand.plain("start", c::start), + SubCommand.plain("pause", c::pause), + SubCommand.plain("resume", c::resume), + SubCommand.plain("stop", c::stop), + SubCommand.plain("status", c::status), + SubCommand.value("block", () -> blockChoices(c), c::setBlock), + SubCommand.value("strategy", c::strategyIds, c::setStrategy), + SubCommand.value("shape", c::shapeIds, c::setShape), + SubCommand.value("layers", () -> List.of("1", "2", "3"), v -> c.setLayers(parse(v))), + set(c)); + } + + private static List blockChoices(final BuildControl c) { + final List ids = new java.util.ArrayList<>(c.blockIds()); + ids.add(0, "hand"); + return ids; + } + + private static int parse(final String v) { + try { + return Integer.parseInt(v); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(LAYERS_USAGE, e); + } + } + + private static SubCommand set(final BuildControl c) { + return new SubCommand("set", "<ключ> <значение>", i -> i == 0 ? c.optionKeys() : List.of(), args -> { + if (args.size() != SET_ARGS) { + throw new IllegalArgumentException("использование: .build set <ключ> <значение>; ключи: " + + c.optionKeys()); + } + return c.setOption(args.get(0), args.get(1)); + }); + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/commands/SubCommand.java b/src/main/java/dev/loki/satura/feature/builder/commands/SubCommand.java new file mode 100644 index 0000000..4dc615f --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/commands/SubCommand.java @@ -0,0 +1,32 @@ +package dev.loki.satura.feature.builder.commands; + +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * Подкоманда {@code .build }. + * + * @param usage справка по аргументам + * @param options кандидаты для подсказки по токену номер index (после имени) + * @param run выполнить с аргументами после имени, вернуть ответ + */ +public record SubCommand(String name, String usage, Function> options, + Function, String> run) { + + private static final int SINGLE_ARG = 1; + + public static SubCommand plain(final String name, final Supplier action) { + return new SubCommand(name, "", i -> List.of(), args -> action.get()); + } + + public static SubCommand value(final String name, final Supplier> choices, + final Function apply) { + return new SubCommand(name, "<значение>", i -> i == 0 ? choices.get() : List.of(), args -> { + if (args.size() != SINGLE_ARG) { + throw new IllegalArgumentException("нужно значение: .build " + name + " <значение>"); + } + return apply.apply(args.get(0)); + }); + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/BuildEngine.java b/src/main/java/dev/loki/satura/feature/builder/engine/BuildEngine.java new file mode 100644 index 0000000..191c732 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/engine/BuildEngine.java @@ -0,0 +1,153 @@ +package dev.loki.satura.feature.builder.engine; + +import dev.loki.satura.core.event.Listener; +import dev.loki.satura.core.event.world.BlockChangeEvent; +import dev.loki.satura.feature.builder.engine.host.EngineDeps; +import dev.loki.satura.feature.builder.plan.ColumnTarget; +import dev.loki.satura.interaction.inventory.HotbarRefill; +import dev.loki.satura.interaction.place.PlaceResult; +import java.util.Optional; + +@SuppressWarnings("PMD.CompareObjectsWithEquals") +/** + * Тик билдера: planner → стратегия → пополнение хотбара. Паузы (экран, смерть, смена мира) + * снимаются сами, «нет блоков» — только вручную. Дыры чинятся ремонтными проходами. + */ +public final class BuildEngine { + + public static final int PROGRESS_INTERVAL_TICKS = 20; + public static final String NO_BLOCKS = "нет блоков"; + + private final EngineDeps deps; + private final BuildSession session; + private final Listener blockListener; + private Object world; + private int ticks; + + public BuildEngine(final EngineDeps deps) { + this.deps = deps; + this.session = new BuildSession(deps.cache()); + this.blockListener = Listener.of(BlockChangeEvent.class, e -> deps.cache().onBlockChanged(e.pos())); + } + + public void start() { + deps.events().subscribe(blockListener); + world = deps.game().worldToken(); + deps.cache().fullRescan(); + session.start(); + } + + /** Ручная пауза: авто-резюм не сработает. */ + public void pause() { + if (session.stage() == Stage.BUILD || session.stage() == Stage.PAUSED) { + session.pause("пауза", false); + halt(); + } + } + + public void resume() { + if (session.stage() == Stage.PAUSED) { + session.resume(); + } + } + + public void stop() { + halt(); + deps.events().unsubscribe(blockListener); + session.stop(); + } + + public Stage stage() { + return session.stage(); + } + + public BuildSession.Snapshot snapshot() { + return session.snapshot(deps.tracker().holes()); + } + + public void tick() { + deps.clicks().tick(); + session.advance(deps.clock().nowMillis()); + switch (session.stage()) { + case BUILD -> build(); + case PAUSED -> tryAutoResume(); + default -> { } + } + ticks++; + if (ticks % PROGRESS_INTERVAL_TICKS == 0 && session.stage() != Stage.IDLE) { + deps.bar().accept(snapshot().describe()); + } + } + + private void tryAutoResume() { + if (session.autoResume() && deps.game().blockReason().isEmpty()) { + syncWorld(); + session.resume(); + } + } + + private void build() { + final Optional blocked = deps.game().blockReason(); + if (blocked.isPresent()) { + session.pause(blocked.get(), true); + return; + } + syncWorld(); + final HotbarRefill.State stock = deps.refill().tick(); + if (stock == HotbarRefill.State.EMPTY) { + session.pause(NO_BLOCKS, false); + deps.chat().accept("Пауза: " + NO_BLOCKS + ". Положи блоки и .build resume"); + } else if (stock == HotbarRefill.State.READY) { + deps.planner().next().ifPresentOrElse(this::place, this::finishOrRepair); + } + } + + private void syncWorld() { + final Object token = deps.game().worldToken(); + if (token != world) { + world = token; + deps.cache().fullRescan(); + } + } + + private void place(final ColumnTarget target) { + final var tracker = deps.tracker(); + tracker.observe(target.column(), deps.cache().done()); + session.at(target.column()); + final PlaceResult result = deps.strategy().tick(deps.ctx(), target); + final boolean giveUp = switch (result) { + case PLACED -> { + session.onPlaced(); + yield false; + } + case FAILED -> { + session.onFailed(); + yield tracker.failure(); + } + case WAIT -> tracker.stall(); + }; + if (giveUp) { + tracker.skip(target.column()); + } + } + + private void finishOrRepair() { + if (deps.tracker().startRepair(deps.planner())) { + deps.chat().accept("Ремонтный проход " + deps.tracker().passes() + ", дыр: " + + snapshot().holes()); + return; + } + final BuildSession.Snapshot shot = snapshot(); + session.finish(); + halt(); + deps.events().unsubscribe(blockListener); + deps.chat().accept("Готово: " + shot.done() + "/" + shot.total() + ", дыр: " + shot.holes()); + } + + private void halt() { + deps.walker().cancel(); + if (deps.game().blockReason().isEmpty()) { + deps.ctx().setVelocity(0, 0, 0); + } + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/BuildSession.java b/src/main/java/dev/loki/satura/feature/builder/engine/BuildSession.java new file mode 100644 index 0000000..61b56c8 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/engine/BuildSession.java @@ -0,0 +1,108 @@ +package dev.loki.satura.feature.builder.engine; + +import dev.loki.satura.feature.builder.scan.ColumnCache; +import java.util.Locale; +import java.util.Optional; +import net.minecraft.util.math.BlockPos; + +@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.NullAssignment"}) +/** Состояние сессии: этап, причина паузы, позиция, счётчики и статистика (прогресс — из ColumnCache). */ +public final class BuildSession { + + private static final long MAX_STEP_MS = 250; + private static final double MS_PER_SECOND = 1000.0; + + /** + * Снимок статистики. + * + * @param holes колонны, которые не удалось достроить + */ + public record Snapshot(Stage stage, String reason, int done, int total, double percent, int holes, + int placed, int failed, double blocksPerSecond, Optional column) { + + public String describe() { + final String why = stage == Stage.PAUSED ? " (" + reason + ")" : ""; + return String.format(Locale.ROOT, "%s%s %d/%d (%.1f%%), %.1f бл/с, дыр: %d", + stage, why, done, total, percent, blocksPerSecond, holes); + } + } + + private final ColumnCache cache; + private Stage stage = Stage.IDLE; + private String reason = ""; + private boolean autoResume; + private int placed; + private int failed; + private long activeMs; + private long lastTickMs = -1; + private BlockPos column; + + public BuildSession(final ColumnCache cache) { + this.cache = cache; + } + + public Stage stage() { + return stage; + } + + public boolean autoResume() { + return autoResume; + } + + public void start() { + stage = Stage.BUILD; + reason = ""; + placed = 0; + failed = 0; + activeMs = 0; + lastTickMs = -1; + column = null; + } + + public void pause(final String why, final boolean auto) { + stage = Stage.PAUSED; + reason = why; + autoResume = auto; + } + + public void resume() { + stage = Stage.BUILD; + reason = ""; + } + + public void finish() { + stage = Stage.DONE; + column = null; + } + + public void stop() { + stage = Stage.IDLE; + column = null; + } + + /** Учёт времени: считается только время в BUILD, паузы не входят. */ + public void advance(final long nowMs) { + if (stage == Stage.BUILD && lastTickMs >= 0) { + activeMs += Math.min(nowMs - lastTickMs, MAX_STEP_MS); + } + lastTickMs = nowMs; + } + + public void onPlaced() { + placed++; + } + + public void onFailed() { + failed++; + } + + public void at(final BlockPos target) { + column = target; + } + + public Snapshot snapshot(final int holes) { + final double rate = activeMs <= 0 ? 0.0 : placed * MS_PER_SECOND / activeMs; + return new Snapshot(stage, reason, cache.done(), cache.total(), cache.percent(), holes, + placed, failed, rate, Optional.ofNullable(column)); + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/RepairTracker.java b/src/main/java/dev/loki/satura/feature/builder/engine/RepairTracker.java new file mode 100644 index 0000000..7dba333 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/engine/RepairTracker.java @@ -0,0 +1,74 @@ +package dev.loki.satura.feature.builder.engine; + +import dev.loki.satura.feature.builder.plan.Planner; +import java.util.HashSet; +import java.util.Set; +import net.minecraft.util.math.BlockPos; + +@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName") +/** Дыры: колонны, которые не удалось достроить; пропуск, счётчики отказов и ремонтные проходы. */ +public final class RepairTracker { + + public static final int MAX_FAILURES = 3; + public static final int STALL_TICKS = 200; + public static final int MAX_PASSES = 3; + + private final Set skipped = new HashSet<>(); + private final int maxPasses; + private int passes; + private BlockPos column; + private int lastDone = -1; + private int failures; + private int waits; + + public RepairTracker(final int maxPasses) { + this.maxPasses = maxPasses; + } + + public boolean skipped(final BlockPos pos) { + return skipped.contains(pos.withY(0)); + } + + public int holes() { + return skipped.size(); + } + + public int passes() { + return passes; + } + + /** Сбрасывает счётчики, если сменилась колонна или прибавился прогресс. */ + public void observe(final BlockPos target, final int done) { + if (!target.equals(column) || done != lastDone) { + column = target; + lastDone = done; + failures = 0; + waits = 0; + } + } + + /** Отказ стратегии; true — лимит исчерпан. */ + public boolean failure() { + return ++failures >= MAX_FAILURES; + } + + /** Ожидание без прогресса; true — колонна зависла. */ + public boolean stall() { + return ++waits >= STALL_TICKS; + } + + public void skip(final BlockPos target) { + skipped.add(target.withY(0)); + } + + /** Ремонтный проход: вернуть пропущенные колонны в план; false — дыр нет или проходы кончились. */ + public boolean startRepair(final Planner planner) { + if (skipped.isEmpty() || passes >= maxPasses) { + return false; + } + passes++; + skipped.clear(); + planner.reset(); + return true; + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/Stage.java b/src/main/java/dev/loki/satura/feature/builder/engine/Stage.java new file mode 100644 index 0000000..62cf930 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/engine/Stage.java @@ -0,0 +1,11 @@ +package dev.loki.satura.feature.builder.engine; + +/** Этап сессии. TRANSIT и SUPPLY — точки расширения (переход к области, вылазка за блоками). */ +public enum Stage { + IDLE, + BUILD, + PAUSED, + DONE, + TRANSIT, + SUPPLY +} diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/host/EngineDeps.java b/src/main/java/dev/loki/satura/feature/builder/engine/host/EngineDeps.java new file mode 100644 index 0000000..b7881e9 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/engine/host/EngineDeps.java @@ -0,0 +1,26 @@ +package dev.loki.satura.feature.builder.engine.host; + +import dev.loki.satura.core.event.EventBus; +import dev.loki.satura.feature.builder.engine.RepairTracker; +import dev.loki.satura.feature.builder.engine.walk.Walker; +import dev.loki.satura.feature.builder.plan.Planner; +import dev.loki.satura.feature.builder.scan.ColumnCache; +import dev.loki.satura.interaction.click.ClickScheduler; +import dev.loki.satura.interaction.click.Clock; +import dev.loki.satura.interaction.inventory.HotbarRefill; +import dev.loki.satura.interaction.place.PlaceContext; +import dev.loki.satura.interaction.place.PlaceStrategy; +import java.util.function.Consumer; + +/** + * Все зависимости движка (собираются снаружи, движок ничего не создаёт сам). + * + * @param chat сообщения пользователю + * @param bar строка прогресса (actionBar) + */ +@SuppressWarnings("PMD.ExcessiveParameterList") +public record EngineDeps(Planner planner, ColumnCache cache, RepairTracker tracker, PlaceStrategy strategy, + PlaceContext ctx, HotbarRefill refill, ClickScheduler clicks, GameState game, + Walker walker, Clock clock, EventBus events, Consumer chat, + Consumer bar) { +} diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/host/GameState.java b/src/main/java/dev/loki/satura/feature/builder/engine/host/GameState.java new file mode 100644 index 0000000..693c0d4 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/engine/host/GameState.java @@ -0,0 +1,13 @@ +package dev.loki.satura.feature.builder.engine.host; + +import java.util.Optional; + +/** Состояние игры, влияющее на работу движка; отделяет движок от клиента Minecraft. */ +public interface GameState { + + /** Причина, по которой строить сейчас нельзя (экран, смерть, нет мира); пусто — можно. */ + Optional blockReason(); + + /** Токен текущего мира: смена токена = смена мира. */ + Object worldToken(); +} diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftBlocks.java b/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftBlocks.java new file mode 100644 index 0000000..f8b9e23 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftBlocks.java @@ -0,0 +1,45 @@ +package dev.loki.satura.feature.builder.engine.host; + +import java.util.List; +import net.minecraft.block.Block; +import net.minecraft.block.Blocks; +import net.minecraft.client.MinecraftClient; +import net.minecraft.item.BlockItem; +import net.minecraft.registry.Registries; +import net.minecraft.util.Identifier; + +/** Поиск блоков: по ID из реестра или по предмету в основной руке. */ +public final class MinecraftBlocks { + + public static final String HAND = "hand"; + + private final MinecraftClient client; + + public MinecraftBlocks(final MinecraftClient client) { + this.client = client; + } + + /** Блок по ID ({@code stone} или {@code minecraft:stone}) либо из руки при {@link #HAND}. */ + public Block resolve(final String id) { + if (HAND.equalsIgnoreCase(id)) { + return fromHand(); + } + final Identifier key = Identifier.tryParse(id.toLowerCase(java.util.Locale.ROOT)); + final Block block = key == null ? Blocks.AIR : Registries.BLOCK.get(key); + if (key == null || !Registries.BLOCK.containsId(key) || block == Blocks.AIR) { + throw new IllegalArgumentException("неизвестный блок: " + id); + } + return block; + } + + public List ids() { + return Registries.BLOCK.getIds().stream().map(Identifier::getPath).sorted().toList(); + } + + private Block fromHand() { + if (client.player != null && client.player.getMainHandStack().getItem() instanceof BlockItem item) { + return item.getBlock(); + } + throw new IllegalStateException("в руке нет блока"); + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftGameState.java b/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftGameState.java new file mode 100644 index 0000000..fcd275c --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftGameState.java @@ -0,0 +1,33 @@ +package dev.loki.satura.feature.builder.engine.host; + +import java.util.Optional; +import net.minecraft.client.MinecraftClient; + +/** Тонкий адаптер {@link GameState} к клиенту Minecraft. */ +public final class MinecraftGameState implements GameState { + + private final MinecraftClient client; + + public MinecraftGameState(final MinecraftClient client) { + this.client = client; + } + + @Override + public Optional blockReason() { + if (client.player == null || client.world == null) { + return Optional.of("нет мира"); + } + if (!client.player.isAlive()) { + return Optional.of("смерть"); + } + if (client.currentScreen != null) { + return Optional.of("открыт экран"); + } + return Optional.empty(); + } + + @Override + public Object worldToken() { + return client.world; + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/walk/NoWalker.java b/src/main/java/dev/loki/satura/feature/builder/engine/walk/NoWalker.java new file mode 100644 index 0000000..a5d8479 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/engine/walk/NoWalker.java @@ -0,0 +1,15 @@ +package dev.loki.satura.feature.builder.engine.walk; + +/** Ходок «нет»: ничего не умеет. */ +public final class NoWalker implements Walker { + + @Override + public boolean walkTo(final double x, final double z) { + return false; + } + + @Override + public void cancel() { + // нечего отменять + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/walk/Walker.java b/src/main/java/dev/loki/satura/feature/builder/engine/walk/Walker.java new file mode 100644 index 0000000..8ee432c --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/engine/walk/Walker.java @@ -0,0 +1,10 @@ +package dev.loki.satura.feature.builder.engine.walk; + +/** Ходок для наземных стратегий (S5/S6); мост к Baritone подключается позже. */ +public interface Walker { + + /** Начать путь к точке (x, z); false — ходок недоступен или команда не принята. */ + boolean walkTo(double x, double z); + + void cancel(); +} diff --git a/src/main/java/dev/loki/satura/feature/builder/plan/ColumnTarget.java b/src/main/java/dev/loki/satura/feature/builder/plan/ColumnTarget.java new file mode 100644 index 0000000..33a26d6 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/plan/ColumnTarget.java @@ -0,0 +1,12 @@ +package dev.loki.satura.feature.builder.plan; + +import java.util.List; +import net.minecraft.util.math.BlockPos; + +/** Колонна с ещё не построенными ячейками текущего Y-окна (по возрастанию Y). */ +public record ColumnTarget(BlockPos column, List cells) { + + public ColumnTarget { + cells = List.copyOf(cells); + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/plan/Planner.java b/src/main/java/dev/loki/satura/feature/builder/plan/Planner.java new file mode 100644 index 0000000..f752e9d --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/plan/Planner.java @@ -0,0 +1,70 @@ +package dev.loki.satura.feature.builder.plan; + +import dev.loki.satura.feature.builder.plan.shape.Shape; +import dev.loki.satura.feature.builder.selection.Area; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import net.minecraft.util.math.BlockPos; + +/** Режет область на Y-окна и отдаёт следующую недостроенную колонну по змейке. */ +public final class Planner { + + public static final int MIN_BAND_LAYERS = 1; + public static final int MAX_BAND_LAYERS = 3; + + private final Area area; + private final Shape shape; + private final int bandLayers; + private final Predicate done; + private final List columns; + private int bandFloor; + + public Planner(final Area area, final Shape shape, final int bandLayers, + final Predicate done) { + this.area = area; + this.shape = shape; + this.bandLayers = Math.max(MIN_BAND_LAYERS, Math.min(MAX_BAND_LAYERS, bandLayers)); + this.done = done; + this.columns = area.columns(); + this.bandFloor = area.min().getY(); + } + + /** Следующая цель; окно сдвигается вверх, когда текущее достроено. Пусто = всё готово. */ + public Optional next() { + final int top = area.max().getY(); + while (bandFloor <= top) { + final int bandEnd = Math.min(bandFloor + bandLayers - 1, top); + for (final BlockPos column : columns) { + final List pending = pending(column, bandFloor, bandEnd); + if (!pending.isEmpty()) { + return Optional.of(new ColumnTarget(column, pending)); + } + } + bandFloor = bandEnd + 1; + } + return Optional.empty(); + } + + /** Нижний Y текущего окна. */ + public int bandStart() { + return bandFloor; + } + + /** Вернуться к нижнему окну (для ремонтного прохода). */ + public void reset() { + bandFloor = area.min().getY(); + } + + private List pending(final BlockPos column, final int fromY, final int toY) { + final List cells = new ArrayList<>(); + for (int y = fromY; y <= toY; y++) { + final BlockPos pos = new BlockPos(column.getX(), y, column.getZ()); + if (shape.includes(area, pos) && !done.test(pos)) { + cells.add(pos); + } + } + return cells; + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/plan/shape/BoxShape.java b/src/main/java/dev/loki/satura/feature/builder/plan/shape/BoxShape.java new file mode 100644 index 0000000..8ed5a26 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/plan/shape/BoxShape.java @@ -0,0 +1,13 @@ +package dev.loki.satura.feature.builder.plan.shape; + +import dev.loki.satura.feature.builder.selection.Area; +import net.minecraft.util.math.BlockPos; + +/** Сплошной параллелепипед. */ +public final class BoxShape implements Shape { + + @Override + public boolean includes(final Area area, final BlockPos pos) { + return area.contains(pos); + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/plan/shape/CheckerShape.java b/src/main/java/dev/loki/satura/feature/builder/plan/shape/CheckerShape.java new file mode 100644 index 0000000..30e0eab --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/plan/shape/CheckerShape.java @@ -0,0 +1,18 @@ +package dev.loki.satura.feature.builder.plan.shape; + +import dev.loki.satura.feature.builder.selection.Area; +import net.minecraft.util.math.BlockPos; + +/** Шахматка: чётность x+z относительно угла min области. */ +public final class CheckerShape implements Shape { + + @Override + public boolean includes(final Area area, final BlockPos pos) { + if (!area.contains(pos)) { + return false; + } + final int dx = pos.getX() - area.min().getX(); + final int dz = pos.getZ() - area.min().getZ(); + return ((dx + dz) & 1) == 0; + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/plan/shape/Shape.java b/src/main/java/dev/loki/satura/feature/builder/plan/shape/Shape.java new file mode 100644 index 0000000..b35a763 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/plan/shape/Shape.java @@ -0,0 +1,10 @@ +package dev.loki.satura.feature.builder.plan.shape; + +import dev.loki.satura.feature.builder.selection.Area; +import net.minecraft.util.math.BlockPos; + +/** Какие ячейки области нужно строить. */ +public interface Shape { + + boolean includes(Area area, BlockPos pos); +} diff --git a/src/main/java/dev/loki/satura/feature/builder/plan/shape/WallsShape.java b/src/main/java/dev/loki/satura/feature/builder/plan/shape/WallsShape.java new file mode 100644 index 0000000..8d000b4 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/plan/shape/WallsShape.java @@ -0,0 +1,19 @@ +package dev.loki.satura.feature.builder.plan.shape; + +import dev.loki.satura.feature.builder.selection.Area; +import net.minecraft.util.math.BlockPos; + +/** Только внешний периметр (стены) по всей высоте. */ +public final class WallsShape implements Shape { + + @Override + public boolean includes(final Area area, final BlockPos pos) { + if (!area.contains(pos)) { + return false; + } + final int x = pos.getX(); + final int z = pos.getZ(); + return x == area.min().getX() || x == area.max().getX() + || z == area.min().getZ() || z == area.max().getZ(); + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/scan/BlockProbe.java b/src/main/java/dev/loki/satura/feature/builder/scan/BlockProbe.java new file mode 100644 index 0000000..a12834a --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/scan/BlockProbe.java @@ -0,0 +1,9 @@ +package dev.loki.satura.feature.builder.scan; + +import net.minecraft.util.math.BlockPos; + +/** Источник состояния блоков; отделяет подсчёт от клиента Minecraft. */ +public interface BlockProbe { + + boolean isFilled(BlockPos pos); +} diff --git a/src/main/java/dev/loki/satura/feature/builder/scan/ColumnCache.java b/src/main/java/dev/loki/satura/feature/builder/scan/ColumnCache.java new file mode 100644 index 0000000..0cdbe34 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/scan/ColumnCache.java @@ -0,0 +1,104 @@ +package dev.loki.satura.feature.builder.scan; + +import dev.loki.satura.feature.builder.plan.shape.Shape; +import dev.loki.satura.feature.builder.selection.Area; +import java.util.Arrays; +import net.minecraft.util.math.BlockPos; + +/** Инкрементальные счётчики заполненности по колоннам области (вместо полного X*Y*Z-скана). */ +public final class ColumnCache { + + private static final double PERCENT_FULL = 100.0; + + private final Area area; + private final Shape shape; + private final BlockProbe probe; + private final int[] built; + private final int[] required; + private int doneTotal; + private int requiredTotal; + + public ColumnCache(final Area area, final Shape shape, final BlockProbe probe) { + this.area = area; + this.shape = shape; + this.probe = probe; + final int columns = area.sizeX() * area.sizeZ(); + this.built = new int[columns]; + this.required = new int[columns]; + fullRescan(); + } + + /** Полный пересчёт всей области. */ + public void fullRescan() { + doneTotal = 0; + requiredTotal = 0; + Arrays.fill(built, 0); + Arrays.fill(required, 0); + for (final BlockPos column : area.columns()) { + recount(column.getX(), column.getZ()); + } + } + + /** Пересчитывает только колонну изменённого блока; вне области — игнор. */ + public void onBlockChanged(final BlockPos pos) { + if (area.contains(pos)) { + recount(pos.getX(), pos.getZ()); + } + } + + public boolean isDone(final BlockPos pos) { + return probe.isFilled(pos); + } + + public int done() { + return doneTotal; + } + + public int total() { + return requiredTotal; + } + + public int remaining() { + return requiredTotal - doneTotal; + } + + /** Построено клеток формы в колонне (x, z). */ + public int builtIn(final int x, final int z) { + return built[index(x, z)]; + } + + /** Осталось построить в колонне (x, z). */ + public int remainingIn(final int x, final int z) { + final int i = index(x, z); + return required[i] - built[i]; + } + + public double percent() { + return requiredTotal == 0 ? PERCENT_FULL : PERCENT_FULL * doneTotal / requiredTotal; + } + + private int index(final int x, final int z) { + return (z - area.min().getZ()) * area.sizeX() + (x - area.min().getX()); + } + + private void recount(final int x, final int z) { + final int i = index(x, z); + doneTotal -= built[i]; + requiredTotal -= required[i]; + int need = 0; + int have = 0; + for (int y = area.min().getY(); y <= area.max().getY(); y++) { + final BlockPos pos = new BlockPos(x, y, z); + if (shape.includes(area, pos)) { + need++; + if (probe.isFilled(pos)) { + have++; + } + } + } + required[i] = need; + built[i] = have; + requiredTotal += need; + doneTotal += have; + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/scan/WorldBlockProbe.java b/src/main/java/dev/loki/satura/feature/builder/scan/WorldBlockProbe.java new file mode 100644 index 0000000..a604b73 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/scan/WorldBlockProbe.java @@ -0,0 +1,27 @@ +package dev.loki.satura.feature.builder.scan; + +import java.util.function.Supplier; +import net.minecraft.block.BlockState; +import net.minecraft.client.world.ClientWorld; +import net.minecraft.util.math.BlockPos; + +/** Заполнено = не воздух и не заменяемое (трава, вода и т.п.). Мир берётся лениво. */ +@SuppressWarnings("PMD.CloseResource") +public final class WorldBlockProbe implements BlockProbe { + + private final Supplier world; + + public WorldBlockProbe(final Supplier world) { + this.world = world; + } + + @Override + public boolean isFilled(final BlockPos pos) { + final ClientWorld w = world.get(); + if (w == null) { + return false; + } + final BlockState state = w.getBlockState(pos); + return !state.isAir() && !state.isReplaceable(); + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/selection/Area.java b/src/main/java/dev/loki/satura/feature/builder/selection/Area.java new file mode 100644 index 0000000..59dc8b5 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/selection/Area.java @@ -0,0 +1,56 @@ +package dev.loki.satura.feature.builder.selection; + +import java.util.ArrayList; +import java.util.List; +import net.minecraft.util.math.BlockPos; + +/** Прямоугольная область мира (границы включительно). */ +public record Area(BlockPos min, BlockPos max) { + + private static final int EVEN_DIVISOR = 2; + + public static Area of(BlockPos a, BlockPos b) { + return new Area( + new BlockPos(Math.min(a.getX(), b.getX()), Math.min(a.getY(), b.getY()), + Math.min(a.getZ(), b.getZ())), + new BlockPos(Math.max(a.getX(), b.getX()), Math.max(a.getY(), b.getY()), + Math.max(a.getZ(), b.getZ()))); + } + + public boolean contains(BlockPos p) { + return p.getX() >= min.getX() && p.getX() <= max.getX() + && p.getY() >= min.getY() && p.getY() <= max.getY() + && p.getZ() >= min.getZ() && p.getZ() <= max.getZ(); + } + + public long volume() { + return (long) sizeX() * sizeY() * sizeZ(); + } + + public int sizeX() { + return max.getX() - min.getX() + 1; + } + + public int sizeY() { + return max.getY() - min.getY() + 1; + } + + public int sizeZ() { + return max.getZ() - min.getZ() + 1; + } + + /** Колонны на y = min.y: ряды по z, чётные ряды по x вверх, нечётные вниз. */ + public List columns() { + int sx = sizeX(); + int sz = sizeZ(); + List out = new ArrayList<>(sx * sz); + for (int r = 0; r < sz; r++) { + boolean forward = r % EVEN_DIVISOR == 0; + for (int i = 0; i < sx; i++) { + int dx = forward ? i : sx - 1 - i; + out.add(new BlockPos(min.getX() + dx, min.getY(), min.getZ() + r)); + } + } + return out; + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/selection/PosCommand.java b/src/main/java/dev/loki/satura/feature/builder/selection/PosCommand.java new file mode 100644 index 0000000..f73ebd8 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/selection/PosCommand.java @@ -0,0 +1,48 @@ +package dev.loki.satura.feature.builder.selection; + +import dev.loki.satura.core.command.Command; +import java.util.List; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; +import net.minecraft.util.math.BlockPos; + +/** {@code .pos1} / {@code .pos2} — запомнить позицию ног игрока. */ +public final class PosCommand implements Command { + + private final String label; + private final Supplier feet; + private final BiConsumer setter; + private final Selection selection; + + public PosCommand(String name, Selection selection, Supplier feet, + BiConsumer setter) { + this.label = name; + this.selection = selection; + this.feet = feet; + this.setter = setter; + } + + @Override + public String name() { + return label; + } + + @Override + public String description() { + return "запомнить позицию ног как " + label; + } + + @Override + public void execute(List args, Consumer reply) { + BlockPos pos = feet.get(); + if (pos == null) { + reply.accept("Нет игрока (зайди в мир)"); + return; + } + setter.accept(selection, pos); + reply.accept(label + " = " + pos.toShortString()); + selection.area().ifPresent(a -> reply.accept("Область: " + a.sizeX() + "x" + + a.sizeY() + "x" + a.sizeZ() + " (" + a.volume() + " блоков)")); + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/selection/SelCommand.java b/src/main/java/dev/loki/satura/feature/builder/selection/SelCommand.java new file mode 100644 index 0000000..8e53654 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/selection/SelCommand.java @@ -0,0 +1,42 @@ +package dev.loki.satura.feature.builder.selection; + +import dev.loki.satura.core.command.Command; +import java.util.List; +import java.util.function.Consumer; + +/** {@code .sel clear} — сбросить выделение. */ +public final class SelCommand implements Command { + + private static final String CLEAR = "clear"; + + private final Selection selection; + + public SelCommand(Selection selection) { + this.selection = selection; + } + + @Override + public String name() { + return "sel"; + } + + @Override + public String description() { + return "управление выделением: .sel clear"; + } + + @Override + public void execute(List args, Consumer reply) { + if (args.size() == 1 && CLEAR.equalsIgnoreCase(args.get(0))) { + selection.clear(); + reply.accept("Выделение сброшено"); + return; + } + reply.accept("Использование: .sel clear"); + } + + @Override + public List suggest(List args) { + return List.of(CLEAR); + } +} diff --git a/src/main/java/dev/loki/satura/feature/builder/selection/Selection.java b/src/main/java/dev/loki/satura/feature/builder/selection/Selection.java new file mode 100644 index 0000000..afeedc7 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/selection/Selection.java @@ -0,0 +1,40 @@ +package dev.loki.satura.feature.builder.selection; + +import java.util.Optional; +import net.minecraft.util.math.BlockPos; + +/** Две точки выделения; область существует, когда заданы обе. */ +public final class Selection { + + private Optional first = Optional.empty(); + private Optional second = Optional.empty(); + + public void setPos1(BlockPos pos) { + first = Optional.of(pos); + } + + public void setPos2(BlockPos pos) { + second = Optional.of(pos); + } + + public Optional pos1() { + return first; + } + + public Optional pos2() { + return second; + } + + public boolean isComplete() { + return first.isPresent() && second.isPresent(); + } + + public Optional area() { + return isComplete() ? Optional.of(Area.of(first.get(), second.get())) : Optional.empty(); + } + + public void clear() { + first = Optional.empty(); + second = Optional.empty(); + } +} diff --git a/src/main/java/dev/loki/satura/interaction/click/ClickConfig.java b/src/main/java/dev/loki/satura/interaction/click/ClickConfig.java new file mode 100644 index 0000000..e2e1df8 --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/click/ClickConfig.java @@ -0,0 +1,38 @@ +package dev.loki.satura.interaction.click; + +import java.util.random.RandomGenerator; + +/** + * Настройки темпа кликов по контейнерам. + * + * @param minDelayMs базовая пауза между кликами + * @param jitter доля случайного разброса паузы (0.3 = плюс-минус 30%) + * @param confirmTimeoutMs сколько ждать подтверждения клика до повтора + * @param maxAttempts сколько раз кликнуть, прежде чем сдаться + */ +public record ClickConfig(long minDelayMs, double jitter, long confirmTimeoutMs, int maxAttempts) { + + public static final long DEFAULT_DELAY_MS = 120; + public static final double DEFAULT_JITTER = 0.3; + public static final long DEFAULT_CONFIRM_TIMEOUT_MS = 1000; + public static final int DEFAULT_ATTEMPTS = 3; + + public static final ClickConfig DEFAULT = + new ClickConfig(DEFAULT_DELAY_MS, DEFAULT_JITTER, DEFAULT_CONFIRM_TIMEOUT_MS, DEFAULT_ATTEMPTS); + + public ClickConfig { + if (minDelayMs < 0 || jitter < 0 || jitter > 1 || confirmTimeoutMs <= 0 || maxAttempts < 1) { + throw new IllegalArgumentException("Bad click config"); + } + } + + public ClickConfig withDelay(long delayMs) { + return new ClickConfig(delayMs, jitter, confirmTimeoutMs, maxAttempts); + } + + /** Следующая пауза: minDelayMs * (1 +- jitter), равномерно. */ + public long nextDelay(RandomGenerator random) { + double factor = 1 + jitter * (2 * random.nextDouble() - 1); + return Math.round(minDelayMs * factor); + } +} diff --git a/src/main/java/dev/loki/satura/interaction/click/ClickScheduler.java b/src/main/java/dev/loki/satura/interaction/click/ClickScheduler.java new file mode 100644 index 0000000..31682db --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/click/ClickScheduler.java @@ -0,0 +1,100 @@ +package dev.loki.satura.interaction.click; + +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.random.RandomGenerator; + +/** + * Единая очередь контейнерных кликов: пауза с джиттером между кликами и подтверждение + * каждого клика по синхронизации слотов (таймаут, повтор). Тикается владельцем раз в тик. + */ +public final class ClickScheduler { + + private final Deque queue = new ArrayDeque<>(); + private final Clock clock; + private final RandomGenerator random; + private ClickConfig config; + private ClickTask current; + private boolean clicked; + private int attempts; + private long nextClickAt; + private long deadline; + + public ClickScheduler(ClickConfig config, Clock clock, RandomGenerator random) { + this.config = config; + this.clock = clock; + this.random = random; + } + + public void configure(ClickConfig newConfig) { + this.config = newConfig; + } + + public void submit(ClickTask task) { + queue.add(task); + } + + public boolean isIdle() { + return current == null && queue.isEmpty(); + } + + public int pending() { + return queue.size() + (current == null ? 0 : 1); + } + + /** Отложить следующий клик минимум на delayMs (пауза «человека» после открытия экрана). */ + public void delayNext(long delayMs) { + nextClickAt = Math.max(nextClickAt, clock.nowMillis() + delayMs); + } + + @SuppressWarnings("PMD.NullAssignment") + public void clear() { + queue.clear(); + current = null; + } + + public void tick() { + long now = clock.nowMillis(); + if (current == null) { + current = queue.poll(); + clicked = false; + attempts = 0; + } + if (current == null) { + return; + } + if (clicked) { + awaitConfirmation(now); + } else if (now >= nextClickAt) { + fire(now); + } + } + + private void fire(long now) { + attempts++; + clicked = true; + deadline = now + config.confirmTimeoutMs(); + current.click().run(); + } + + private void awaitConfirmation(long now) { + if (current.confirmed().getAsBoolean()) { + finish(now, ClickTask.Outcome.CONFIRMED); + } else if (now >= deadline) { + if (attempts >= config.maxAttempts()) { + finish(now, ClickTask.Outcome.FAILED); + } else { + clicked = false; + nextClickAt = now + config.nextDelay(random); + } + } + } + + @SuppressWarnings("PMD.NullAssignment") + private void finish(long now, ClickTask.Outcome outcome) { + ClickTask done = current; + current = null; + nextClickAt = now + config.nextDelay(random); + done.onDone().accept(outcome); + } +} diff --git a/src/main/java/dev/loki/satura/interaction/click/ClickTask.java b/src/main/java/dev/loki/satura/interaction/click/ClickTask.java new file mode 100644 index 0000000..730fed3 --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/click/ClickTask.java @@ -0,0 +1,21 @@ +package dev.loki.satura.interaction.click; + +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; + +/** + * Один клик по контейнеру. + * + * @param click действие клика (вызов clickSlot) + * @param confirmed true, когда результат клика виден в слотах (синхронизация пришла) + * @param onDone итог задачи + */ +public record ClickTask(Runnable click, BooleanSupplier confirmed, Consumer onDone) { + + /** Итог задачи. */ + public enum Outcome { CONFIRMED, FAILED } + + public static ClickTask of(Runnable click, BooleanSupplier confirmed) { + return new ClickTask(click, confirmed, outcome -> { }); + } +} diff --git a/src/main/java/dev/loki/satura/interaction/click/Clock.java b/src/main/java/dev/loki/satura/interaction/click/Clock.java new file mode 100644 index 0000000..aa47d97 --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/click/Clock.java @@ -0,0 +1,10 @@ +package dev.loki.satura.interaction.click; + +/** Источник времени; подменяется в тестах. */ +@FunctionalInterface +public interface Clock { + + Clock SYSTEM = System::currentTimeMillis; + + long nowMillis(); +} diff --git a/src/main/java/dev/loki/satura/interaction/inventory/HotbarRefill.java b/src/main/java/dev/loki/satura/interaction/inventory/HotbarRefill.java new file mode 100644 index 0000000..4cd846a --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/inventory/HotbarRefill.java @@ -0,0 +1,65 @@ +package dev.loki.satura.interaction.inventory; + +import dev.loki.satura.interaction.click.ClickScheduler; +import dev.loki.satura.interaction.click.ClickTask; + +/** + * Пополнение хотбара: когда в выбранном слоте осталось не больше порога, самый полный стак + * из инвентаря меняется с пустеющим слотом хотбара (SWAP) через общий ClickScheduler. + */ +public final class HotbarRefill { + + /** Порог: слот с таким или меньшим числом блоков считается пустым. */ + public static final int LOW = 2; + + /** Состояние пополнения. */ + public enum State { READY, REFILLING, EMPTY } + + private final InventoryView inventory; + private final ClickScheduler scheduler; + private final RefillPlanner planner; + private boolean swapPending; + + public HotbarRefill(InventoryView inventory, ClickScheduler scheduler) { + this(inventory, scheduler, LOW); + } + + public HotbarRefill(InventoryView inventory, ClickScheduler scheduler, int low) { + this.inventory = inventory; + this.scheduler = scheduler; + this.planner = new RefillPlanner(low); + } + + /** Один тик логики; сам планировщик кликов тикает владелец. */ + public State tick() { + if (swapPending) { + return State.REFILLING; + } + int[] counts = new int[InventoryView.SLOTS]; + for (int i = 0; i < counts.length; i++) { + counts[i] = inventory.count(i); + } + RefillPlanner.Decision decision = planner.plan(counts, inventory.selectedSlot()); + return switch (decision.kind()) { + case READY -> State.READY; + case SELECT -> select(decision.from()); + case SWAP -> swap(decision.from(), decision.to(), counts[decision.from()]); + case EMPTY -> State.EMPTY; + }; + } + + private State select(int slot) { + inventory.select(slot); + return State.READY; + } + + @SuppressWarnings("PMD.UnusedAssignment") + private State swap(int src, int dst, int movedCount) { + swapPending = true; + scheduler.submit(new ClickTask( + () -> inventory.swapToHotbar(src, dst), + () -> inventory.count(dst) == movedCount, + outcome -> swapPending = false)); + return State.REFILLING; + } +} diff --git a/src/main/java/dev/loki/satura/interaction/inventory/InventoryView.java b/src/main/java/dev/loki/satura/interaction/inventory/InventoryView.java new file mode 100644 index 0000000..77589cb --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/inventory/InventoryView.java @@ -0,0 +1,18 @@ +package dev.loki.satura.interaction.inventory; + +/** Вид на инвентарь игрока относительно целевого предмета. Слоты 0-8 хотбар, 9-35 инвентарь. */ +public interface InventoryView { + + int SLOTS = 36; + int HOTBAR_SIZE = 9; + + /** Сколько целевых предметов в слоте (0, если слот пуст или там другое). */ + int count(int slot); + + int selectedSlot(); + + void select(int slot); + + /** Клик SWAP: стак из слота инвентаря src меняется местами со слотом хотбара hotbarSlot. */ + void swapToHotbar(int src, int hotbarSlot); +} diff --git a/src/main/java/dev/loki/satura/interaction/inventory/MinecraftInventoryView.java b/src/main/java/dev/loki/satura/interaction/inventory/MinecraftInventoryView.java new file mode 100644 index 0000000..3dd3538 --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/inventory/MinecraftInventoryView.java @@ -0,0 +1,53 @@ +package dev.loki.satura.interaction.inventory; + +import net.minecraft.block.Block; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.network.ClientPlayerEntity; +import net.minecraft.item.BlockItem; +import net.minecraft.item.ItemStack; +import net.minecraft.screen.slot.SlotActionType; + +/** Тонкий адаптер к клиенту Minecraft: инвентарь игрока относительно одного блока. */ +public final class MinecraftInventoryView implements InventoryView { + + private final MinecraftClient client; + private final Block block; + + public MinecraftInventoryView(MinecraftClient client, Block block) { + this.client = client; + this.block = block; + } + + @Override + @SuppressWarnings("PMD.CompareObjectsWithEquals") + public int count(int slot) { + ClientPlayerEntity player = client.player; + if (player == null) { + return 0; + } + ItemStack stack = player.getInventory().getStack(slot); + boolean match = !stack.isEmpty() && stack.getItem() instanceof BlockItem item && item.getBlock() == block; + return match ? stack.getCount() : 0; + } + + @Override + public int selectedSlot() { + return client.player == null ? 0 : client.player.getInventory().getSelectedSlot(); + } + + @Override + public void select(int slot) { + if (client.player != null) { + client.player.getInventory().setSelectedSlot(slot); + } + } + + @Override + public void swapToHotbar(int src, int hotbarSlot) { + ClientPlayerEntity player = client.player; + if (player != null && client.interactionManager != null) { + client.interactionManager.clickSlot( + player.currentScreenHandler.syncId, src, hotbarSlot, SlotActionType.SWAP, player); + } + } +} diff --git a/src/main/java/dev/loki/satura/interaction/inventory/RefillPlanner.java b/src/main/java/dev/loki/satura/interaction/inventory/RefillPlanner.java new file mode 100644 index 0000000..6191f47 --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/inventory/RefillPlanner.java @@ -0,0 +1,63 @@ +package dev.loki.satura.interaction.inventory; + +/** Чистый выбор действия по заполненности слотов. */ +public final class RefillPlanner { + + /** Тип решения. */ + public enum Kind { READY, SELECT, SWAP, EMPTY } + + /** + * Решение: SELECT - выбрать хотбар-слот from; SWAP - обменять from (инвентарь) на to (хотбар). + */ + public record Decision(Kind kind, int from, int to) { + + static Decision of(Kind kind) { + return new Decision(kind, -1, -1); + } + } + + private final int low; + + public RefillPlanner(int low) { + this.low = low; + } + + public Decision plan(int[] counts, int selected) { + if (counts[selected] > low) { + return Decision.of(Kind.READY); + } + int best = fullest(counts, 0, InventoryView.HOTBAR_SIZE); + if (counts[best] > low) { + return new Decision(Kind.SELECT, best, -1); + } + int src = fullest(counts, InventoryView.HOTBAR_SIZE, InventoryView.SLOTS); + int dst = firstLow(counts); + if (counts[src] > 0 && dst >= 0 && counts[src] > counts[dst]) { + return new Decision(Kind.SWAP, src, dst); + } + if (counts[best] > 0) { + return new Decision(Kind.SELECT, best, -1); + } + return Decision.of(Kind.EMPTY); + } + + @SuppressWarnings("PMD.UseVarargs") + private int firstLow(int[] counts) { + for (int i = 0; i < InventoryView.HOTBAR_SIZE; i++) { + if (counts[i] <= low) { + return i; + } + } + return -1; + } + + private static int fullest(int[] counts, int from, int to) { + int best = from; + for (int i = from; i < to; i++) { + if (counts[i] > counts[best]) { + best = i; + } + } + return best; + } +} diff --git a/src/main/java/dev/loki/satura/interaction/movement/Angles.java b/src/main/java/dev/loki/satura/interaction/movement/Angles.java new file mode 100644 index 0000000..8647dbd --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/movement/Angles.java @@ -0,0 +1,44 @@ +package dev.loki.satura.interaction.movement; + +/** Чистая математика углов (градусы, система Minecraft). */ +public final class Angles { + + private static final float FULL_TURN = 360f; + private static final float HALF_TURN = 180f; + private static final float QUARTER_TURN = 90f; + + private Angles() { + } + + public static float wrap(float degrees) { + float d = degrees % FULL_TURN; + if (d >= HALF_TURN) { + d -= FULL_TURN; + } else if (d < -HALF_TURN) { + d += FULL_TURN; + } + return d; + } + + public static float yawTo(double dx, double dz) { + return (float) Math.toDegrees(Math.atan2(dz, dx)) - QUARTER_TURN; + } + + public static float pitchTo(double dy, double horizontal) { + float pitch = (float) -Math.toDegrees(Math.atan2(dy, horizontal)); + return Math.max(-QUARTER_TURN, Math.min(QUARTER_TURN, pitch)); + } + + public static float clamp(float value, float limit) { + return Math.max(-limit, Math.min(limit, value)); + } + + /** Шаг от current к target не больше maxStep по кратчайшей дуге. */ + public static float approachYaw(float current, float target, float maxStep) { + return current + clamp(wrap(target - current), maxStep); + } + + public static float approachPitch(float current, float target, float maxStep) { + return current + clamp(target - current, maxStep); + } +} diff --git a/src/main/java/dev/loki/satura/interaction/movement/LookController.java b/src/main/java/dev/loki/satura/interaction/movement/LookController.java new file mode 100644 index 0000000..9742665 --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/movement/LookController.java @@ -0,0 +1,41 @@ +package dev.loki.satura.interaction.movement; + +import dev.loki.satura.interaction.movement.io.PlayerPose; + +/** Управление взглядом: плавный доворот с клампом °/тик и мгновенный взгляд вниз. */ +public final class LookController { + + public static final float MAX_YAW_STEP = 25f; + public static final float MAX_PITCH_STEP = 20f; + public static final float SNAP_EPSILON = 0.4f; + public static final float DOWN_PITCH = 90f; + + private final PlayerPose pose; + + public LookController(PlayerPose pose) { + this.pose = pose; + } + + /** Доворот к точке за один тик; true, когда взгляд уже на цели. */ + public boolean lookAtSmooth(double x, double y, double z) { + double dx = x - pose.x(); + double dz = z - pose.z(); + float targetYaw = Angles.yawTo(dx, dz); + float targetPitch = Angles.pitchTo(y - pose.eyeY(), Math.hypot(dx, dz)); + float dYaw = Angles.wrap(targetYaw - pose.yaw()); + float dPitch = targetPitch - pose.pitch(); + if (Math.abs(dYaw) < SNAP_EPSILON && Math.abs(dPitch) < SNAP_EPSILON) { + pose.setYaw(targetYaw); + pose.setPitch(targetPitch); + return true; + } + pose.setYaw(Angles.approachYaw(pose.yaw(), targetYaw, MAX_YAW_STEP)); + pose.setPitch(Angles.approachPitch(pose.pitch(), targetPitch, MAX_PITCH_STEP)); + return false; + } + + /** Мгновенно смотреть строго вниз (для стратегий столбика/пола). */ + public void lookDown() { + pose.setPitch(DOWN_PITCH); + } +} diff --git a/src/main/java/dev/loki/satura/interaction/movement/MovementController.java b/src/main/java/dev/loki/satura/interaction/movement/MovementController.java new file mode 100644 index 0000000..e8ea604 --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/movement/MovementController.java @@ -0,0 +1,92 @@ +package dev.loki.satura.interaction.movement; + +import dev.loki.satura.interaction.movement.io.KeyInput; +import dev.loki.satura.interaction.movement.io.PlayerPose; + +/** Ходьба к точке фейк-клавишами: кламп поворота, прыжок на препятствии, сайдстеп при застревании. */ +public final class MovementController { + + public static final float MAX_TURN_STEP = 35f; + public static final float ALIGN_TOLERANCE = 45f; + public static final double ARRIVE_DIST_SQ = 0.09; + public static final double STUCK_MIN_MOVE_SQ = 0.0004; + public static final int STUCK_TICKS = 10; + public static final int SIDESTEP_TICKS = 8; + + private final KeyInput keys; + private final PlayerPose pose; + private double lastX = Double.NaN; + private double lastZ = Double.NaN; + private int stillTicks; + private int sidestepLeft; + private boolean sidestepRight = true; + + public MovementController(KeyInput keys, PlayerPose pose) { + this.keys = keys; + this.pose = pose; + } + + public void stop() { + keys.releaseAll(); + stillTicks = 0; + sidestepLeft = 0; + lastX = Double.NaN; + } + + public void sneak(boolean on) { + keys.setSneak(on); + } + + public void pillarKeys() { + keys.releaseAll(); + keys.setJump(true); + } + + /** Один тик ходьбы к (x, z); true, когда дошли (клавиши отпущены). */ + public boolean walkTo(double x, double z) { + double dx = x - pose.x(); + double dz = z - pose.z(); + if (dx * dx + dz * dz <= ARRIVE_DIST_SQ) { + stop(); + return true; + } + if (sidestepLeft > 0) { + sidestep(); + return false; + } + float target = Angles.yawTo(dx, dz); + pose.setYaw(Angles.approachYaw(pose.yaw(), target, MAX_TURN_STEP)); + boolean aligned = Math.abs(Angles.wrap(target - pose.yaw())) < ALIGN_TOLERANCE; + keys.releaseAll(); + keys.setForward(aligned); + keys.setJump(pose.horizontalCollision()); + trackStuck(aligned); + return false; + } + + private void sidestep() { + sidestepLeft--; + keys.releaseAll(); + keys.setLeft(!sidestepRight); + keys.setRight(sidestepRight); + keys.setJump(true); + if (sidestepLeft == 0) { + sidestepRight = !sidestepRight; + stillTicks = 0; + } + } + + private void trackStuck(boolean pushing) { + double moved = Double.isNaN(lastX) ? Double.MAX_VALUE : sq(pose.x() - lastX) + sq(pose.z() - lastZ); + lastX = pose.x(); + lastZ = pose.z(); + stillTicks = pushing && moved < STUCK_MIN_MOVE_SQ ? stillTicks + 1 : 0; + if (stillTicks >= STUCK_TICKS) { + sidestepLeft = SIDESTEP_TICKS; + } + } + + private static double sq(double v) { + return v * v; + } +} diff --git a/src/main/java/dev/loki/satura/interaction/movement/io/KeyInput.java b/src/main/java/dev/loki/satura/interaction/movement/io/KeyInput.java new file mode 100644 index 0000000..ae30e02 --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/movement/io/KeyInput.java @@ -0,0 +1,26 @@ +package dev.loki.satura.interaction.movement.io; + +/** Фейковые клавиши движения. */ +public interface KeyInput { + + void setForward(boolean pressed); + + void setBack(boolean pressed); + + void setLeft(boolean pressed); + + void setRight(boolean pressed); + + void setJump(boolean pressed); + + void setSneak(boolean pressed); + + default void releaseAll() { + setForward(false); + setBack(false); + setLeft(false); + setRight(false); + setJump(false); + setSneak(false); + } +} diff --git a/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftKeyInput.java b/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftKeyInput.java new file mode 100644 index 0000000..4648e68 --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftKeyInput.java @@ -0,0 +1,43 @@ +package dev.loki.satura.interaction.movement.io; + +import net.minecraft.client.MinecraftClient; + +/** Адаптер клавиш к настройкам клиента Minecraft. */ +public final class MinecraftKeyInput implements KeyInput { + + private final MinecraftClient client; + + public MinecraftKeyInput(MinecraftClient client) { + this.client = client; + } + + @Override + public void setForward(boolean pressed) { + client.options.forwardKey.setPressed(pressed); + } + + @Override + public void setBack(boolean pressed) { + client.options.backKey.setPressed(pressed); + } + + @Override + public void setLeft(boolean pressed) { + client.options.leftKey.setPressed(pressed); + } + + @Override + public void setRight(boolean pressed) { + client.options.rightKey.setPressed(pressed); + } + + @Override + public void setJump(boolean pressed) { + client.options.jumpKey.setPressed(pressed); + } + + @Override + public void setSneak(boolean pressed) { + client.options.sneakKey.setPressed(pressed); + } +} diff --git a/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftPlayerPose.java b/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftPlayerPose.java new file mode 100644 index 0000000..3b35b0d --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftPlayerPose.java @@ -0,0 +1,67 @@ +package dev.loki.satura.interaction.movement.io; + +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.network.ClientPlayerEntity; + +/** Адаптер позы к ClientPlayerEntity; без игрока (мир не загружен) работает как заглушка. */ +public final class MinecraftPlayerPose implements PlayerPose { + + private final MinecraftClient client; + + public MinecraftPlayerPose(MinecraftClient client) { + this.client = client; + } + + private ClientPlayerEntity player() { + return client.player; + } + + @Override + public double x() { + return player() == null ? 0 : player().getX(); + } + + @Override + public double y() { + return player() == null ? 0 : player().getY(); + } + + @Override + public double z() { + return player() == null ? 0 : player().getZ(); + } + + @Override + public double eyeY() { + return player() == null ? 0 : player().getEyeY(); + } + + @Override + public float yaw() { + return player() == null ? 0 : player().getYaw(); + } + + @Override + public float pitch() { + return player() == null ? 0 : player().getPitch(); + } + + @Override + public void setYaw(float yaw) { + if (player() != null) { + player().setYaw(yaw); + } + } + + @Override + public void setPitch(float pitch) { + if (player() != null) { + player().setPitch(pitch); + } + } + + @Override + public boolean horizontalCollision() { + return player() != null && player().horizontalCollision; + } +} diff --git a/src/main/java/dev/loki/satura/interaction/movement/io/PlayerPose.java b/src/main/java/dev/loki/satura/interaction/movement/io/PlayerPose.java new file mode 100644 index 0000000..5212441 --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/movement/io/PlayerPose.java @@ -0,0 +1,23 @@ +package dev.loki.satura.interaction.movement.io; + +/** Положение и взгляд игрока (градусы по Minecraft: yaw 0 = юг, pitch + вниз). */ +public interface PlayerPose { + + double x(); + + double y(); + + double z(); + + double eyeY(); + + float yaw(); + + float pitch(); + + void setYaw(float yaw); + + void setPitch(float pitch); + + boolean horizontalCollision(); +} diff --git a/src/main/java/dev/loki/satura/interaction/place/PlaceContext.java b/src/main/java/dev/loki/satura/interaction/place/PlaceContext.java new file mode 100644 index 0000000..7bedf56 --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/place/PlaceContext.java @@ -0,0 +1,33 @@ +package dev.loki.satura.interaction.place; + +import net.minecraft.util.hit.BlockHitResult; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; + +/** Всё, чем стратегия касается игры. Узкий интерфейс, чтобы логику можно было тестировать фейком. */ +public interface PlaceContext { + + /** Позиция ног игрока. */ + Vec3d feetPos(); + + /** Позиция глаз игрока. */ + Vec3d eyePos(); + + /** Годится ли блок как опора. */ + boolean isSolid(BlockPos pos); + + /** Клик ПКМ по блоку; true - клиент принял действие. */ + boolean interact(BlockHitResult hit); + + void swing(); + + /** Мгновенно взгляд строго вниз. */ + void lookDown(); + + void setVelocity(double x, double y, double z); + + /** Включить полёт, если он разрешён. */ + void enableFlight(); + + long nowMs(); +} diff --git a/src/main/java/dev/loki/satura/interaction/place/PlaceResult.java b/src/main/java/dev/loki/satura/interaction/place/PlaceResult.java new file mode 100644 index 0000000..6a496ff --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/place/PlaceResult.java @@ -0,0 +1,11 @@ +package dev.loki.satura.interaction.place; + +/** Итог одного тика стратегии. */ +public enum PlaceResult { + /** Блок поставлен в этом тике. */ + PLACED, + /** Ничего не делали: летим, кулдаун, ждём ответ сервера. */ + WAIT, + /** Цель сейчас не поставить (нет опоры / вне досягаемости): движок вправе пересчитать цель. */ + FAILED +} diff --git a/src/main/java/dev/loki/satura/interaction/place/PlaceStrategy.java b/src/main/java/dev/loki/satura/interaction/place/PlaceStrategy.java new file mode 100644 index 0000000..28a8e37 --- /dev/null +++ b/src/main/java/dev/loki/satura/interaction/place/PlaceStrategy.java @@ -0,0 +1,24 @@ +package dev.loki.satura.interaction.place; + +import dev.loki.satura.feature.builder.plan.ColumnTarget; +import dev.loki.satura.interaction.place.option.Option; +import dev.loki.satura.interaction.place.option.OptionValues; +import java.util.List; + +/** Способ ставить блоки в колонну. Движок вызывает {@link #tick} каждый тик, пока колонна не достроена. */ +public interface PlaceStrategy { + + /** Стабильный ключ для конфига. */ + String id(); + + /** Название для GUI. */ + String label(); + + /** Объявление параметров; GUI рисует их генерично. */ + List