From 2ae354f88897ee71aff6a4337d0e61147119418f Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Sat, 31 Oct 2026 21:07:57 +0100 Subject: [PATCH] Redesign GUI, surface-aware planning, edge-safe walking and /fly-aware flight - GUI: custom-rendered Satura screen (sidebar, pages, cards, sliders, status bar); old vanilla-widget screen removed; texts in lang files - Flight: constant height per Y window (default hover 2), eased velocity, flight enabled like a double jump (sends abilities update), pause when flight is unavailable (/fly hint) and auto-resume; default flySpeed 0.5 - Planner offers only cells with contact (below or side); unsupported cells wait - GroundWalk/BaritoneWalk walk to a stand block next to the cell, never off an edge (sneak guard); Baritone goal is a block instead of the target column - Profiles: named profiles, active profile persisted, .build profile, GUI page - MSDF fonts moved to assets/satura/msdf (vanilla tried to parse them as fonts) - Tests for stand finder, edge guard, planner support, flight, profiles --- config/checkstyle/suppressions.xml | 3 + config/pmd/pmd.xml | 4 +- .../loki/satura/core/config/ConfigStore.java | 43 +++- .../dev/loki/satura/core/config/Profile.java | 7 + .../loki/satura/core/config/ProfileBook.java | 22 ++ .../satura/feature/builder/BuildSettings.java | 23 +- .../feature/builder/BuilderFeature.java | 92 ++++---- .../feature/builder/EngineAssembler.java | 8 +- .../satura/feature/builder/Strategies.java | 60 ++++++ .../builder/baritone/BaritoneBridge.java | 15 ++ .../builder/baritone/BaritoneLink.java | 9 + .../feature/builder/baritone/WalkerPort.java | 5 + .../builder/commands/BuildControl.java | 6 + .../feature/builder/commands/BuildSubs.java | 1 + .../feature/builder/engine/BuildEngine.java | 16 +- .../builder/engine/host/GameState.java | 3 + .../engine/host/MinecraftGameState.java | 5 + .../feature/builder/engine/walk/Walker.java | 5 + .../satura/feature/builder/plan/Planner.java | 33 ++- .../java/dev/loki/satura/gui/BuilderUi.java | 4 +- .../dev/loki/satura/gui/page/BuildPage.java | 119 ++++++++++ .../java/dev/loki/satura/gui/page/Host.java | 18 ++ .../java/dev/loki/satura/gui/page/Page.java | 19 ++ .../dev/loki/satura/gui/page/PlacePage.java | 91 ++++++++ .../satura/gui/page/extra/ProfilesPage.java | 69 ++++++ .../satura/gui/page/extra/SupplyPage.java | 39 ++++ .../satura/gui/page/extra/ThemesPage.java | 54 +++++ .../loki/satura/gui/screen/BuilderScreen.java | 204 ------------------ .../java/dev/loki/satura/gui/screen/Nav.java | 60 ++++++ .../dev/loki/satura/gui/screen/Pages.java | 24 +++ .../dev/loki/satura/gui/screen/Panel.java | 62 ------ .../loki/satura/gui/screen/SaturaScreen.java | 168 +++++++++++++++ .../dev/loki/satura/gui/screen/Shell.java | 137 ++++++++++++ .../java/dev/loki/satura/gui/screen/Tab.java | 66 ------ .../satura/gui/screen/content/BuildTab.java | 135 ------------ .../satura/gui/screen/content/PlaceTab.java | 74 ------- .../satura/gui/screen/content/SupplyTab.java | 25 --- .../dev/loki/satura/gui/ui/core/Draw.java | 126 +++++++++++ .../dev/loki/satura/gui/ui/core/Palette.java | 42 ++++ .../java/dev/loki/satura/gui/ui/core/Tr.java | 19 ++ .../dev/loki/satura/gui/ui/core/Widget.java | 44 ++++ .../dev/loki/satura/gui/ui/input/TextBox.java | 114 ++++++++++ .../dev/loki/satura/gui/ui/layout/Flow.java | 53 +++++ .../dev/loki/satura/gui/ui/layout/Pane.java | 148 +++++++++++++ .../satura/gui/ui/widget/ActionButton.java | 70 ++++++ .../dev/loki/satura/gui/ui/widget/Card.java | 115 ++++++++++ .../dev/loki/satura/gui/ui/widget/Label.java | 51 +++++ .../loki/satura/gui/ui/widget/SliderBar.java | 102 +++++++++ .../loki/satura/gui/widget/CycleButton.java | 49 ----- .../loki/satura/gui/widget/NumberSlider.java | 56 ----- .../satura/interaction/movement/WalkPort.java | 5 + .../interaction/place/PlaceContext.java | 10 +- .../interaction/place/PlaceStrategy.java | 5 + .../place/client/MinecraftPlaceContext.java | 11 +- .../place/option/CommonOptions.java | 4 +- .../place/option/OptionValues.java | 5 + .../interaction/place/strategy/BandStack.java | 5 + .../place/strategy/ColumnDrop.java | 5 + .../place/strategy/ColumnPlacing.java | 7 +- .../place/strategy/FlightControl.java | 36 +++- .../place/strategy/ground/BaritoneWalk.java | 39 ++-- .../place/strategy/ground/GroundMove.java | 35 ++- .../place/strategy/ground/GroundWalk.java | 19 +- .../place/strategy/ground/StandFinder.java | 64 ++++++ .../place/strategy/manual/HoldRmb.java | 5 + .../place/strategy/precise/FlyHover.java | 5 + .../strategy/precise/PrecisePlacement.java | 16 +- .../place/target/ColumnTarget.java | 19 +- .../satura/render/msdf/MsdfFontLoader.java | 4 +- .../resources/assets/satura/lang/en_us.json | 81 +++++-- .../resources/assets/satura/lang/ru_ru.json | 81 +++++-- .../assets/satura/{font => msdf}/bold.json | 0 .../assets/satura/{font => msdf}/bold.png | Bin .../assets/satura/{font => msdf}/icons.json | 0 .../assets/satura/{font => msdf}/icons.png | Bin .../assets/satura/{font => msdf}/icons2.json | 0 .../assets/satura/{font => msdf}/icons2.png | Bin .../satura/{font => msdf}/montserrat.json | 0 .../satura/{font => msdf}/montserrat.png | Bin .../satura/core/config/ConfigStoreTest.java | 51 +++++ .../feature/builder/BuildSettingsTest.java | 55 +++++ .../builder/commands/BuildCommandTest.java | 7 +- .../feature/builder/engine/EngineHarness.java | 5 + .../feature/builder/plan/PlannerTest.java | 27 +++ .../place/strategy/StrategyTest.java | 34 +++ .../place/strategy/ground/GroundWalkTest.java | 56 ++++- .../strategy/ground/StandFinderTest.java | 58 +++++ .../place/strategy/precise/FlyHoverTest.java | 4 +- 88 files changed, 2652 insertions(+), 823 deletions(-) create mode 100644 src/main/java/dev/loki/satura/core/config/ProfileBook.java create mode 100644 src/main/java/dev/loki/satura/feature/builder/Strategies.java create mode 100644 src/main/java/dev/loki/satura/gui/page/BuildPage.java create mode 100644 src/main/java/dev/loki/satura/gui/page/Host.java create mode 100644 src/main/java/dev/loki/satura/gui/page/Page.java create mode 100644 src/main/java/dev/loki/satura/gui/page/PlacePage.java create mode 100644 src/main/java/dev/loki/satura/gui/page/extra/ProfilesPage.java create mode 100644 src/main/java/dev/loki/satura/gui/page/extra/SupplyPage.java create mode 100644 src/main/java/dev/loki/satura/gui/page/extra/ThemesPage.java delete mode 100644 src/main/java/dev/loki/satura/gui/screen/BuilderScreen.java create mode 100644 src/main/java/dev/loki/satura/gui/screen/Nav.java create mode 100644 src/main/java/dev/loki/satura/gui/screen/Pages.java delete mode 100644 src/main/java/dev/loki/satura/gui/screen/Panel.java create mode 100644 src/main/java/dev/loki/satura/gui/screen/SaturaScreen.java create mode 100644 src/main/java/dev/loki/satura/gui/screen/Shell.java delete mode 100644 src/main/java/dev/loki/satura/gui/screen/Tab.java delete mode 100644 src/main/java/dev/loki/satura/gui/screen/content/BuildTab.java delete mode 100644 src/main/java/dev/loki/satura/gui/screen/content/PlaceTab.java delete mode 100644 src/main/java/dev/loki/satura/gui/screen/content/SupplyTab.java create mode 100644 src/main/java/dev/loki/satura/gui/ui/core/Draw.java create mode 100644 src/main/java/dev/loki/satura/gui/ui/core/Palette.java create mode 100644 src/main/java/dev/loki/satura/gui/ui/core/Tr.java create mode 100644 src/main/java/dev/loki/satura/gui/ui/core/Widget.java create mode 100644 src/main/java/dev/loki/satura/gui/ui/input/TextBox.java create mode 100644 src/main/java/dev/loki/satura/gui/ui/layout/Flow.java create mode 100644 src/main/java/dev/loki/satura/gui/ui/layout/Pane.java create mode 100644 src/main/java/dev/loki/satura/gui/ui/widget/ActionButton.java create mode 100644 src/main/java/dev/loki/satura/gui/ui/widget/Card.java create mode 100644 src/main/java/dev/loki/satura/gui/ui/widget/Label.java create mode 100644 src/main/java/dev/loki/satura/gui/ui/widget/SliderBar.java delete mode 100644 src/main/java/dev/loki/satura/gui/widget/CycleButton.java delete mode 100644 src/main/java/dev/loki/satura/gui/widget/NumberSlider.java create mode 100644 src/main/java/dev/loki/satura/interaction/place/strategy/ground/StandFinder.java rename src/main/resources/assets/satura/{font => msdf}/bold.json (100%) rename src/main/resources/assets/satura/{font => msdf}/bold.png (100%) rename src/main/resources/assets/satura/{font => msdf}/icons.json (100%) rename src/main/resources/assets/satura/{font => msdf}/icons.png (100%) rename src/main/resources/assets/satura/{font => msdf}/icons2.json (100%) rename src/main/resources/assets/satura/{font => msdf}/icons2.png (100%) rename src/main/resources/assets/satura/{font => msdf}/montserrat.json (100%) rename src/main/resources/assets/satura/{font => msdf}/montserrat.png (100%) create mode 100644 src/test/java/dev/loki/satura/core/config/ConfigStoreTest.java create mode 100644 src/test/java/dev/loki/satura/feature/builder/BuildSettingsTest.java create mode 100644 src/test/java/dev/loki/satura/interaction/place/strategy/ground/StandFinderTest.java diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml index 9219648..3d3b8fe 100644 --- a/config/checkstyle/suppressions.xml +++ b/config/checkstyle/suppressions.xml @@ -9,4 +9,7 @@ + + diff --git a/config/pmd/pmd.xml b/config/pmd/pmd.xml index d3df49f..15221a6 100644 --- a/config/pmd/pmd.xml +++ b/config/pmd/pmd.xml @@ -7,7 +7,9 @@ Satura ruleset: errorprone, bestpractices, design, codestyle, performance, multithreading, security - + + + diff --git a/src/main/java/dev/loki/satura/core/config/ConfigStore.java b/src/main/java/dev/loki/satura/core/config/ConfigStore.java index 9c2f6be..6754e2d 100644 --- a/src/main/java/dev/loki/satura/core/config/ConfigStore.java +++ b/src/main/java/dev/loki/satura/core/config/ConfigStore.java @@ -10,16 +10,20 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Optional; +import java.util.Set; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Stores profiles as json files in a directory (config/satura/). */ @SuppressWarnings("PMD.GuardLogStatement") -public final class ConfigStore { +public final class ConfigStore implements ProfileBook { private static final Logger LOG = LoggerFactory.getLogger(ConfigStore.class); private static final String EXTENSION = ".json"; + private static final String ACTIVE_FILE = "active.txt"; + /** Settings files that share the directory but are not builder profiles. */ + private static final Set RESERVED = Set.of("render"); private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private final Path dir; @@ -45,7 +49,7 @@ public final class ConfigStore { } } - /** Loads the profile or an empty default; read errors never propagate to the caller. */ + @Override @SuppressWarnings({"PMD.AvoidCatchingGenericException", "PMD.CloseResource"}) public Profile loadOrEmpty(final String name) { try { @@ -56,7 +60,7 @@ public final class ConfigStore { } } - /** Saves the profile, swallowing I/O errors (for GUI/click handlers that cannot throw). */ + @Override public void saveQuietly(final Profile profile) { try { save(profile); @@ -78,7 +82,40 @@ public final class ConfigStore { } } + @Override + public List names() { + try { + return list().stream().filter(n -> !RESERVED.contains(n)).toList(); + } catch (IOException e) { + LOG.warn("[satura] profile list not read: {}", e.toString()); + return List.of(); + } + } + + @Override + public String active() { + try { + final String name = Files.readString(dir.resolve(ACTIVE_FILE), StandardCharsets.UTF_8).strip(); + return Profile.isValidName(name) ? name : Profile.DEFAULT_NAME; + } catch (IOException e) { + return Profile.DEFAULT_NAME; + } + } + + @Override + public void activate(String name) { + try { + Files.createDirectories(dir); + Files.writeString(dir.resolve(ACTIVE_FILE), name, StandardCharsets.UTF_8); + } catch (IOException e) { + LOG.warn("[satura] active profile not saved: {}", e.toString()); + } + } + private Path file(String name) { + if (!Profile.isValidName(name)) { + throw new IllegalArgumentException("bad profile name: " + 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 index fe091d9..fa77baf 100644 --- a/src/main/java/dev/loki/satura/core/config/Profile.java +++ b/src/main/java/dev/loki/satura/core/config/Profile.java @@ -2,6 +2,7 @@ package dev.loki.satura.core.config; import java.util.HashMap; import java.util.Map; +import java.util.regex.Pattern; /** * Immutable settings profile. @@ -13,11 +14,17 @@ import java.util.Map; public record Profile(String name, Map settings) { public static final String DEFAULT_NAME = "default"; + private static final Pattern VALID_NAME = Pattern.compile("[a-z0-9_-]{1,32}"); public Profile { settings = Map.copyOf(settings); } + /** Profile names double as file names: lowercase letters, digits, '_' and '-', up to 32 chars. */ + public static boolean isValidName(String name) { + return VALID_NAME.matcher(name).matches(); + } + public static Profile empty(String name) { return new Profile(name, Map.of()); } diff --git a/src/main/java/dev/loki/satura/core/config/ProfileBook.java b/src/main/java/dev/loki/satura/core/config/ProfileBook.java new file mode 100644 index 0000000..fac3a54 --- /dev/null +++ b/src/main/java/dev/loki/satura/core/config/ProfileBook.java @@ -0,0 +1,22 @@ +package dev.loki.satura.core.config; + +import java.util.List; + +/** Named settings profiles plus the choice of the active one; consumers never touch files. */ +public interface ProfileBook { + + /** Names of all stored profiles, sorted. */ + List names(); + + /** Name of the profile used at start; {@link Profile#DEFAULT_NAME} until another is activated. */ + String active(); + + /** Remembers the profile to load at the next start. */ + void activate(String name); + + /** Loads the profile, or an empty one if it does not exist or cannot be read. */ + Profile loadOrEmpty(String name); + + /** Stores the profile; failures are logged, never thrown. */ + void saveQuietly(Profile profile); +} diff --git a/src/main/java/dev/loki/satura/feature/builder/BuildSettings.java b/src/main/java/dev/loki/satura/feature/builder/BuildSettings.java index 65fa9cd..f1d7a08 100644 --- a/src/main/java/dev/loki/satura/feature/builder/BuildSettings.java +++ b/src/main/java/dev/loki/satura/feature/builder/BuildSettings.java @@ -16,7 +16,7 @@ import java.util.Map; import java.util.Optional; /** Builder settings; read from and serialized back into a {@link Profile}. */ -@SuppressWarnings({"PMD.LooseCoupling", "PMD.AvoidFieldNameMatchingMethodName"}) +@SuppressWarnings({"PMD.LooseCoupling", }) public final class BuildSettings { /** Range and current value of a strategy parameter, for a GUI slider. */ @@ -28,6 +28,10 @@ public final class BuildSettings { double min, double max, double step, double value) { } + /** GUI-facing strategy description: id, label and whether it needs flight. */ + public record StrategyInfo(String id, String label, boolean flight) { + } + static final String KEY_BLOCK = "block"; static final String KEY_SHAPE = "shape"; static final String KEY_LAYERS = "layers"; @@ -62,12 +66,20 @@ public final class BuildSettings { for (final PlaceStrategy s : available) { strategies.put(s.id(), s); } + apply(profile); + } + + /** Replaces every setting with the profile's; missing keys fall back to the defaults. */ + public void apply(final Profile profile) { 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(); + ? profile.get(KEY_STRATEGY, "") : strategies.keySet().iterator().next(); layers = parseLayers(profile.get(KEY_LAYERS, "2")); - strategies.values().forEach(s -> loadOptions(profile, s)); + strategies.values().forEach(s -> { + s.values().reset(); + loadOptions(profile, s); + }); } public String block() { @@ -104,6 +116,11 @@ public final class BuildSettings { return List.copyOf(strategies.keySet()); } + public List strategyInfos() { + return strategies.values().stream() + .map(s -> new StrategyInfo(s.id(), s.label(), s.needsFlight())).toList(); + } + public void setStrategy(final String id) { require(strategies.containsKey(id), "стратегия: " + strategyIds()); strategy = id; diff --git a/src/main/java/dev/loki/satura/feature/builder/BuilderFeature.java b/src/main/java/dev/loki/satura/feature/builder/BuilderFeature.java index 6021a36..545e06f 100644 --- a/src/main/java/dev/loki/satura/feature/builder/BuilderFeature.java +++ b/src/main/java/dev/loki/satura/feature/builder/BuilderFeature.java @@ -3,10 +3,12 @@ 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.config.ProfileBook; 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.BuildSession; 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; @@ -14,30 +16,13 @@ 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.movement.MovementController; -import dev.loki.satura.interaction.movement.WalkPort; -import dev.loki.satura.interaction.movement.io.MinecraftKeyInput; -import dev.loki.satura.interaction.movement.io.MinecraftPlayerPose; 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.strategy.ground.BaritoneWalk; -import dev.loki.satura.interaction.place.strategy.ground.GroundMove; -import dev.loki.satura.interaction.place.strategy.ground.GroundWalk; -import dev.loki.satura.interaction.place.strategy.manual.BurstPlace; -import dev.loki.satura.interaction.place.strategy.manual.HoldRmb; -import dev.loki.satura.interaction.place.strategy.precise.FlyHover; -import dev.loki.satura.interaction.place.strategy.precise.PrecisePlacement; -import dev.loki.satura.interaction.place.strategy.precise.PreciseSupport; -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.util.List; import java.util.Optional; -import java.util.function.Consumer; import java.util.function.Supplier; +import java.util.stream.Stream; import net.minecraft.client.MinecraftClient; import net.minecraft.util.math.BlockPos; @@ -48,15 +33,17 @@ public final class BuilderFeature implements BuildControl { private final Selection current = new Selection(); private final BuildSettings settings; private final EngineAssembler assembler; - private final Consumer persist; + private final ProfileBook profiles; + private String profileName; private BuildEngine engine; public BuilderFeature(final CommandRegistry commands, final Supplier feet, final EngineAssembler assembler, final BuildSettings settings, - final Consumer persist) { + final ProfileBook profiles) { this.assembler = assembler; this.settings = settings; - this.persist = persist; + this.profiles = profiles; + this.profileName = profiles.active(); commands.register(new PosCommand("pos1", current, feet, Selection::setPos1)); commands.register(new PosCommand("pos2", current, feet, Selection::setPos2)); commands.register(new SelCommand(current)); @@ -69,34 +56,13 @@ public final class BuilderFeature implements BuildControl { 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 PreciseSupport precise = new PreciseSupport(); - final BlockPlacer precisePlacer = new BlockPlacer(precise, new Cooldown()); - final GroundMove ground = new GroundMove(new MovementController( - new MinecraftKeyInput(client), new MinecraftPlayerPose(client))); - final WalkPort port = new WalkPort() { - @Override - public boolean walkTo(final double x, final double z) { - return walker.walkTo(x, z); - } - - @Override - public void cancel() { - walker.cancel(); - } - }; - final List strategies = List.of( - new BandStack(placer), new ColumnDrop(placer), - new PrecisePlacement(precisePlacer), new FlyHover(precise, precisePlacer), - new GroundWalk(ground, placer), new BaritoneWalk(port, precisePlacer), - new HoldRmb(placer), new BurstPlace(precise)); + final List strategies = Strategies.create(client, walker); return new BuilderFeature(commands, () -> client.player == null ? null : client.player.getBlockPos(), new EngineAssembler(client, events, walker, new ChatOut(), new ActionBarOut()), - new BuildSettings(store.loadOrEmpty(Profile.DEFAULT_NAME), strategies), store::saveQuietly); + new BuildSettings(store.loadOrEmpty(store.active()), strategies), store); } public Selection selection() { @@ -141,7 +107,13 @@ public final class BuilderFeature implements BuildControl { @Override public String status() { - return engine == null ? "IDLE" : engine.snapshot().describe(); + final String progress = engine == null ? Stage.IDLE.name() : engine.snapshot().describe(); + return settings.strategy().id() + " | " + progress; + } + + /** Live statistics of the running or finished build; empty before the first start. */ + public Optional progress() { + return engine == null ? Optional.empty() : Optional.of(engine.snapshot()); } /** Session stage, for GUI labels (the Pause/Resume button). */ @@ -203,6 +175,34 @@ public final class BuilderFeature implements BuildControl { return changed(settings.applyPreset(id)); } + @Override + public List profileIds() { + final List names = profiles.names(); + return names.contains(profileName) ? names : Stream.concat(Stream.of(profileName), names.stream()).toList(); + } + + @Override + public String profile() { + return profileName; + } + + /** Loads the named profile, or creates it from the current settings if it does not exist yet. */ + @Override + public String switchProfile(final String id) { + if (!Profile.isValidName(id)) { + throw new IllegalArgumentException("имя профиля: a-z, 0-9, _ и -, до 32 символов"); + } + final boolean exists = profiles.names().contains(id); + if (exists) { + settings.apply(profiles.loadOrEmpty(id)); + } else { + profiles.saveQuietly(settings.toProfile(id)); + } + profileName = id; + profiles.activate(id); + return (exists ? "Профиль: " : "Профиль создан: ") + id; + } + @Override public List blockIds() { return assembler.blocks().ids(); @@ -230,7 +230,7 @@ public final class BuilderFeature implements BuildControl { } private String changed(final String message) { - persist.accept(settings.toProfile(Profile.DEFAULT_NAME)); + profiles.saveQuietly(settings.toProfile(profileName)); return message; } } diff --git a/src/main/java/dev/loki/satura/feature/builder/EngineAssembler.java b/src/main/java/dev/loki/satura/feature/builder/EngineAssembler.java index d972c9c..411eea1 100644 --- a/src/main/java/dev/loki/satura/feature/builder/EngineAssembler.java +++ b/src/main/java/dev/loki/satura/feature/builder/EngineAssembler.java @@ -21,6 +21,7 @@ import java.util.function.Consumer; import java.util.random.RandomGenerator; import net.minecraft.block.Block; import net.minecraft.client.MinecraftClient; +import net.minecraft.util.math.BlockPos; /** Thin assembler of the engine from settings and the Minecraft client. */ @SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName") @@ -43,6 +44,11 @@ public final class EngineAssembler { this.blocks = new MinecraftBlocks(client); } + private boolean solid(final BlockPos pos) { + final var world = client.world; + return world != null && world.getBlockState(pos).isSolidBlock(world, pos); + } + public MinecraftBlocks blocks() { return blocks; } @@ -55,7 +61,7 @@ public final class EngineAssembler { 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)); + pos -> cache.isDone(pos) || tracker.skipped(pos), this::solid); final ClickScheduler clicks = new ClickScheduler(ClickConfig.DEFAULT, Clock.SYSTEM, RandomGenerator.getDefault()); final HotbarRefill refill = new HotbarRefill(new MinecraftInventoryView(client, block), clicks); diff --git a/src/main/java/dev/loki/satura/feature/builder/Strategies.java b/src/main/java/dev/loki/satura/feature/builder/Strategies.java new file mode 100644 index 0000000..0e7cf59 --- /dev/null +++ b/src/main/java/dev/loki/satura/feature/builder/Strategies.java @@ -0,0 +1,60 @@ +package dev.loki.satura.feature.builder; + +import dev.loki.satura.feature.builder.engine.walk.Walker; +import dev.loki.satura.interaction.movement.MovementController; +import dev.loki.satura.interaction.movement.WalkPort; +import dev.loki.satura.interaction.movement.io.MinecraftKeyInput; +import dev.loki.satura.interaction.movement.io.MinecraftPlayerPose; +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.strategy.ground.BaritoneWalk; +import dev.loki.satura.interaction.place.strategy.ground.GroundMove; +import dev.loki.satura.interaction.place.strategy.ground.GroundWalk; +import dev.loki.satura.interaction.place.strategy.manual.BurstPlace; +import dev.loki.satura.interaction.place.strategy.manual.HoldRmb; +import dev.loki.satura.interaction.place.strategy.precise.FlyHover; +import dev.loki.satura.interaction.place.strategy.precise.PrecisePlacement; +import dev.loki.satura.interaction.place.strategy.precise.PreciseSupport; +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 java.util.List; +import net.minecraft.client.MinecraftClient; + +/** Assembles every placement strategy on the Minecraft client; the first one is the default. */ +final class Strategies { + + private Strategies() { + } + + @SuppressWarnings("PMD.CloseResource") + static List create(final MinecraftClient client, final Walker walker) { + final BlockPlacer placer = new BlockPlacer(new SupportFinder(), new Cooldown()); + final PreciseSupport precise = new PreciseSupport(); + final BlockPlacer precisePlacer = new BlockPlacer(precise, new Cooldown()); + final GroundMove ground = new GroundMove(new MovementController( + new MinecraftKeyInput(client), new MinecraftPlayerPose(client))); + final WalkPort port = new WalkPort() { + @Override + public boolean walkTo(final double x, final double z) { + return walker.walkTo(x, z); + } + + @Override + public boolean walkToBlock(final int x, final int y, final int z) { + return walker.walkToBlock(x, y, z); + } + + @Override + public void cancel() { + walker.cancel(); + } + }; + return List.of( + new BandStack(placer), new ColumnDrop(placer), + new PrecisePlacement(precisePlacer), new FlyHover(precise, precisePlacer), + new GroundWalk(ground, placer), new BaritoneWalk(port, precisePlacer), + new HoldRmb(placer), new BurstPlace(precise)); + } +} 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 index cfb9d4f..e5b54e0 100644 --- a/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneBridge.java +++ b/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneBridge.java @@ -49,6 +49,21 @@ public final class BaritoneBridge implements WalkerPort, Walker { } } + @Override + public boolean walkToBlock(int x, int y, int z) { + BaritoneLink l = link(); + if (l == null) { + return false; + } + try { + l.walkToBlock(x, y, z); + return true; + } catch (ReflectiveOperationException | RuntimeException e) { + fail(e); + return false; + } + } + @Override public void cancel() { BaritoneLink l = link(); 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 index 991537a..d1f1443 100644 --- a/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneLink.java +++ b/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneLink.java @@ -21,6 +21,7 @@ final class BaritoneLink { private final Method processActive; private final Method cancelEverything; private final Constructor goalXz; + private final Constructor goalBlock; private final Object settings; private final Field settingValue; private final Class settingsClass; @@ -42,6 +43,8 @@ final class BaritoneLink { processActive = process.getMethod("isActive"); cancelEverything = behavior.getMethod("cancelEverything"); goalXz = Class.forName(PKG + "pathing.goals.GoalXZ", true, loader).getConstructor(int.class, int.class); + goalBlock = Class.forName(PKG + "pathing.goals.GoalBlock", true, loader) + .getConstructor(int.class, int.class, int.class); settings = api.getMethod("getSettings").invoke(null); settingValue = Class.forName(PKG + "Settings$Setting", true, loader).getField("value"); } @@ -61,6 +64,12 @@ final class BaritoneLink { path.invoke(process); } + void walkToBlock(int x, int y, int z) throws ReflectiveOperationException { + Object process = customGoal.invoke(primary()); + setGoal.invoke(process, goalBlock.newInstance(x, y, z)); + path.invoke(process); + } + boolean isActive() throws ReflectiveOperationException { return (Boolean) processActive.invoke(customGoal.invoke(primary())); } 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 index af02c05..c7e0a9a 100644 --- a/src/main/java/dev/loki/satura/feature/builder/baritone/WalkerPort.java +++ b/src/main/java/dev/loki/satura/feature/builder/baritone/WalkerPort.java @@ -6,6 +6,11 @@ public interface WalkerPort { /** Start a path to point (x, z); false if the walker is unavailable or the command was rejected. */ boolean walkTo(double x, double z); + /** Start a path to stand exactly in the given block; false if unavailable or rejected. */ + default boolean walkToBlock(final int x, final int y, final int z) { + return false; + } + void cancel(); boolean isActive(); 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 index 7c1d390..b15d4ac 100644 --- a/src/main/java/dev/loki/satura/feature/builder/commands/BuildControl.java +++ b/src/main/java/dev/loki/satura/feature/builder/commands/BuildControl.java @@ -29,6 +29,12 @@ public interface BuildControl { String applyPreset(String id); + List profileIds(); + + String profile(); + + String switchProfile(String id); + List blockIds(); List strategyIds(); 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 index 625e3f9..386b5e9 100644 --- a/src/main/java/dev/loki/satura/feature/builder/commands/BuildSubs.java +++ b/src/main/java/dev/loki/satura/feature/builder/commands/BuildSubs.java @@ -23,6 +23,7 @@ final class BuildSubs { SubCommand.value("shape", c::shapeIds, c::setShape), SubCommand.value("layers", () -> List.of("1", "2", "3"), v -> c.setLayers(parse(v))), SubCommand.value("preset", c::presetIds, c::applyPreset), + SubCommand.value("profile", c::profileIds, c::switchProfile), set(c)); } 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 index c393cf4..8acbeb3 100644 --- a/src/main/java/dev/loki/satura/feature/builder/engine/BuildEngine.java +++ b/src/main/java/dev/loki/satura/feature/builder/engine/BuildEngine.java @@ -18,6 +18,7 @@ public final class BuildEngine { public static final int PROGRESS_INTERVAL_TICKS = 20; public static final String NO_BLOCKS = "нет блоков"; + public static final String NO_FLIGHT = "нужен полёт: включи /fly (или креатив) либо стратегию ground_walk"; private final EngineDeps deps; private final BuildSession session; @@ -81,16 +82,27 @@ public final class BuildEngine { } } + private Optional blockReason() { + final Optional reason = deps.game().blockReason(); + if (reason.isEmpty() && deps.strategy().needsFlight() && !deps.game().canFly()) { + return Optional.of(NO_FLIGHT); + } + return reason; + } + private void tryAutoResume() { - if (session.autoResume() && deps.game().blockReason().isEmpty()) { + if (session.autoResume() && blockReason().isEmpty()) { syncWorld(); session.resume(); } } private void build() { - final Optional blocked = deps.game().blockReason(); + final Optional blocked = blockReason(); if (blocked.isPresent()) { + if (NO_FLIGHT.equals(blocked.get())) { + deps.chat().accept("Пауза: " + NO_FLIGHT + ". Продолжу сам, когда полёт включится"); + } session.pause(blocked.get(), true); return; } 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 index 7ebdc18..517a503 100644 --- 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 @@ -8,6 +8,9 @@ public interface GameState { /** Reason why building is not possible now (screen, death, no world); empty when it is possible. */ Optional blockReason(); + /** Whether the player may fly: creative, spectator, or flight granted by the server (/fly). */ + boolean canFly(); + /** Token of the current world: a token change means a world change. */ Object worldToken(); } 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 index 5477dd9..68a8504 100644 --- 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 @@ -26,6 +26,11 @@ public final class MinecraftGameState implements GameState { return Optional.empty(); } + @Override + public boolean canFly() { + return client.player != null && client.player.getAbilities().allowFlying; + } + @Override public Object worldToken() { return client.world; 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 index 1942ff8..122aba4 100644 --- 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 @@ -6,5 +6,10 @@ public interface Walker { /** Start a path to point (x, z); false if the walker is unavailable or the command was rejected. */ boolean walkTo(double x, double z); + /** Start a path to stand exactly in the given block; false if unavailable or rejected. */ + default boolean walkToBlock(final int x, final int y, final int z) { + return false; + } + void cancel(); } 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 index 180d88c..6dc53d0 100644 --- a/src/main/java/dev/loki/satura/feature/builder/plan/Planner.java +++ b/src/main/java/dev/loki/satura/feature/builder/plan/Planner.java @@ -9,19 +9,37 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Direction; /** Slices the area into Y windows and returns the next unfinished column in snake order. */ public final class Planner { + /** Contact needed to place a block: below or any side (a block above is a last resort only). */ + private static final Direction[] SUPPORT_DIRECTIONS = { + Direction.DOWN, Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST + }; + private final Area area; private final Shape shape; private final int bandLayers; private final Predicate done; + private final Predicate solid; private final List columns; private int bandFloor; public Planner(final Area area, final Shape shape, final int bandLayers, final Predicate done) { + this(area, shape, bandLayers, done, pos -> true); + } + + /** + * Surface-aware planner: a cell is offered only when something solid (terrain or an already + * placed block) touches it from below or from a side, so nothing is attempted on thin air. + * Cells without contact wait until their neighbours get built. + */ + public Planner(final Area area, final Shape shape, final int bandLayers, + final Predicate done, final Predicate solid) { + this.solid = solid; this.area = area; this.shape = shape; this.bandLayers = Math.max(CommonOptions.MIN_LAYERS, Math.min(CommonOptions.MAX_LAYERS, bandLayers)); @@ -38,7 +56,7 @@ public final class Planner { for (final BlockPos column : columns) { final List pending = pending(column, bandFloor, bandEnd); if (!pending.isEmpty()) { - return Optional.of(new ColumnTarget(column, pending)); + return Optional.of(new ColumnTarget(column, pending, bandFloor, bandEnd)); } } bandFloor = bandEnd + 1; @@ -71,7 +89,7 @@ public final class Planner { for (final BlockPos column : columns) { final List pending = pending(column, bandFloor, bandEnd); if (!pending.isEmpty() && out.size() < max) { - out.add(new ColumnTarget(column, pending)); + out.add(new ColumnTarget(column, pending, bandFloor, bandEnd)); } } if (out.isEmpty()) { @@ -81,11 +99,20 @@ public final class Planner { return out; } + private boolean supported(final BlockPos cell) { + for (final Direction dir : SUPPORT_DIRECTIONS) { + if (solid.test(cell.offset(dir))) { + return true; + } + } + return false; + } + 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)) { + if (shape.includes(area, pos) && !done.test(pos) && supported(pos)) { cells.add(pos); } } diff --git a/src/main/java/dev/loki/satura/gui/BuilderUi.java b/src/main/java/dev/loki/satura/gui/BuilderUi.java index 892b0f9..3762d74 100644 --- a/src/main/java/dev/loki/satura/gui/BuilderUi.java +++ b/src/main/java/dev/loki/satura/gui/BuilderUi.java @@ -2,7 +2,7 @@ package dev.loki.satura.gui; import dev.loki.satura.core.config.ConfigStore; import dev.loki.satura.feature.builder.BuilderFeature; -import dev.loki.satura.gui.screen.BuilderScreen; +import dev.loki.satura.gui.screen.SaturaScreen; import java.util.function.Consumer; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; @@ -46,7 +46,7 @@ public final class BuilderUi { private void tick(final MinecraftClient client) { while (openMenu.wasPressed()) { if (client.currentScreen == null) { - client.setScreen(new BuilderScreen(builder, openMenu, store)); + client.setScreen(new SaturaScreen(builder, openMenu, store)); } } while (toggleBuild.wasPressed()) { diff --git a/src/main/java/dev/loki/satura/gui/page/BuildPage.java b/src/main/java/dev/loki/satura/gui/page/BuildPage.java new file mode 100644 index 0000000..5cf910c --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/page/BuildPage.java @@ -0,0 +1,119 @@ +package dev.loki.satura.gui.page; + +import dev.loki.satura.feature.builder.BuilderFeature; +import dev.loki.satura.feature.builder.engine.Stage; +import dev.loki.satura.gui.ui.core.Tr; +import dev.loki.satura.gui.ui.core.Widget; +import dev.loki.satura.gui.ui.input.TextBox; +import dev.loki.satura.gui.ui.layout.Flow; +import dev.loki.satura.gui.ui.widget.ActionButton; +import dev.loki.satura.gui.ui.widget.Card; +import dev.loki.satura.gui.ui.widget.Label; +import dev.loki.satura.render.geom.Bounds; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import net.minecraft.client.MinecraftClient; +import net.minecraft.util.math.BlockPos; + +/** Build page: selection corners, start/pause/stop, shape and the block to place. */ +public final class BuildPage implements Page { + + private static final float GAP = 6f; + private static final float CAPTION_H = 16f; + private static final float POS_H = 34f; + private static final float BUTTON_H = 24f; + private static final float SHAPE_H = 34f; + private static final float INPUT_H = 22f; + private static final int BLOCK_LEN = 64; + private static final int POS1 = 1; + + private final Host host; + private final BuilderFeature builder; + + public BuildPage(final Host host, final BuilderFeature builder) { + this.host = host; + this.builder = builder; + } + + @Override + public String title() { + return Tr.t("satura.ui.build.title"); + } + + @Override + public String subtitle() { + return Tr.t("satura.ui.build.subtitle"); + } + + @Override + public View build(final float width) { + final Flow flow = new Flow(width, GAP); + final List out = new ArrayList<>(); + final List pos = flow.cols(2, POS_H); + out.add(posCard(pos.get(0), POS1)); + out.add(posCard(pos.get(1), 2)); + final List buttons = flow.cols(3, BUTTON_H); + out.add(new ActionButton(buttons.get(0), () -> Tr.t("satura.ui.start"), ActionButton.Kind.PRIMARY, + () -> host.run(builder::start))); + out.add(new ActionButton(buttons.get(1), this::pauseLabel, ActionButton.Kind.NEUTRAL, this::togglePause)); + out.add(new ActionButton(buttons.get(2), () -> Tr.t("satura.ui.stop"), ActionButton.Kind.DANGER, + () -> host.run(builder::stop))); + out.add(Label.caption(flow.row(CAPTION_H), Tr.t("satura.ui.shape"))); + final List shapes = builder.shapeIds(); + final List cells = flow.cols(shapes.size(), SHAPE_H); + for (int i = 0; i < shapes.size(); i++) { + out.add(shapeCard(cells.get(i), shapes.get(i))); + } + out.add(Label.caption(flow.row(CAPTION_H), Tr.t("satura.ui.block"))); + out.add(new TextBox(flow.row(INPUT_H), builder.settings().block(), Tr.t("satura.ui.block.hint"), + BLOCK_LEN, id -> host.run(() -> builder.setBlock(id)))); + return new View(out, flow.height()); + } + + private Card posCard(final Bounds b, final int which) { + return new Card(b, "Pos" + which, () -> coords(which), () -> position(which).isPresent(), + () -> capture(which)); + } + + private Card shapeCard(final Bounds b, final String id) { + return new Card(b, Tr.orElse("satura.ui.shape." + id, id), + () -> Tr.orElse("satura.ui.shape." + id + ".desc", ""), + () -> builder.settings().shapeId().equals(id), + () -> { + host.run(() -> builder.setShape(id)); + host.rebuild(); + }); + } + + private Optional position(final int which) { + return which == POS1 ? builder.selection().pos1() : builder.selection().pos2(); + } + + private String coords(final int which) { + return position(which).map(BlockPos::toShortString).orElse(Tr.t("satura.ui.pos.unset")); + } + + private void capture(final int which) { + final var player = MinecraftClient.getInstance().player; + if (player == null) { + host.notice(Tr.t("satura.ui.no.world")); + return; + } + final BlockPos feet = player.getBlockPos(); + if (which == POS1) { + builder.selection().setPos1(feet); + } else { + builder.selection().setPos2(feet); + } + host.notice("Pos" + which + ": " + feet.toShortString()); + } + + private String pauseLabel() { + return Tr.t(builder.stage() == Stage.PAUSED ? "satura.ui.resume" : "satura.ui.pause"); + } + + private void togglePause() { + host.run(() -> builder.stage() == Stage.PAUSED ? builder.resume() : builder.pause()); + } +} diff --git a/src/main/java/dev/loki/satura/gui/page/Host.java b/src/main/java/dev/loki/satura/gui/page/Host.java new file mode 100644 index 0000000..4efcf17 --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/page/Host.java @@ -0,0 +1,18 @@ +package dev.loki.satura.gui.page; + +import java.util.function.Supplier; + +/** What a page may ask of the screen that shows it. */ +public interface Host { + + /** Runs the action and shows its reply (or the error text) as a toast. */ + void run(Supplier action); + + /** Runs the action quietly: only an error produces a toast (sliders, live edits). */ + void apply(Supplier action); + + void notice(String text); + + /** The page structure changed (selection, strategy, profile): lay the widgets out again. */ + void rebuild(); +} diff --git a/src/main/java/dev/loki/satura/gui/page/Page.java b/src/main/java/dev/loki/satura/gui/page/Page.java new file mode 100644 index 0000000..13c93cd --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/page/Page.java @@ -0,0 +1,19 @@ +package dev.loki.satura.gui.page; + +import dev.loki.satura.gui.ui.core.Widget; +import java.util.List; + +/** One screen section: its caption texts and the widgets laid out for a given content width. */ +public interface Page { + + String title(); + + String subtitle(); + + /** Widgets in content coordinates (origin top-left of the pane) and the resulting content height. */ + View build(float width); + + /** Built widgets plus their total height (drives scrolling). */ + record View(List widgets, float height) { + } +} diff --git a/src/main/java/dev/loki/satura/gui/page/PlacePage.java b/src/main/java/dev/loki/satura/gui/page/PlacePage.java new file mode 100644 index 0000000..c75ee3b --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/page/PlacePage.java @@ -0,0 +1,91 @@ +package dev.loki.satura.gui.page; + +import dev.loki.satura.feature.builder.BuildSettings; +import dev.loki.satura.feature.builder.BuilderFeature; +import dev.loki.satura.gui.ui.core.Tr; +import dev.loki.satura.gui.ui.core.Widget; +import dev.loki.satura.gui.ui.layout.Flow; +import dev.loki.satura.gui.ui.widget.ActionButton; +import dev.loki.satura.gui.ui.widget.Card; +import dev.loki.satura.gui.ui.widget.Label; +import dev.loki.satura.gui.ui.widget.SliderBar; +import dev.loki.satura.render.geom.Bounds; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** Placement page: presets, the strategy grid and the generic parameter sliders of the chosen strategy. */ +public final class PlacePage implements Page { + + private static final float GAP = 6f; + private static final float CAPTION_H = 16f; + private static final float BUTTON_H = 22f; + private static final float STRATEGY_H = 36f; + private static final float SLIDER_H = 28f; + private static final int STRATEGY_COLS = 2; + + private final Host host; + private final BuilderFeature builder; + + public PlacePage(final Host host, final BuilderFeature builder) { + this.host = host; + this.builder = builder; + } + + @Override + public String title() { + return Tr.t("satura.ui.place.title"); + } + + @Override + public String subtitle() { + return Tr.t("satura.ui.place.subtitle"); + } + + @Override + public View build(final float width) { + final Flow flow = new Flow(width, GAP); + final List out = new ArrayList<>(); + out.add(Label.caption(flow.row(CAPTION_H), Tr.t("satura.ui.preset"))); + final List presets = builder.presetIds(); + final List cells = flow.cols(presets.size(), BUTTON_H); + for (int i = 0; i < presets.size(); i++) { + final String id = presets.get(i); + out.add(new ActionButton(cells.get(i), () -> Tr.orElse("satura.ui.preset." + id, id), + ActionButton.Kind.NEUTRAL, () -> { + host.run(() -> builder.applyPreset(id)); + host.rebuild(); + })); + } + out.add(Label.caption(flow.row(CAPTION_H), Tr.t("satura.ui.strategy"))); + final List strategies = builder.settings().strategyInfos(); + for (int i = 0; i < strategies.size(); i++) { + out.add(strategyCard(flow.cell(i, STRATEGY_COLS, STRATEGY_H), strategies.get(i))); + } + flow.skipGrid(strategies.size(), STRATEGY_COLS, STRATEGY_H); + out.add(Label.caption(flow.row(CAPTION_H), Tr.t("satura.ui.params"))); + for (final BuildSettings.Slider option : builder.settings().optionSliders()) { + out.add(slider(flow.row(SLIDER_H), option)); + } + return new View(out, flow.height()); + } + + private Card strategyCard(final Bounds b, final BuildSettings.StrategyInfo info) { + return new Card(b, info.label(), () -> Tr.orElse("satura.ui.strategy." + info.id(), ""), + () -> builder.settings().strategy().id().equals(info.id()), + () -> { + host.run(() -> builder.setStrategy(info.id())); + host.rebuild(); + }).badge(Tr.t(info.flight() ? "satura.ui.fly" : "satura.ui.walk")); + } + + private SliderBar slider(final Bounds b, final BuildSettings.Slider option) { + return new SliderBar(b, option.label(), + new SliderBar.Range(option.min(), option.max(), option.step(), option.value()), + v -> host.apply(() -> builder.setOption(option.key(), format(option, v)))); + } + + private static String format(final BuildSettings.Slider option, final double value) { + return option.integer() ? String.valueOf(Math.round(value)) : String.format(Locale.ROOT, "%.2f", value); + } +} diff --git a/src/main/java/dev/loki/satura/gui/page/extra/ProfilesPage.java b/src/main/java/dev/loki/satura/gui/page/extra/ProfilesPage.java new file mode 100644 index 0000000..24ce426 --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/page/extra/ProfilesPage.java @@ -0,0 +1,69 @@ +package dev.loki.satura.gui.page.extra; + +import dev.loki.satura.feature.builder.BuilderFeature; +import dev.loki.satura.gui.page.Host; +import dev.loki.satura.gui.page.Page; +import dev.loki.satura.gui.ui.core.Tr; +import dev.loki.satura.gui.ui.core.Widget; +import dev.loki.satura.gui.ui.input.TextBox; +import dev.loki.satura.gui.ui.layout.Flow; +import dev.loki.satura.gui.ui.widget.Card; +import dev.loki.satura.gui.ui.widget.Label; +import java.util.ArrayList; +import java.util.List; + +/** Profiles page: switch between saved setting sets or create a new one from the current settings. */ +public final class ProfilesPage implements Page { + + private static final float GAP = 6f; + private static final float CAPTION_H = 16f; + private static final float CARD_H = 30f; + private static final float INPUT_H = 22f; + private static final int COLS = 2; + private static final int NAME_LEN = 32; + + private final Host host; + private final BuilderFeature builder; + + public ProfilesPage(final Host host, final BuilderFeature builder) { + this.host = host; + this.builder = builder; + } + + @Override + public String title() { + return Tr.t("satura.ui.profiles.title"); + } + + @Override + public String subtitle() { + return Tr.t("satura.ui.profiles.subtitle"); + } + + @Override + public View build(final float width) { + final Flow flow = new Flow(width, GAP); + final List out = new ArrayList<>(); + final List names = builder.profileIds(); + for (int i = 0; i < names.size(); i++) { + out.add(card(flow.cell(i, COLS, CARD_H), names.get(i))); + } + flow.skipGrid(names.size(), COLS, CARD_H); + out.add(Label.caption(flow.row(CAPTION_H), Tr.t("satura.ui.profiles.new"))); + out.add(new TextBox(flow.row(INPUT_H), "", Tr.t("satura.ui.profiles.hint"), NAME_LEN, name -> { + host.run(() -> builder.switchProfile(name)); + host.rebuild(); + })); + return new View(out, flow.height()); + } + + private Card card(final dev.loki.satura.render.geom.Bounds b, final String name) { + return new Card(b, name, + () -> builder.profile().equals(name) ? Tr.t("satura.ui.profiles.active") : "", + () -> builder.profile().equals(name), + () -> { + host.run(() -> builder.switchProfile(name)); + host.rebuild(); + }); + } +} diff --git a/src/main/java/dev/loki/satura/gui/page/extra/SupplyPage.java b/src/main/java/dev/loki/satura/gui/page/extra/SupplyPage.java new file mode 100644 index 0000000..f2d556b --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/page/extra/SupplyPage.java @@ -0,0 +1,39 @@ +package dev.loki.satura.gui.page.extra; + +import dev.loki.satura.gui.page.Page; +import dev.loki.satura.gui.ui.core.Tr; +import dev.loki.satura.gui.ui.core.Widget; +import dev.loki.satura.gui.ui.layout.Flow; +import dev.loki.satura.gui.ui.widget.Card; +import java.util.ArrayList; +import java.util.List; + +/** Supply page: placeholder until the supply feature (chest routes, teleports) exists. */ +public final class SupplyPage implements Page { + + private static final float GAP = 6f; + private static final float CARD_H = 34f; + private static final List PLANNED = List.of("route", "teleport", "restock"); + + @Override + public String title() { + return Tr.t("satura.ui.supply.title"); + } + + @Override + public String subtitle() { + return Tr.t("satura.ui.supply.subtitle"); + } + + @Override + public View build(final float width) { + final Flow flow = new Flow(width, GAP); + final List out = new ArrayList<>(); + for (final String key : PLANNED) { + out.add(new Card(flow.row(CARD_H), Tr.t("satura.ui.supply." + key), + () -> Tr.t("satura.ui.supply." + key + ".desc"), () -> false, null) + .badge(Tr.t("satura.ui.soon"))); + } + return new View(out, flow.height()); + } +} diff --git a/src/main/java/dev/loki/satura/gui/page/extra/ThemesPage.java b/src/main/java/dev/loki/satura/gui/page/extra/ThemesPage.java new file mode 100644 index 0000000..6b7374e --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/page/extra/ThemesPage.java @@ -0,0 +1,54 @@ +package dev.loki.satura.gui.page.extra; + +import dev.loki.satura.core.config.ConfigStore; +import dev.loki.satura.gui.ThemePref; +import dev.loki.satura.gui.page.Host; +import dev.loki.satura.gui.page.Page; +import dev.loki.satura.gui.ui.core.Tr; +import dev.loki.satura.gui.ui.core.Widget; +import dev.loki.satura.gui.ui.layout.Flow; +import dev.loki.satura.gui.ui.widget.Card; +import dev.loki.satura.render.Theme; +import java.util.ArrayList; +import java.util.List; + +/** Themes page: the accent palettes; the choice is applied at once and saved. */ +public final class ThemesPage implements Page { + + private static final float GAP = 6f; + private static final float CARD_H = 30f; + private static final int COLS = 2; + + private final Host host; + private final ConfigStore store; + + public ThemesPage(final Host host, final ConfigStore store) { + this.host = host; + this.store = store; + } + + @Override + public String title() { + return Tr.t("satura.ui.themes.title"); + } + + @Override + public String subtitle() { + return Tr.t("satura.ui.themes.subtitle"); + } + + @Override + public View build(final float width) { + final Flow flow = new Flow(width, GAP); + final List out = new ArrayList<>(); + final List themes = Theme.all(); + for (int i = 0; i < themes.size(); i++) { + final Theme theme = themes.get(i); + out.add(new Card(flow.cell(i, COLS, CARD_H), Tr.orElse("satura.ui.theme." + theme.id(), theme.id()), + () -> "", () -> Theme.get().id().equals(theme.id()), + () -> host.run(() -> ThemePref.apply(store, theme.id()))).swatch(theme.accent())); + } + flow.skipGrid(themes.size(), COLS, CARD_H); + return new View(out, flow.height()); + } +} diff --git a/src/main/java/dev/loki/satura/gui/screen/BuilderScreen.java b/src/main/java/dev/loki/satura/gui/screen/BuilderScreen.java deleted file mode 100644 index 3bddd1c..0000000 --- a/src/main/java/dev/loki/satura/gui/screen/BuilderScreen.java +++ /dev/null @@ -1,204 +0,0 @@ -package dev.loki.satura.gui.screen; - -import dev.loki.satura.core.config.ConfigStore; -import dev.loki.satura.feature.builder.BuilderFeature; -import dev.loki.satura.gui.screen.content.BuildTab; -import dev.loki.satura.gui.screen.content.PlaceTab; -import dev.loki.satura.gui.screen.content.SupplyTab; -import dev.loki.satura.render.Renderer; -import dev.loki.satura.render.Theme; -import java.util.List; -import java.util.function.Supplier; -import net.minecraft.client.font.TextRenderer; -import net.minecraft.client.gui.DrawContext; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.gui.widget.ButtonWidget; -import net.minecraft.client.gui.widget.ClickableWidget; -import net.minecraft.client.gui.widget.TextFieldWidget; -import net.minecraft.client.input.KeyInput; -import net.minecraft.client.option.KeyBinding; -import net.minecraft.text.Text; - -/** - * Tabbed builder screen: the panel, the tab bar (build / placement / supply) and the status - * line are shared; tab content is provided by {@link Tab} implementations. - */ -@SuppressWarnings("PMD.AvoidCatchingGenericException") -public final class BuilderScreen extends Screen implements Tab.Host { - - private static final int TAB_COUNT = 3; - private static final int TAB_BUILD = 0; - private static final int TAB_PLACE = 1; - private static final int TAB_BAR_ROWS = 1; - private static final int GRID_THIRD = 3; - private static final int NOTICE_TICKS = 100; - private static final String NOTICE_ERROR = "ошибка"; - private static final List TAB_KEYS = - List.of("satura.gui.tab.build", "satura.gui.tab.place", "satura.gui.tab.supply"); - - private final BuilderFeature builder; - private final KeyBinding openMenu; - private final ConfigStore store; - private Panel panel; - private Tab tab; - private int tabIndex = TAB_BUILD; - private Text noticeText = Text.empty(); - private int noticeTicks; - private boolean reinitQueued; - - public BuilderScreen(final BuilderFeature builder, final KeyBinding openMenu, final ConfigStore store) { - super(Text.translatable("satura.title")); - this.builder = builder; - this.openMenu = openMenu; - this.store = store; - } - - @Override - protected void init() { - final int rowCap = Math.max(0, usableRows() - TAB_BAR_ROWS); - tab = createTab(rowCap); - panel = new Panel(width, height, TAB_BAR_ROWS + tab.rows()); - final Tab.Grid grid = grid(); - final int barY = panel.top() + Panel.PAD + Panel.TITLE_H + Panel.GAP; - addTabButtons(barY, grid); - tab.build(barY + Panel.WIDGET_H + Panel.GAP, grid); - } - - @Override - public void tick() { - if (reinitQueued) { - reinitQueued = false; - clearAndInit(); - return; - } - if (noticeTicks > 0) { - noticeTicks--; - } - tab.tick(); - } - - @Override - public void render(final DrawContext context, final int mouseX, final int mouseY, final float delta) { - super.render(context, mouseX, mouseY, delta); - context.drawCenteredTextWithShadow(textRenderer, title, width / 2, - panel.top() + Panel.PAD, Theme.TEXT); - int lineY = panel.top() + Panel.PAD + Panel.TITLE_H + Panel.GAP * 2 + Panel.WIDGET_H; - for (final Text line : tab.lines()) { - context.drawTextWithShadow(textRenderer, line, panel.left(), lineY, Theme.TEXT_MUTED); - lineY += Panel.LINE_H; - } - context.drawTextWithShadow(textRenderer, trim(noticeText.getString()), - panel.left(), panel.statusY(), Theme.get().accentHover()); - context.drawTextWithShadow(textRenderer, trim(builder.status()), - panel.left(), panel.statusY() + Panel.LINE_H, Theme.TEXT_MUTED); - } - - @Override - public void renderBackground(final DrawContext context, final int mouseX, final int mouseY, - final float delta) { - super.renderBackground(context, mouseX, mouseY, delta); - panel.paint(Renderer.shared()); - } - - @Override - public boolean keyPressed(final KeyInput input) { - if (openMenu.matchesKey(input)) { - close(); - return true; - } - return tab.key(input) || super.keyPressed(input); - } - - @Override - public void removed() { - tab.close(); - super.removed(); - } - - @Override - public boolean shouldPause() { - return false; - } - - @Override - public W add(final W widget) { - return addDrawableChild(widget); - } - - @Override - public void addField(final TextFieldWidget field) { - addSelectableChild(field); - } - - @Override - public void run(final Supplier action) { - try { - showNotice(action.get()); - } catch (RuntimeException e) { - showNotice(e.getMessage() == null ? NOTICE_ERROR : e.getMessage()); - } - } - - @Override - public void notice(final String text) { - showNotice(text); - } - - @Override - public void reinit() { - reinitQueued = true; - } - - @Override - public TextRenderer font() { - return textRenderer; - } - - /** Widget rows that fit between the title and the status block (GUI scale aware). */ - private int usableRows() { - final int usable = height - Panel.PAD * 2 - Panel.TITLE_H - Panel.GAP * 2 - - Panel.STATUS_ROWS * Panel.LINE_H; - return usable / (Panel.WIDGET_H + Panel.GAP); - } - - private Tab createTab(final int rowCap) { - return switch (tabIndex) { - case TAB_BUILD -> new BuildTab(this, builder, store); - case TAB_PLACE -> new PlaceTab(this, builder, rowCap); - default -> new SupplyTab(); - }; - } - - private Tab.Grid grid() { - return new Tab.Grid(panel.left(), panel.inner(), - (panel.inner() - Panel.GAP) / 2, - (panel.inner() - Panel.GAP * 2) / GRID_THIRD, - Panel.WIDGET_H, Panel.GAP); - } - - private void addTabButtons(final int y, final Tab.Grid g) { - for (int i = 0; i < TAB_COUNT; i++) { - final int index = i; - addDrawableChild(ButtonWidget.builder(Text.translatable(TAB_KEYS.get(i)), - b -> switchTab(index)) - .dimensions(g.left() + (g.third() + Panel.GAP) * i, y, g.third(), Panel.WIDGET_H) - .build()); - } - } - - private void switchTab(final int index) { - if (index != tabIndex) { - tabIndex = index; - reinitQueued = true; - } - } - - private void showNotice(final String text) { - noticeText = Text.literal(text); - noticeTicks = NOTICE_TICKS; - } - - private String trim(final String text) { - return textRenderer.trimToWidth(text, Panel.WIDTH - Panel.PAD * 2); - } -} diff --git a/src/main/java/dev/loki/satura/gui/screen/Nav.java b/src/main/java/dev/loki/satura/gui/screen/Nav.java new file mode 100644 index 0000000..6ccc955 --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/screen/Nav.java @@ -0,0 +1,60 @@ +package dev.loki.satura.gui.screen; + +import dev.loki.satura.gui.ui.core.Draw; +import dev.loki.satura.gui.ui.core.Palette; +import dev.loki.satura.render.color.Colors; +import dev.loki.satura.render.geom.Bounds; +import java.util.List; + +/** Sidebar navigation: one pill per page, the selected one filled with the accent gradient. */ +final class Nav { + + private static final float ITEM_H = 22f; + private static final float ITEM_GAP = 3f; + private static final float INSET = 8f; + private static final float RADIUS = 6f; + private static final float TEXT_SIZE = 7.8f; + private static final float TEXT_PAD = 10f; + private static final float HOVER_EASE = 0.3f; + private static final float HOVER_VISIBLE = 0.01f; + + private final Bounds area; + private final List titles; + private final float[] hover; + + Nav(final Bounds area, final List titles) { + this.area = area; + this.titles = titles; + this.hover = new float[titles.size()]; + } + + /** Index of the item under the point, or -1. */ + int hit(final float x, final float y) { + for (int i = 0; i < titles.size(); i++) { + if (Draw.inside(item(i), x, y)) { + return i; + } + } + return -1; + } + + void render(final Draw draw, final float mx, final float my, final int selected) { + for (int i = 0; i < titles.size(); i++) { + final Bounds b = item(i); + hover[i] += ((Draw.inside(b, mx, my) ? 1f : 0f) - hover[i]) * HOVER_EASE; + if (i == selected) { + draw.gradient(b, RADIUS, Palette.gradientFrom(), Palette.gradientTo()); + } else if (hover[i] > HOVER_VISIBLE) { + draw.fill(b, RADIUS, Colors.lerp(0x00FFFFFF, 0x14FFFFFF, hover[i])); + } + final float y = b.y() + (b.height() - draw.lineHeight(TEXT_SIZE)) / 2f; + draw.bold(titles.get(i), b.x() + TEXT_PAD, y, TEXT_SIZE, + i == selected ? Palette.ON_ACCENT : Palette.MUTED); + } + } + + private Bounds item(final int index) { + return new Bounds(area.x() + INSET, area.y() + index * (ITEM_H + ITEM_GAP), + area.width() - INSET * 2f, ITEM_H); + } +} diff --git a/src/main/java/dev/loki/satura/gui/screen/Pages.java b/src/main/java/dev/loki/satura/gui/screen/Pages.java new file mode 100644 index 0000000..377b615 --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/screen/Pages.java @@ -0,0 +1,24 @@ +package dev.loki.satura.gui.screen; + +import dev.loki.satura.core.config.ConfigStore; +import dev.loki.satura.feature.builder.BuilderFeature; +import dev.loki.satura.gui.page.BuildPage; +import dev.loki.satura.gui.page.Host; +import dev.loki.satura.gui.page.Page; +import dev.loki.satura.gui.page.PlacePage; +import dev.loki.satura.gui.page.extra.ProfilesPage; +import dev.loki.satura.gui.page.extra.SupplyPage; +import dev.loki.satura.gui.page.extra.ThemesPage; +import java.util.List; + +/** The pages of the screen in sidebar order. */ +final class Pages { + + private Pages() { + } + + static List create(final Host host, final BuilderFeature builder, final ConfigStore store) { + return List.of(new BuildPage(host, builder), new PlacePage(host, builder), new SupplyPage(), + new ProfilesPage(host, builder), new ThemesPage(host, store)); + } +} diff --git a/src/main/java/dev/loki/satura/gui/screen/Panel.java b/src/main/java/dev/loki/satura/gui/screen/Panel.java deleted file mode 100644 index a9459fb..0000000 --- a/src/main/java/dev/loki/satura/gui/screen/Panel.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.loki.satura.gui.screen; - -import dev.loki.satura.render.Renderer; -import dev.loki.satura.render.Theme; -import dev.loki.satura.render.geom.Bounds; - -/** Geometry and drawing of the screen's dark panel (blur, backdrop, outline). */ -final class Panel { - - static final int WIDTH = 240; - static final int PAD = 10; - static final int WIDGET_H = 20; - static final int GAP = 4; - static final int TITLE_H = 14; - static final int LINE_H = 11; - static final int STATUS_ROWS = 2; - private static final float BLUR_STRENGTH = 1.0f; - - private final int screenW; - private final int screenH; - private final int rows; - - Panel(final int screenW, final int screenH, final int rows) { - this.screenW = screenW; - this.screenH = screenH; - this.rows = rows; - } - - /** Left edge of the content (padding already applied). */ - int left() { - return (screenW - WIDTH) / 2 + PAD; - } - - int inner() { - return WIDTH - PAD * 2; - } - - int top() { - return (screenH - height()) / 2; - } - - int height() { - return PAD + TITLE_H + GAP + rows * (WIDGET_H + GAP) + GAP + STATUS_ROWS * LINE_H + PAD; - } - - /** Y of the first status line (at the bottom of the panel). */ - int statusY() { - return top() + height() - PAD - STATUS_ROWS * LINE_H; - } - - Bounds bounds() { - return new Bounds((screenW - WIDTH) / 2f, top(), WIDTH, height()); - } - - /** Draws the panel backdrop; called after the vanilla background, before the widgets. */ - void paint(final Renderer renderer) { - final Bounds b = bounds(); - renderer.blur(b, Theme.RADIUS, BLUR_STRENGTH); - renderer.rect(b, Theme.RADIUS, Theme.PANEL); - renderer.outline(b, Theme.RADIUS, Theme.BORDER_WIDTH, Theme.BORDER); - } -} diff --git a/src/main/java/dev/loki/satura/gui/screen/SaturaScreen.java b/src/main/java/dev/loki/satura/gui/screen/SaturaScreen.java new file mode 100644 index 0000000..85764c9 --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/screen/SaturaScreen.java @@ -0,0 +1,168 @@ +package dev.loki.satura.gui.screen; + +import dev.loki.satura.core.config.ConfigStore; +import dev.loki.satura.feature.builder.BuilderFeature; +import dev.loki.satura.gui.page.Host; +import dev.loki.satura.gui.page.Page; +import dev.loki.satura.gui.ui.core.Draw; +import dev.loki.satura.gui.ui.core.Tr; +import dev.loki.satura.gui.ui.layout.Pane; +import dev.loki.satura.render.Renderer; +import java.util.List; +import java.util.function.Supplier; +import net.minecraft.client.gui.Click; +import net.minecraft.client.gui.DrawContext; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.input.CharInput; +import net.minecraft.client.input.KeyInput; +import net.minecraft.client.option.KeyBinding; +import net.minecraft.text.Text; + +/** The builder menu: sidebar, one page at a time in a scrollable pane, status bar. All drawn by our renderer. */ +@SuppressWarnings("PMD.AvoidCatchingGenericException") +public final class SaturaScreen extends Screen implements Host { + + private static final int TOAST_TICKS = 100; + private static final List NAV_KEYS = List.of("satura.ui.nav.build", "satura.ui.nav.place", + "satura.ui.nav.supply", "satura.ui.nav.profiles", "satura.ui.nav.themes"); + + private final BuilderFeature builder; + private final KeyBinding openMenu; + private final ConfigStore store; + private Shell shell; + private Nav nav; + private Pane pane; + private List pages; + private int index; + private String toast = ""; + private int toastTicks; + + public SaturaScreen(final BuilderFeature builder, final KeyBinding openMenu, final ConfigStore store) { + super(Text.translatable("satura.title")); + this.builder = builder; + this.openMenu = openMenu; + this.store = store; + } + + @Override + protected void init() { + shell = new Shell(width, height, builder); + nav = new Nav(shell.navArea(), NAV_KEYS.stream().map(Tr::t).toList()); + pane = new Pane(shell.content()); + pages = Pages.create(this, builder, store); + rebuild(); + } + + @Override + public void rebuild() { + final Page.View view = pages.get(index).build(pane.area().width()); + pane.set(view.widgets(), view.height()); + } + + @Override + public void run(final Supplier action) { + try { + notice(action.get()); + } catch (RuntimeException e) { + notice(e.getMessage() == null ? Tr.t("satura.ui.error") : e.getMessage()); + } + } + + @Override + public void apply(final Supplier action) { + try { + action.get(); + } catch (RuntimeException e) { + notice(e.getMessage() == null ? Tr.t("satura.ui.error") : e.getMessage()); + } + } + + @Override + public void notice(final String text) { + toast = text; + toastTicks = TOAST_TICKS; + } + + @Override + public void tick() { + if (toastTicks > 0) { + toastTicks--; + } + } + + @Override + public void render(final DrawContext context, final int mouseX, final int mouseY, final float delta) { + super.render(context, mouseX, mouseY, delta); + Renderer.shared().defer(() -> paint(mouseX, mouseY)); + } + + @Override + public boolean mouseClicked(final Click click, final boolean doubled) { + final float x = (float) click.x(); + final float y = (float) click.y(); + final int hit = click.button() == 0 ? nav.hit(x, y) : -1; + if (hit >= 0) { + pane.blurAll(); + index = hit; + rebuild(); + pane.reset(); + return true; + } + return pane.click(x, y, click.button()) || super.mouseClicked(click, doubled); + } + + @Override + public boolean mouseDragged(final Click click, final double offsetX, final double offsetY) { + pane.drag((float) click.x(), (float) click.y()); + return super.mouseDragged(click, offsetX, offsetY); + } + + @Override + public boolean mouseReleased(final Click click) { + pane.release(); + return super.mouseReleased(click); + } + + @Override + public boolean mouseScrolled(final double mx, final double my, final double horizontal, final double vertical) { + return pane.scroll(mx, my, vertical) || super.mouseScrolled(mx, my, horizontal, vertical); + } + + @Override + public boolean keyPressed(final KeyInput input) { + if (pane.key(input)) { + return true; + } + if (!pane.typing() && openMenu.matchesKey(input)) { + close(); + return true; + } + return super.keyPressed(input); + } + + @Override + public boolean charTyped(final CharInput input) { + return pane.chars(input) || super.charTyped(input); + } + + @Override + public void removed() { + pane.blurAll(); + super.removed(); + } + + @Override + public boolean shouldPause() { + return false; + } + + private void paint(final int mouseX, final int mouseY) { + final Draw draw = new Draw(Renderer.shared()); + shell.frame(draw); + final Page page = pages.get(index); + shell.header(draw, page.title(), page.subtitle()); + nav.render(draw, mouseX, mouseY, index); + pane.render(draw, mouseX, mouseY); + shell.status(draw, toastTicks > 0 ? toast : ""); + } +} diff --git a/src/main/java/dev/loki/satura/gui/screen/Shell.java b/src/main/java/dev/loki/satura/gui/screen/Shell.java new file mode 100644 index 0000000..0c722be --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/screen/Shell.java @@ -0,0 +1,137 @@ +package dev.loki.satura.gui.screen; + +import dev.loki.satura.feature.builder.BuilderFeature; +import dev.loki.satura.feature.builder.engine.BuildSession; +import dev.loki.satura.feature.builder.engine.Stage; +import dev.loki.satura.gui.ui.core.Draw; +import dev.loki.satura.gui.ui.core.Palette; +import dev.loki.satura.gui.ui.core.Tr; +import dev.loki.satura.render.geom.Bounds; +import java.util.Locale; +import java.util.Optional; + +/** Window chrome: frame, sidebar logo and profile chip, page header, status bar and the toast line. */ +final class Shell { + + private static final float MAX_W = 440f; + private static final float MAX_H = 290f; + private static final float MARGIN = 8f; + private static final float SIDEBAR_W = 104f; + private static final float PAD = 10f; + private static final float HEADER_H = 32f; + private static final float STATUS_H = 30f; + private static final float RADIUS = 10f; + private static final float INNER_RADIUS = 8f; + private static final float LOGO_H = 34f; + private static final float TITLE_SIZE = 11f; + private static final float SUB_SIZE = 6.8f; + private static final float SMALL = 6.6f; + private static final float BAR_H = 3f; + private static final float BLUR = 1f; + + private final Bounds window; + private final BuilderFeature builder; + + Shell(final int screenW, final int screenH, final BuilderFeature builder) { + final float w = Math.min(MAX_W, screenW - MARGIN * 2f); + final float h = Math.min(MAX_H, screenH - MARGIN * 2f); + this.window = new Bounds((screenW - w) / 2f, (screenH - h) / 2f, w, h); + this.builder = builder; + } + + /** Sidebar area for the navigation items (below the logo). */ + Bounds navArea() { + return new Bounds(window.x() + PAD / 2f, window.y() + PAD + LOGO_H, SIDEBAR_W - PAD, window.height() / 2f); + } + + /** Scrollable page area between the header and the status bar. */ + Bounds content() { + final float x = window.x() + SIDEBAR_W + PAD; + final float y = window.y() + PAD + HEADER_H; + return new Bounds(x, y, window.right() - PAD - x, window.bottom() - PAD - STATUS_H - 6f - y); + } + + void frame(final Draw draw) { + draw.shadow(window, RADIUS, Palette.SHADOW); + draw.blur(window, RADIUS, BLUR); + draw.fill(window, RADIUS, Palette.WINDOW); + draw.border(window, RADIUS, Palette.BORDER); + final Bounds side = new Bounds(window.x() + PAD / 2f, window.y() + PAD / 2f, SIDEBAR_W - PAD, + window.height() - PAD); + draw.fill(side, INNER_RADIUS, Palette.SIDEBAR); + draw.border(side, INNER_RADIUS, Palette.BORDER); + draw.boldGradient("SATURA", side.x() + PAD, side.y() + PAD, TITLE_SIZE, + Palette.gradientFrom(), Palette.gradientTo()); + draw.text("builder", side.x() + PAD, side.y() + PAD + draw.lineHeight(TITLE_SIZE) + 1f, SUB_SIZE, + Palette.MUTED); + profileChip(draw, side); + } + + void header(final Draw draw, final String title, final String subtitle) { + final Bounds c = content(); + final float x = c.x() + 1f; + draw.bold(title, x, window.y() + PAD, TITLE_SIZE, Palette.TEXT); + draw.text(subtitle, x, window.y() + PAD + draw.lineHeight(TITLE_SIZE) + 2f, SUB_SIZE, Palette.MUTED); + } + + void status(final Draw draw, final String toast) { + final Bounds c = content(); + final Bounds bar = new Bounds(c.x(), window.bottom() - PAD - STATUS_H, c.width(), STATUS_H); + draw.fill(bar, INNER_RADIUS, Palette.CARD); + draw.border(bar, INNER_RADIUS, Palette.BORDER); + final Optional shot = builder.progress(); + final Stage stage = builder.stage(); + final float x = bar.x() + PAD; + draw.fill(new Bounds(x, bar.y() + 8f, 5f, 5f), 2.5f, stageColor(stage)); + final String left = builder.settings().strategy().id() + " - " + stage.name().toLowerCase(Locale.ROOT); + draw.bold(left, x + 9f, bar.y() + 6f, SMALL, Palette.TEXT); + final String right = shot.map(Shell::stats).orElse(Tr.t("satura.ui.status.idle")); + draw.text(right, bar.right() - PAD - draw.width(right, SMALL, false), bar.y() + 6f, SMALL, Palette.MUTED); + progressBar(draw, bar, shot.map(s -> s.percent() / 100.0).orElse(0.0)); + if (toast != null && !toast.isEmpty()) { + toast(draw, bar, toast); + } + } + + private void progressBar(final Draw draw, final Bounds bar, final double fraction) { + final float width = bar.width() - PAD * 2f; + final float y = bar.bottom() - 8f; + draw.fill(new Bounds(bar.x() + PAD, y, width, BAR_H), BAR_H / 2f, Palette.BORDER); + final float filled = (float) Math.max(0.0, Math.min(1.0, fraction)) * width; + if (filled >= BAR_H) { + draw.gradient(new Bounds(bar.x() + PAD, y, filled, BAR_H), BAR_H / 2f, + Palette.gradientFrom(), Palette.gradientTo()); + } + } + + private void toast(final Draw draw, final Bounds bar, final String text) { + final String shown = draw.fit(text, SMALL + 0.8f, true, bar.width() - PAD * 3f); + final float w = draw.width(shown, SMALL + 0.8f, true) + PAD * 2f; + final Bounds pill = new Bounds(bar.right() - w, bar.y() - 22f, w, 18f); + draw.fill(pill, pill.height() / 2f, Palette.WINDOW); + draw.border(pill, pill.height() / 2f, Palette.accent()); + draw.centered(shown, pill, SMALL + 0.8f, Palette.TEXT, true); + } + + private void profileChip(final Draw draw, final Bounds side) { + final Bounds chip = new Bounds(side.x() + 6f, side.bottom() - 30f, side.width() - 12f, 24f); + draw.fill(chip, INNER_RADIUS - 2f, Palette.CARD); + draw.border(chip, INNER_RADIUS - 2f, Palette.BORDER); + draw.fill(new Bounds(chip.x() + 7f, chip.y() + 9.5f, 5f, 5f), 2.5f, Palette.OK); + draw.bold(draw.fit(builder.profile(), SMALL + 0.6f, true, chip.width() - 26f), chip.x() + 17f, + chip.y() + (chip.height() - draw.lineHeight(SMALL)) / 2f, SMALL + 0.6f, Palette.TEXT); + } + + private static String stats(final BuildSession.Snapshot s) { + return String.format(Locale.ROOT, "%d/%d - %.1f/s - %.0f%%", s.done(), s.total(), + s.blocksPerSecond(), s.percent()); + } + + private static int stageColor(final Stage stage) { + return switch (stage) { + case BUILD -> Palette.OK; + case PAUSED -> Palette.WARN; + default -> Palette.MUTED; + }; + } +} diff --git a/src/main/java/dev/loki/satura/gui/screen/Tab.java b/src/main/java/dev/loki/satura/gui/screen/Tab.java deleted file mode 100644 index 765258c..0000000 --- a/src/main/java/dev/loki/satura/gui/screen/Tab.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.loki.satura.gui.screen; - -import java.util.List; -import java.util.function.Supplier; -import net.minecraft.client.font.TextRenderer; -import net.minecraft.client.gui.widget.ClickableWidget; -import net.minecraft.client.gui.widget.TextFieldWidget; -import net.minecraft.client.input.KeyInput; -import net.minecraft.text.Text; - -/** - * Content of one screen tab: a fixed number of widget rows built top-down. The screen owns - * the panel, the tab bar and the status line; a tab only fills its own rows. - */ -public interface Tab { - - /** Widget rows this tab needs (the panel is sized from it). */ - int rows(); - - /** Adds widgets starting at y (first content row), using the panel grid. */ - void build(int y, Grid grid); - - /** Static text lines drawn in the empty content area (a tab with no widgets). */ - default List lines() { - return List.of(); - } - - /** Periodic label refresh; called from the screen tick. */ - default void tick() { - } - - /** The screen is closing; commit pending input here. */ - default void close() { - } - - /** Key event; true = consumed. */ - default boolean key(KeyInput input) { - return false; - } - - /** Column layout of the content area, computed by the screen from the panel geometry. */ - record Grid(int left, int inner, int half, int third, int rowH, int gap) { - } - - /** Services the host screen provides to tab content. */ - interface Host { - - /** Registers a widget (button, slider, cycle) and returns it. */ - W add(W widget); - - /** Registers a text field (focusable, committed by the tab). */ - void addField(TextFieldWidget field); - - /** Runs the action, turning the reply or the error into a notice. */ - void run(Supplier action); - - /** Shows a notice line for a short time. */ - void notice(String text); - - /** Rebuilds the screen (tab switch, strategy change). */ - void reinit(); - - /** Font for text fields. */ - TextRenderer font(); - } -} diff --git a/src/main/java/dev/loki/satura/gui/screen/content/BuildTab.java b/src/main/java/dev/loki/satura/gui/screen/content/BuildTab.java deleted file mode 100644 index 1994242..0000000 --- a/src/main/java/dev/loki/satura/gui/screen/content/BuildTab.java +++ /dev/null @@ -1,135 +0,0 @@ -package dev.loki.satura.gui.screen.content; - -import dev.loki.satura.core.config.ConfigStore; -import dev.loki.satura.feature.builder.BuilderFeature; -import dev.loki.satura.feature.builder.engine.Stage; -import dev.loki.satura.gui.ThemePref; -import dev.loki.satura.gui.screen.Tab; -import dev.loki.satura.gui.widget.CycleButton; -import dev.loki.satura.render.Theme; -import java.util.Optional; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.widget.ButtonWidget; -import net.minecraft.client.gui.widget.TextFieldWidget; -import net.minecraft.client.input.KeyInput; -import net.minecraft.text.Text; -import net.minecraft.util.math.BlockPos; - -/** Build tab: selection, start/pause/stop, shape, theme and the block id field. */ -public final class BuildTab implements Tab { - - private static final int WIDGET_ROWS = 5; - private static final int BLOCK_LEN = 64; - private static final String LANG_POS1 = "satura.gui.pos1"; - private static final String LANG_POS2 = "satura.gui.pos2"; - private static final String LANG_PAUSE = "satura.gui.pause"; - private static final String LANG_RESUME = "satura.gui.resume"; - private static final int POS1 = 1; - private static final int POS2 = 2; - - private final Host host; - private final BuilderFeature builder; - private final ConfigStore store; - private ButtonWidget pos1; - private ButtonWidget pos2; - private ButtonWidget pause; - private TextFieldWidget block; - - public BuildTab(final Host host, final BuilderFeature builder, final ConfigStore store) { - this.host = host; - this.builder = builder; - this.store = store; - } - - @Override - public int rows() { - return WIDGET_ROWS; - } - - @Override - public void build(final int y, final Grid g) { - int row = y; - pos1 = host.add(button(LANG_POS1, () -> capture(POS1), g.left(), row, g.half(), g.rowH())); - pos2 = host.add(button(LANG_POS2, () -> capture(POS2), - g.left() + g.half() + g.gap(), row, g.half(), g.rowH())); - row += g.rowH() + g.gap(); - host.add(button("satura.gui.start", () -> host.run(builder::start), - g.left(), row, g.third(), g.rowH())); - pause = host.add(button(LANG_PAUSE, this::togglePause, - g.left() + g.third() + g.gap(), row, g.third(), g.rowH())); - host.add(button("satura.gui.stop", () -> host.run(builder::stop), - g.left() + (g.third() + g.gap()) * 2, row, g.third(), g.rowH())); - row += g.rowH() + g.gap(); - host.add(new CycleButton(g.left(), row, g.inner(), g.rowH(), "satura.gui.shape", - builder.shapeIds(), builder.settings().shapeId(), - id -> host.run(() -> builder.setShape(id)))); - row += g.rowH() + g.gap(); - host.add(new CycleButton(g.left(), row, g.inner(), g.rowH(), "satura.gui.theme", - Theme.all().stream().map(Theme::id).toList(), Theme.get().id(), - id -> host.run(() -> ThemePref.apply(store, id)))); - row += g.rowH() + g.gap(); - block = new TextFieldWidget(host.font(), g.left(), row, g.inner(), g.rowH(), - Text.translatable("satura.gui.block")); - block.setMaxLength(BLOCK_LEN); - block.setText(builder.settings().block()); - host.addField(block); - } - - @Override - public void tick() { - pos1.setMessage(posLabel(LANG_POS1, builder.selection().pos1())); - pos2.setMessage(posLabel(LANG_POS2, builder.selection().pos2())); - pause.setMessage(Text.translatable( - builder.stage() == Stage.PAUSED ? LANG_RESUME : LANG_PAUSE)); - } - - @Override - public boolean key(final KeyInput input) { - if (block.isFocused() && input.isEnter()) { - commitBlock(); - return true; - } - return false; - } - - @Override - public void close() { - commitBlock(); - } - - private void togglePause() { - host.run(() -> builder.stage() == Stage.PAUSED ? builder.resume() : builder.pause()); - } - - private void commitBlock() { - final String id = block.getText().strip(); - if (!id.isEmpty() && !id.equals(builder.settings().block())) { - host.run(() -> builder.setBlock(id)); - } - } - - private void capture(final int which) { - final var player = MinecraftClient.getInstance().player; - if (player == null) { - host.notice("зайди в мир"); - return; - } - final BlockPos pos = player.getBlockPos(); - if (which == POS1) { - builder.selection().setPos1(pos); - } else { - builder.selection().setPos2(pos); - } - host.notice("Pos" + which + ": " + pos.toShortString()); - } - - private Text posLabel(final String key, final Optional pos) { - return Text.translatable(key, pos.map(BlockPos::toShortString).orElse("-")); - } - - private ButtonWidget button(final String key, final Runnable action, final int x, final int y, - final int w, final int h) { - return ButtonWidget.builder(Text.translatable(key), b -> action.run()) - .dimensions(x, y, w, h).build(); - } -} diff --git a/src/main/java/dev/loki/satura/gui/screen/content/PlaceTab.java b/src/main/java/dev/loki/satura/gui/screen/content/PlaceTab.java deleted file mode 100644 index b06c2cb..0000000 --- a/src/main/java/dev/loki/satura/gui/screen/content/PlaceTab.java +++ /dev/null @@ -1,74 +0,0 @@ -package dev.loki.satura.gui.screen.content; - -import dev.loki.satura.feature.builder.BuildSettings; -import dev.loki.satura.feature.builder.BuilderFeature; -import dev.loki.satura.gui.screen.Tab; -import dev.loki.satura.gui.widget.CycleButton; -import dev.loki.satura.gui.widget.NumberSlider; -import java.util.List; -import java.util.Locale; -import net.minecraft.text.Text; - -/** Placement tab: strategy choice with its own option sliders and one-click presets. */ -public final class PlaceTab implements Tab { - - private static final int FIXED_ROWS = 2; - - private final Host host; - private final BuilderFeature builder; - private final List sliders; - - public PlaceTab(final Host host, final BuilderFeature builder, final int rowCap) { - this.host = host; - this.builder = builder; - final List all = builder.settings().optionSliders(); - final int sliderCap = Math.max(0, rowCap - FIXED_ROWS); - this.sliders = all.size() <= sliderCap ? all : all.subList(0, sliderCap); - } - - @Override - public int rows() { - return FIXED_ROWS + sliders.size(); - } - - @Override - public void build(final int y, final Grid g) { - int row = y; - host.add(new CycleButton(g.left(), row, g.inner(), g.rowH(), "satura.gui.strategy", - builder.strategyIds(), builder.settings().strategy().id(), - id -> { - host.run(() -> builder.setStrategy(id)); - host.reinit(); - })); - row += g.rowH() + g.gap(); - host.add(new CycleButton(g.left(), row, g.inner(), g.rowH(), "satura.gui.preset", - builder.presetIds(), BuildSettings.PRESET_CUSTOM, this::applyPreset)); - row += g.rowH() + g.gap(); - for (final BuildSettings.Slider option : sliders) { - host.add(new NumberSlider(g.left(), row, g.inner(), g.rowH(), - new NumberSlider.Spec(option.min(), option.max(), option.step(), option.value()), - v -> Text.literal(option.label() + ": " + format(option, v)), - v -> host.run(() -> builder.setOption(option.key(), format(option, v))))); - row += g.rowH() + g.gap(); - } - } - - @Override - public List lines() { - if (!sliders.isEmpty()) { - return List.of(); - } - return List.of(Text.translatable("satura.gui.options.hidden")); - } - - private void applyPreset(final String id) { - host.run(() -> builder.applyPreset(id)); - host.reinit(); - } - - private String format(final BuildSettings.Slider option, final double value) { - return option.integer() - ? String.valueOf(Math.round(value)) - : String.format(Locale.ROOT, "%.1f", value); - } -} diff --git a/src/main/java/dev/loki/satura/gui/screen/content/SupplyTab.java b/src/main/java/dev/loki/satura/gui/screen/content/SupplyTab.java deleted file mode 100644 index 4c6de00..0000000 --- a/src/main/java/dev/loki/satura/gui/screen/content/SupplyTab.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.loki.satura.gui.screen.content; - -import dev.loki.satura.gui.screen.Tab; -import java.util.List; -import net.minecraft.text.Text; - -/** Supply tab placeholder: the supply feature itself arrives with the next plan phase. */ -public final class SupplyTab implements Tab { - - @Override - public int rows() { - return 0; - } - - @Override - public void build(final int y, final Grid grid) { - // No widgets yet; the plan phase for supply will fill this tab. - } - - @Override - public List lines() { - return List.of(Text.translatable("satura.gui.supply.todo"), - Text.translatable("satura.gui.supply.todo2")); - } -} diff --git a/src/main/java/dev/loki/satura/gui/ui/core/Draw.java b/src/main/java/dev/loki/satura/gui/ui/core/Draw.java new file mode 100644 index 0000000..e609fbe --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/ui/core/Draw.java @@ -0,0 +1,126 @@ +package dev.loki.satura.gui.ui.core; + +import dev.loki.satura.render.Renderer; +import dev.loki.satura.render.color.Colors; +import dev.loki.satura.render.geom.Bounds; +import dev.loki.satura.render.msdf.MsdfFont; +import dev.loki.satura.render.msdf.MsdfFonts; + +/** Drawing helpers over {@link Renderer}; every call is shifted by the pane offset of this instance. */ +public final class Draw { + + private static final String ELLIPSIS = "..."; + private static final float GRID_STEPS = 2f; + private static final int GRID_SIDE = 3; + + private final Renderer renderer; + private final float offsetX; + private final float offsetY; + + public Draw(final Renderer renderer) { + this(renderer, 0f, 0f); + } + + private Draw(final Renderer renderer, final float offsetX, final float offsetY) { + this.renderer = renderer; + this.offsetX = offsetX; + this.offsetY = offsetY; + } + + /** Same renderer, translated further by (dx, dy). */ + public Draw shift(final float dx, final float dy) { + return new Draw(renderer, offsetX + dx, offsetY + dy); + } + + public static boolean inside(final Bounds b, final float x, final float y) { + return x >= b.x() && x < b.right() && y >= b.y() && y < b.bottom(); + } + + public void fill(final Bounds b, final float radius, final int color) { + renderer.rect(moved(b), radius, color); + } + + /** Left-to-right gradient fill. */ + public void gradient(final Bounds b, final float radius, final int from, final int to) { + final int[] grid = new int[GRID_SIDE * GRID_SIDE]; + for (int i = 0; i < grid.length; i++) { + grid[i] = Colors.lerp(from, to, i % GRID_SIDE / GRID_STEPS); + } + renderer.rect(moved(b), radius, grid); + } + + public void border(final Bounds b, final float radius, final int color) { + renderer.outline(moved(b), radius, 1f, color); + } + + public void glow(final Bounds b, final float radius, final float size, final float intensity, final int color) { + renderer.glow(moved(b), radius, 0f, size, intensity, color); + } + + public void shadow(final Bounds b, final float radius, final int color) { + renderer.shadow(moved(b), radius, color); + } + + public void blur(final Bounds b, final float radius, final float strength) { + renderer.blur(moved(b), radius, strength); + } + + public void text(final String s, final float x, final float y, final float size, final int color) { + renderer.text().draw(font(false), s, x + offsetX, y + offsetY, size, color); + } + + public void bold(final String s, final float x, final float y, final float size, final int color) { + renderer.text().draw(font(true), s, x + offsetX, y + offsetY, size, color); + } + + public void boldGradient(final String s, final float x, final float y, final float size, + final int from, final int to) { + renderer.text().drawGradient(font(true), s, x + offsetX, y + offsetY, size, from, to); + } + + /** Text centered both ways inside the bounds. */ + public void centered(final String s, final Bounds b, final float size, final int color, final boolean bold) { + final MsdfFont f = font(bold); + final float w = renderer.text().width(f, s, size); + final float h = renderer.text().height(f, size); + renderer.text().draw(f, s, b.x() + offsetX + (b.width() - w) / 2f, + b.y() + offsetY + (b.height() - h) / 2f, size, color); + } + + public float width(final String s, final float size, final boolean bold) { + return renderer.text().width(font(bold), s, size); + } + + public float lineHeight(final float size) { + return renderer.text().height(font(false), size); + } + + /** The string shortened with "..." so it fits into maxWidth. */ + public String fit(final String s, final float size, final boolean bold, final float maxWidth) { + if (width(s, size, bold) <= maxWidth) { + return s; + } + String cut = s; + while (!cut.isEmpty() && width(cut + ELLIPSIS, size, bold) > maxWidth) { + cut = cut.substring(0, cut.length() - 1); + } + return cut + ELLIPSIS; + } + + /** Clips to the bounds (not shifted: callers pass screen coordinates). */ + public void clip(final Bounds screenArea) { + renderer.pushScissor(screenArea); + } + + public void unclip() { + renderer.popScissor(); + } + + private Bounds moved(final Bounds b) { + return new Bounds(b.x() + offsetX, b.y() + offsetY, b.width(), b.height()); + } + + private MsdfFont font(final boolean bold) { + return renderer.text().font(bold ? MsdfFonts.BOLD : MsdfFonts.MONTSERRAT); + } +} diff --git a/src/main/java/dev/loki/satura/gui/ui/core/Palette.java b/src/main/java/dev/loki/satura/gui/ui/core/Palette.java new file mode 100644 index 0000000..e15f3e3 --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/ui/core/Palette.java @@ -0,0 +1,42 @@ +package dev.loki.satura.gui.ui.core; + +import dev.loki.satura.render.Theme; +import dev.loki.satura.render.color.Colors; + +/** Colors of the Satura UI: fixed dark surfaces plus the accent of the selected {@link Theme}. */ +public final class Palette { + + public static final int WINDOW = 0xF2101117; + public static final int SIDEBAR = 0xF20B0C11; + public static final int CARD = 0xFF181A22; + public static final int CARD_HOVER = 0xFF1F222C; + public static final int BORDER = 0xFF262935; + public static final int TEXT = 0xFFF0F1F5; + public static final int MUTED = 0xFF8B8FA0; + public static final int ON_ACCENT = 0xFFFFFFFF; + public static final int ON_ACCENT_MUTED = 0xCCFFFFFF; + public static final int DANGER = 0xFFD9534F; + public static final int OK = 0xFF4CC38A; + public static final int WARN = 0xFFE6B450; + public static final int SHADOW = 0x99000000; + + private static final int SECOND_STOP = 0xFF8A3DFF; + private static final float SECOND_MIX = 0.38f; + + private Palette() { + } + + /** Start of the accent gradient. */ + public static int gradientFrom() { + return Theme.get().accentHover(); + } + + /** End of the accent gradient: the accent pulled towards violet for depth. */ + public static int gradientTo() { + return Colors.lerp(Theme.get().accentPressed(), SECOND_STOP, SECOND_MIX); + } + + public static int accent() { + return Theme.get().accent(); + } +} diff --git a/src/main/java/dev/loki/satura/gui/ui/core/Tr.java b/src/main/java/dev/loki/satura/gui/ui/core/Tr.java new file mode 100644 index 0000000..265f32d --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/ui/core/Tr.java @@ -0,0 +1,19 @@ +package dev.loki.satura.gui.ui.core; + +import net.minecraft.client.resource.language.I18n; + +/** Translation shortcut for UI labels (lang files in assets/satura/lang). */ +public final class Tr { + + private Tr() { + } + + public static String t(final String key, final Object... args) { + return I18n.translate(key, args); + } + + /** Translation if the key exists, otherwise the fallback (ids of future strategies/shapes). */ + public static String orElse(final String key, final String fallback) { + return I18n.hasTranslation(key) ? I18n.translate(key) : fallback; + } +} diff --git a/src/main/java/dev/loki/satura/gui/ui/core/Widget.java b/src/main/java/dev/loki/satura/gui/ui/core/Widget.java new file mode 100644 index 0000000..0ac3303 --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/ui/core/Widget.java @@ -0,0 +1,44 @@ +package dev.loki.satura.gui.ui.core; + +import dev.loki.satura.render.geom.Bounds; +import net.minecraft.client.input.CharInput; +import net.minecraft.client.input.KeyInput; + +/** A drawn control. Coordinates are local to the owning pane; the pane translates mouse input. */ +public interface Widget { + + Bounds bounds(); + + void render(Draw draw, float mouseX, float mouseY); + + /** Mouse press inside the widget; true = consumed (the widget then also receives drags). */ + default boolean click(final float mouseX, final float mouseY, final int button) { + return false; + } + + default void drag(final float mouseX, final float mouseY) { + // not draggable by default + } + + default void release() { + // nothing to finish by default + } + + /** Another widget was clicked or the pane closed; drop focus and commit pending input. */ + default void blur() { + // nothing focused by default + } + + default boolean key(final KeyInput input) { + return false; + } + + default boolean chars(final CharInput input) { + return false; + } + + /** Whether the widget currently owns the keyboard (text input). */ + default boolean focused() { + return false; + } +} diff --git a/src/main/java/dev/loki/satura/gui/ui/input/TextBox.java b/src/main/java/dev/loki/satura/gui/ui/input/TextBox.java new file mode 100644 index 0000000..f287e3d --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/ui/input/TextBox.java @@ -0,0 +1,114 @@ +package dev.loki.satura.gui.ui.input; + +import dev.loki.satura.gui.ui.core.Draw; +import dev.loki.satura.gui.ui.core.Palette; +import dev.loki.satura.gui.ui.core.Widget; +import dev.loki.satura.render.geom.Bounds; +import java.util.function.Consumer; +import net.minecraft.client.input.CharInput; +import net.minecraft.client.input.KeyInput; +import org.lwjgl.glfw.GLFW; + +/** Single-line text input; Enter or losing focus commits a changed value. */ +public final class TextBox implements Widget { + + private static final float RADIUS = 6f; + private static final float TEXT_SIZE = 7.8f; + private static final float PAD = 8f; + private static final long BLINK_MS = 500L; + + private final Bounds bounds; + private final String hint; + private final int maxLength; + private final Consumer onCommit; + private String text; + private String committed; + private boolean focus; + + public TextBox(final Bounds bounds, final String initial, final String hint, final int maxLength, + final Consumer onCommit) { + this.bounds = bounds; + this.text = initial; + this.committed = initial; + this.hint = hint; + this.maxLength = maxLength; + this.onCommit = onCommit; + } + + @Override + public Bounds bounds() { + return bounds; + } + + @Override + public void render(final Draw draw, final float mx, final float my) { + draw.fill(bounds, RADIUS, Palette.CARD); + draw.border(bounds, RADIUS, focus ? Palette.accent() : Palette.BORDER); + final float y = bounds.y() + (bounds.height() - draw.lineHeight(TEXT_SIZE)) / 2f; + final float max = bounds.width() - PAD * 2f; + if (text.isEmpty() && !focus) { + draw.text(draw.fit(hint, TEXT_SIZE, false, max), bounds.x() + PAD, y, TEXT_SIZE, Palette.MUTED); + return; + } + final String shown = draw.fit(text, TEXT_SIZE, false, max); + draw.text(shown, bounds.x() + PAD, y, TEXT_SIZE, Palette.TEXT); + if (focus && System.currentTimeMillis() / BLINK_MS % 2 == 0) { + final float cx = bounds.x() + PAD + draw.width(shown, TEXT_SIZE, false) + 1f; + draw.fill(new Bounds(cx, y, 1f, draw.lineHeight(TEXT_SIZE)), 0f, Palette.TEXT); + } + } + + @Override + public boolean click(final float mx, final float my, final int button) { + focus = true; + return true; + } + + @Override + public void blur() { + if (focus) { + focus = false; + commit(); + } + } + + @Override + public boolean focused() { + return focus; + } + + @Override + public boolean key(final KeyInput input) { + if (!focus) { + return false; + } + if (input.key() == GLFW.GLFW_KEY_BACKSPACE) { + if (!text.isEmpty()) { + text = text.substring(0, text.length() - 1); + } + return true; + } + if (input.isEnter()) { + blur(); + return true; + } + return false; + } + + @Override + public boolean chars(final CharInput input) { + if (!focus || !input.isValidChar() || text.length() >= maxLength) { + return false; + } + text += input.asString(); + return true; + } + + private void commit() { + final String value = text.strip(); + if (!value.isEmpty() && !value.equals(committed)) { + committed = value; + onCommit.accept(value); + } + } +} diff --git a/src/main/java/dev/loki/satura/gui/ui/layout/Flow.java b/src/main/java/dev/loki/satura/gui/ui/layout/Flow.java new file mode 100644 index 0000000..94ccb02 --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/ui/layout/Flow.java @@ -0,0 +1,53 @@ +package dev.loki.satura.gui.ui.layout; + +import dev.loki.satura.render.geom.Bounds; +import java.util.ArrayList; +import java.util.List; + +/** Vertical flow of full-width rows and equal-column rows; tracks the total content height. */ +public final class Flow { + + private final float width; + private final float gap; + private float y; + + public Flow(final float width, final float gap) { + this.width = width; + this.gap = gap; + } + + public Bounds row(final float height) { + final Bounds row = new Bounds(0f, y, width, height); + y += height + gap; + return row; + } + + /** One row split into {@code count} equal cells. */ + public List cols(final int count, final float height) { + final List cells = new ArrayList<>(); + final float cell = (width - gap * (count - 1)) / count; + for (int i = 0; i < count; i++) { + cells.add(new Bounds((cell + gap) * i, y, cell, height)); + } + y += height + gap; + return cells; + } + + /** Cell {@code index} of a grid with {@code count} columns, opening a new row when needed. */ + public Bounds cell(final int index, final int count, final float height) { + final float cell = (width - gap * (count - 1)) / count; + final int col = index % count; + final float top = y + (index / count) * (height + gap); + return new Bounds((cell + gap) * col, top, cell, height); + } + + /** Advances past a grid of {@code items} cells laid out with {@link #cell}. */ + public void skipGrid(final int items, final int count, final float height) { + final int rows = (items + count - 1) / count; + y += rows * (height + gap); + } + + public float height() { + return Math.max(0f, y - gap); + } +} diff --git a/src/main/java/dev/loki/satura/gui/ui/layout/Pane.java b/src/main/java/dev/loki/satura/gui/ui/layout/Pane.java new file mode 100644 index 0000000..6da6ce8 --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/ui/layout/Pane.java @@ -0,0 +1,148 @@ +package dev.loki.satura.gui.ui.layout; + +import dev.loki.satura.gui.ui.core.Draw; +import dev.loki.satura.gui.ui.core.Palette; +import dev.loki.satura.gui.ui.core.Widget; +import dev.loki.satura.render.geom.Bounds; +import java.util.List; +import net.minecraft.client.input.CharInput; +import net.minecraft.client.input.KeyInput; + +/** Scrollable, clipped area holding widgets in content coordinates; routes input with the offset applied. */ +public final class Pane { + + private static final float WHEEL_STEP = 24f; + private static final float SCROLL_EASE = 0.35f; + private static final float BAR_W = 2f; + private static final int NONE = -1; + + private final Bounds area; + private List widgets = List.of(); + private float contentHeight; + private float scroll; + private float target; + private int pressed = NONE; + + public Pane(final Bounds area) { + this.area = area; + } + + public Bounds area() { + return area; + } + + /** Replaces the content; the scroll position is kept (clamped) so rebuilds do not jump. */ + public void set(final List content, final float height) { + blurAll(); + widgets = List.copyOf(content); + pressed = NONE; + contentHeight = height; + target = Math.min(target, maxScroll()); + scroll = Math.min(scroll, maxScroll()); + } + + /** Back to the top (page switch). */ + public void reset() { + scroll = 0f; + target = 0f; + } + + public void render(final Draw draw, final float mx, final float my) { + scroll += (target - scroll) * SCROLL_EASE; + final Draw local = draw.shift(area.x(), area.y() - scroll); + final float lx = mx - area.x(); + final float ly = my - area.y() + scroll; + draw.clip(area); + for (final Widget w : widgets) { + final Bounds b = w.bounds(); + if (b.bottom() >= scroll && b.y() <= scroll + area.height()) { + w.render(local, lx, ly); + } + } + draw.unclip(); + drawBar(draw); + } + + public boolean click(final float mx, final float my, final int button) { + if (!Draw.inside(area, mx, my)) { + blurAll(); + return false; + } + final float lx = mx - area.x(); + final float ly = my - area.y() + scroll; + pressed = NONE; + for (int i = widgets.size() - 1; i >= 0 && pressed == NONE; i--) { + final Widget w = widgets.get(i); + if (Draw.inside(w.bounds(), lx, ly) && w.click(lx, ly, button)) { + pressed = i; + } + } + for (int i = 0; i < widgets.size(); i++) { + if (i != pressed) { + widgets.get(i).blur(); + } + } + return pressed != NONE; + } + + public void drag(final float mx, final float my) { + if (pressed != NONE) { + widgets.get(pressed).drag(mx - area.x(), my - area.y() + scroll); + } + } + + public void release() { + if (pressed != NONE) { + widgets.get(pressed).release(); + pressed = NONE; + } + } + + public boolean scroll(final double mx, final double my, final double amount) { + if (!Draw.inside(area, (float) mx, (float) my)) { + return false; + } + target = Math.max(0f, Math.min(maxScroll(), target - (float) amount * WHEEL_STEP)); + return true; + } + + public boolean key(final KeyInput input) { + for (final Widget w : widgets) { + if (w.focused() && w.key(input)) { + return true; + } + } + return false; + } + + public boolean chars(final CharInput input) { + for (final Widget w : widgets) { + if (w.focused() && w.chars(input)) { + return true; + } + } + return false; + } + + /** Whether some widget owns the keyboard (text input), so global shortcuts must stay out. */ + public boolean typing() { + return widgets.stream().anyMatch(Widget::focused); + } + + public void blurAll() { + widgets.forEach(Widget::blur); + } + + private float maxScroll() { + return Math.max(0f, contentHeight - area.height()); + } + + private void drawBar(final Draw draw) { + if (contentHeight <= area.height()) { + return; + } + final float h = Math.max(12f, area.height() * area.height() / contentHeight); + final float y = area.y() + (area.height() - h) * (scroll / maxScroll()); + draw.fill(new Bounds(area.right() - BAR_W, y, BAR_W, h), BAR_W / 2f, Palette.BORDER); + } +} diff --git a/src/main/java/dev/loki/satura/gui/ui/widget/ActionButton.java b/src/main/java/dev/loki/satura/gui/ui/widget/ActionButton.java new file mode 100644 index 0000000..6d4958c --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/ui/widget/ActionButton.java @@ -0,0 +1,70 @@ +package dev.loki.satura.gui.ui.widget; + +import dev.loki.satura.gui.ui.core.Draw; +import dev.loki.satura.gui.ui.core.Palette; +import dev.loki.satura.gui.ui.core.Widget; +import dev.loki.satura.render.color.Colors; +import dev.loki.satura.render.geom.Bounds; +import java.util.function.Supplier; + +/** Push button with a dynamic label; primary buttons use the accent gradient. */ +public final class ActionButton implements Widget { + + /** Visual weight of the button. */ + public enum Kind { PRIMARY, NEUTRAL, DANGER } + + private static final float RADIUS = 6f; + private static final float TEXT_SIZE = 7.6f; + private static final float HOVER_EASE = 0.3f; + private static final int DANGER_FILL = 0xFF3A1D1F; + private static final int DANGER_HOVER = 0xFF4A2326; + + private final Bounds bounds; + private final Supplier label; + private final Kind kind; + private final Runnable action; + private float hover; + + public ActionButton(final Bounds bounds, final Supplier label, final Kind kind, + final Runnable action) { + this.bounds = bounds; + this.label = label; + this.kind = kind; + this.action = action; + } + + @Override + public Bounds bounds() { + return bounds; + } + + @Override + public void render(final Draw draw, final float mx, final float my) { + hover += ((Draw.inside(bounds, mx, my) ? 1f : 0f) - hover) * HOVER_EASE; + switch (kind) { + case PRIMARY -> { + final int lift = Colors.lerp(0x00000000, 0x30FFFFFF, hover); + draw.gradient(bounds, RADIUS, Palette.gradientFrom(), Palette.gradientTo()); + draw.fill(bounds, RADIUS, lift); + } + case DANGER -> { + draw.fill(bounds, RADIUS, Colors.lerp(DANGER_FILL, DANGER_HOVER, hover)); + draw.border(bounds, RADIUS, Palette.DANGER); + } + default -> { + draw.fill(bounds, RADIUS, Colors.lerp(Palette.CARD, Palette.CARD_HOVER, hover)); + draw.border(bounds, RADIUS, Palette.BORDER); + } + } + draw.centered(label.get(), bounds, TEXT_SIZE, kind == Kind.PRIMARY ? Palette.ON_ACCENT : Palette.TEXT, true); + } + + @Override + public boolean click(final float mx, final float my, final int button) { + if (button != 0) { + return false; + } + action.run(); + return true; + } +} diff --git a/src/main/java/dev/loki/satura/gui/ui/widget/Card.java b/src/main/java/dev/loki/satura/gui/ui/widget/Card.java new file mode 100644 index 0000000..62a28cf --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/ui/widget/Card.java @@ -0,0 +1,115 @@ +package dev.loki.satura.gui.ui.widget; + +import dev.loki.satura.gui.ui.core.Draw; +import dev.loki.satura.gui.ui.core.Palette; +import dev.loki.satura.gui.ui.core.Widget; +import dev.loki.satura.render.color.Colors; +import dev.loki.satura.render.geom.Bounds; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; + +/** Selectable card: title, a dynamic description line, optional badge and color swatch. */ +public final class Card implements Widget { + + private static final float RADIUS = 6f; + private static final float PAD = 8f; + private static final float TITLE_SIZE = 8.5f; + private static final float TEXT_SIZE = 6.8f; + private static final float BADGE_SIZE = 5.8f; + private static final float HOVER_EASE = 0.3f; + private static final float DOT_SIZE = 10f; + private static final float GLOW_SIZE = 7f; + private static final float GLOW_POWER = 0.35f; + + private final Bounds bounds; + private final String title; + private final Supplier subtitle; + private final BooleanSupplier selected; + private final Runnable onClick; + private String badge = ""; + private int swatch; + private float hover; + + public Card(final Bounds bounds, final String title, final Supplier subtitle, + final BooleanSupplier selected, final Runnable onClick) { + this.bounds = bounds; + this.title = title; + this.subtitle = subtitle; + this.selected = selected; + this.onClick = onClick; + } + + public Card badge(final String text) { + this.badge = text; + return this; + } + + public Card swatch(final int color) { + this.swatch = color; + return this; + } + + @Override + public Bounds bounds() { + return bounds; + } + + @Override + public void render(final Draw draw, final float mx, final float my) { + final boolean hovered = onClick != null && Draw.inside(bounds, mx, my); + hover += ((hovered ? 1f : 0f) - hover) * HOVER_EASE; + final boolean on = selected.getAsBoolean(); + if (on) { + draw.glow(bounds, RADIUS, GLOW_SIZE, GLOW_POWER, Palette.gradientFrom()); + draw.gradient(bounds, RADIUS, Palette.gradientFrom(), Palette.gradientTo()); + } else { + draw.fill(bounds, RADIUS, Colors.lerp(Palette.CARD, Palette.CARD_HOVER, hover)); + draw.border(bounds, RADIUS, Palette.BORDER); + } + float textX = bounds.x() + PAD; + if (swatch != 0) { + final Bounds dot = new Bounds(textX, bounds.y() + PAD, DOT_SIZE, DOT_SIZE); + draw.fill(dot, DOT_SIZE / 2f, swatch); + textX += DOT_SIZE + PAD / 2f; + } + final float room = bounds.right() - PAD - textX - badgeWidth(draw); + draw.bold(draw.fit(title, TITLE_SIZE, true, room), textX, bounds.y() + PAD, TITLE_SIZE, + on ? Palette.ON_ACCENT : Palette.TEXT); + drawSubtitle(draw, on, textX); + drawBadge(draw, on); + } + + @Override + public boolean click(final float mx, final float my, final int button) { + if (onClick == null || button != 0) { + return false; + } + onClick.run(); + return true; + } + + private void drawSubtitle(final Draw draw, final boolean on, final float textX) { + final String line = subtitle.get(); + if (line.isEmpty()) { + return; + } + final float y = bounds.y() + PAD + draw.lineHeight(TITLE_SIZE) + 3f; + draw.text(draw.fit(line, TEXT_SIZE, false, bounds.right() - PAD - textX), textX, y, TEXT_SIZE, + on ? Palette.ON_ACCENT_MUTED : Palette.MUTED); + } + + private void drawBadge(final Draw draw, final boolean on) { + if (badge.isEmpty()) { + return; + } + final float w = badgeWidth(draw) - PAD / 2f; + final Bounds pill = new Bounds(bounds.right() - PAD - w, bounds.y() + PAD - 1f, w, + draw.lineHeight(BADGE_SIZE) + 4f); + draw.fill(pill, pill.height() / 2f, on ? 0x33FFFFFF : 0x22FFFFFF); + draw.centered(badge, pill, BADGE_SIZE, on ? Palette.ON_ACCENT : Palette.MUTED, true); + } + + private float badgeWidth(final Draw draw) { + return badge.isEmpty() ? 0f : draw.width(badge, BADGE_SIZE, true) + PAD + PAD / 2f; + } +} diff --git a/src/main/java/dev/loki/satura/gui/ui/widget/Label.java b/src/main/java/dev/loki/satura/gui/ui/widget/Label.java new file mode 100644 index 0000000..bf0471e --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/ui/widget/Label.java @@ -0,0 +1,51 @@ +package dev.loki.satura.gui.ui.widget; + +import dev.loki.satura.gui.ui.core.Draw; +import dev.loki.satura.gui.ui.core.Palette; +import dev.loki.satura.gui.ui.core.Widget; +import dev.loki.satura.render.geom.Bounds; +import java.util.Locale; + +/** Section caption or a plain muted text line. */ +public final class Label implements Widget { + + private static final float CAPTION_SIZE = 6.6f; + private static final float TEXT_SIZE = 7.2f; + private static final float CAPTION_TOP = 7f; + + private final Bounds bounds; + private final String text; + private final boolean caption; + + private Label(final Bounds bounds, final String text, final boolean caption) { + this.bounds = bounds; + this.text = text; + this.caption = caption; + } + + /** Small bold section header. */ + public static Label caption(final Bounds bounds, final String text) { + return new Label(bounds, text, true); + } + + /** Muted body line. */ + public static Label line(final Bounds bounds, final String text) { + return new Label(bounds, text, false); + } + + @Override + public Bounds bounds() { + return bounds; + } + + @Override + public void render(final Draw draw, final float mx, final float my) { + if (caption) { + draw.bold(text.toUpperCase(Locale.ROOT), bounds.x() + 1f, bounds.y() + CAPTION_TOP, CAPTION_SIZE, + Palette.MUTED); + } else { + draw.text(draw.fit(text, TEXT_SIZE, false, bounds.width()), bounds.x(), bounds.y(), TEXT_SIZE, + Palette.MUTED); + } + } +} diff --git a/src/main/java/dev/loki/satura/gui/ui/widget/SliderBar.java b/src/main/java/dev/loki/satura/gui/ui/widget/SliderBar.java new file mode 100644 index 0000000..860e205 --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/ui/widget/SliderBar.java @@ -0,0 +1,102 @@ +package dev.loki.satura.gui.ui.widget; + +import dev.loki.satura.gui.ui.core.Draw; +import dev.loki.satura.gui.ui.core.Palette; +import dev.loki.satura.gui.ui.core.Widget; +import dev.loki.satura.render.geom.Bounds; +import java.util.Locale; +import java.util.function.DoubleConsumer; + +/** Horizontal slider with a label and a value readout; snaps to the step while dragging. */ +public final class SliderBar implements Widget { + + /** Slider range: bounds, step (0 = continuous) and the initial value. */ + public record Range(double min, double max, double step, double initial) { + } + + private static final float RADIUS = 6f; + private static final float TEXT_SIZE = 7.2f; + private static final float TRACK_H = 3f; + private static final float KNOB = 8f; + private static final float PAD = 8f; + private static final float TRACK_GAP = 8f; + private static final float NO_STEP = 0f; + + private final Bounds bounds; + private final String label; + private final Range range; + private final DoubleConsumer onChange; + private double value; + private boolean dragging; + + public SliderBar(final Bounds bounds, final String label, final Range range, final DoubleConsumer onChange) { + this.bounds = bounds; + this.label = label; + this.range = range; + this.onChange = onChange; + this.value = range.initial(); + } + + @Override + public Bounds bounds() { + return bounds; + } + + @Override + public void render(final Draw draw, final float mx, final float my) { + draw.fill(bounds, RADIUS, Palette.CARD); + draw.border(bounds, RADIUS, dragging ? Palette.accent() : Palette.BORDER); + draw.text(draw.fit(label, TEXT_SIZE, false, bounds.width() * 0.6f), bounds.x() + PAD, bounds.y() + 5f, + TEXT_SIZE, Palette.TEXT); + final String readout = format(value); + draw.bold(readout, bounds.right() - PAD - draw.width(readout, TEXT_SIZE, true), bounds.y() + 5f, + TEXT_SIZE, Palette.accent()); + final float left = bounds.x() + PAD; + final float width = bounds.width() - PAD * 2f; + final float y = bounds.bottom() - TRACK_GAP; + draw.fill(new Bounds(left, y, width, TRACK_H), TRACK_H / 2f, Palette.BORDER); + final float filled = width * (float) fraction(); + draw.gradient(new Bounds(left, y, Math.max(filled, TRACK_H), TRACK_H), TRACK_H / 2f, + Palette.gradientFrom(), Palette.gradientTo()); + draw.fill(new Bounds(left + filled - KNOB / 2f, y + TRACK_H / 2f - KNOB / 2f, KNOB, KNOB), KNOB / 2f, + Palette.TEXT); + } + + @Override + public boolean click(final float mx, final float my, final int button) { + if (button != 0) { + return false; + } + dragging = true; + drag(mx, my); + return true; + } + + @Override + public void drag(final float mx, final float my) { + final float left = bounds.x() + PAD; + final double t = Math.max(0.0, Math.min(1.0, (mx - left) / (bounds.width() - PAD * 2f))); + double next = range.min() + (range.max() - range.min()) * t; + if (range.step() > NO_STEP) { + next = Math.round(next / range.step()) * range.step(); + } + next = Math.max(range.min(), Math.min(range.max(), next)); + if (next != value) { + value = next; + onChange.accept(value); + } + } + + @Override + public void release() { + dragging = false; + } + + private double fraction() { + return range.max() <= range.min() ? 0.0 : (value - range.min()) / (range.max() - range.min()); + } + + private String format(final double v) { + return range.step() >= 1.0 ? String.valueOf(Math.round(v)) : String.format(Locale.ROOT, "%.2f", v); + } +} diff --git a/src/main/java/dev/loki/satura/gui/widget/CycleButton.java b/src/main/java/dev/loki/satura/gui/widget/CycleButton.java deleted file mode 100644 index 4b39876..0000000 --- a/src/main/java/dev/loki/satura/gui/widget/CycleButton.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.loki.satura.gui.widget; - -import java.util.List; -import java.util.function.Consumer; -import net.minecraft.client.gui.widget.ButtonWidget; -import net.minecraft.client.input.AbstractInput; - -/** - * Cycle button: a click steps through the values and hands the chosen one to the owner. - * The label is a translatable string with {@code %s} in place of the value. Rendering is vanilla - * (inherited from ButtonWidget.Text). - */ -public final class CycleButton extends ButtonWidget.Text { - - private final List values; - private final String labelKey; - private final Consumer onChange; - private int index; - - public CycleButton(final int x, final int y, final int width, final int height, - final String labelKey, final List values, - final String initial, final Consumer onChange) { - super(x, y, width, height, net.minecraft.text.Text.empty(), b -> { }, DEFAULT_NARRATION_SUPPLIER); - if (values.isEmpty()) { - throw new IllegalArgumentException("cycle without values: " + labelKey); - } - this.values = List.copyOf(values); - this.labelKey = labelKey; - this.onChange = onChange; - this.index = Math.max(0, this.values.indexOf(initial)); - refresh(); - } - - /** Currently selected value. */ - public String value() { - return values.get(index); - } - - @Override - public void onPress(final AbstractInput input) { - index = (index + 1) % values.size(); - refresh(); - onChange.accept(values.get(index)); - } - - private void refresh() { - setMessage(net.minecraft.text.Text.translatable(labelKey, values.get(index))); - } -} diff --git a/src/main/java/dev/loki/satura/gui/widget/NumberSlider.java b/src/main/java/dev/loki/satura/gui/widget/NumberSlider.java deleted file mode 100644 index 166db44..0000000 --- a/src/main/java/dev/loki/satura/gui/widget/NumberSlider.java +++ /dev/null @@ -1,56 +0,0 @@ -package dev.loki.satura.gui.widget; - -import java.util.function.Consumer; -import java.util.function.DoubleFunction; -import net.minecraft.client.gui.widget.SliderWidget; -import net.minecraft.text.Text; - -/** Number slider (int/float) with a step; range, label and receiver are set by the owner. */ -public final class NumberSlider extends SliderWidget { - - private static final double NO_STEP = 0.0; - - /** Slider range: bounds, step (0 = continuous) and the initial value. */ - public record Spec(double min, double max, double step, double initial) { - } - - private final double min; - private final double max; - private final double step; - private final DoubleFunction label; - private final Consumer onChange; - - public NumberSlider(final int x, final int y, final int width, final int height, final Spec spec, - final DoubleFunction label, final Consumer onChange) { - super(x, y, width, height, Text.empty(), normalized(spec.min(), spec.max(), spec.initial())); - this.min = spec.min(); - this.max = spec.max(); - this.step = spec.step(); - this.label = label; - this.onChange = onChange; - updateMessage(); - } - - /** Current value in range units (step applied). */ - public double current() { - final double raw = min + (max - min) * value; - return step == NO_STEP ? raw : Math.round(raw / step) * step; - } - - @Override - protected void updateMessage() { - setMessage(label.apply(current())); - } - - @Override - protected void applyValue() { - onChange.accept(current()); - } - - private static double normalized(final double min, final double max, final double value) { - if (max <= min) { - return 0.0; - } - return Math.clamp((value - min) / (max - min), 0.0, 1.0); - } -} diff --git a/src/main/java/dev/loki/satura/interaction/movement/WalkPort.java b/src/main/java/dev/loki/satura/interaction/movement/WalkPort.java index fddf745..535b07e 100644 --- a/src/main/java/dev/loki/satura/interaction/movement/WalkPort.java +++ b/src/main/java/dev/loki/satura/interaction/movement/WalkPort.java @@ -6,5 +6,10 @@ public interface WalkPort { /** Start walking to (x, z); false if the walker is unavailable. */ boolean walkTo(double x, double z); + /** Start walking to stand exactly in the given block; false if the walker is unavailable. */ + default boolean walkToBlock(final int x, final int y, final int z) { + return false; + } + void cancel(); } diff --git a/src/main/java/dev/loki/satura/interaction/place/PlaceContext.java b/src/main/java/dev/loki/satura/interaction/place/PlaceContext.java index c8a6a19..4101da1 100644 --- a/src/main/java/dev/loki/satura/interaction/place/PlaceContext.java +++ b/src/main/java/dev/loki/satura/interaction/place/PlaceContext.java @@ -33,8 +33,16 @@ public interface PlaceContext { void setVelocity(double x, double y, double z); - /** Enable flight if it is allowed. */ + /** + * Starts flying like the double-jump does (and tells the server), if flight is allowed: creative + * or a granted {@code /fly}. Never grants flight by itself. + */ void enableFlight(); + /** Switch creative flight off so walking strategies really walk. */ + default void disableFlight() { + // flying is not a concern for the context by default + } + long nowMs(); } diff --git a/src/main/java/dev/loki/satura/interaction/place/PlaceStrategy.java b/src/main/java/dev/loki/satura/interaction/place/PlaceStrategy.java index dd0626c..f3b56e7 100644 --- a/src/main/java/dev/loki/satura/interaction/place/PlaceStrategy.java +++ b/src/main/java/dev/loki/satura/interaction/place/PlaceStrategy.java @@ -25,6 +25,11 @@ public interface PlaceStrategy { return 1; } + /** Whether the strategy moves the player by flying (needs creative or an allowed flight). */ + default boolean needsFlight() { + return false; + } + /** Release keys, cancel walking, drop transient state; called on start/stop/pause. */ default void reset() { // stateless by default diff --git a/src/main/java/dev/loki/satura/interaction/place/client/MinecraftPlaceContext.java b/src/main/java/dev/loki/satura/interaction/place/client/MinecraftPlaceContext.java index 01d88d6..496aa99 100644 --- a/src/main/java/dev/loki/satura/interaction/place/client/MinecraftPlaceContext.java +++ b/src/main/java/dev/loki/satura/interaction/place/client/MinecraftPlaceContext.java @@ -75,11 +75,18 @@ public final class MinecraftPlaceContext implements PlaceContext { @Override public void enableFlight() { final ClientPlayerEntity player = client.player; - if (player.getAbilities().allowFlying) { - player.getAbilities().flying = true; + final var abilities = player.getAbilities(); + if (abilities.allowFlying && !abilities.flying) { + abilities.flying = true; + player.sendAbilitiesUpdate(); } } + @Override + public void disableFlight() { + client.player.getAbilities().flying = false; + } + @Override public long nowMs() { return System.currentTimeMillis(); diff --git a/src/main/java/dev/loki/satura/interaction/place/option/CommonOptions.java b/src/main/java/dev/loki/satura/interaction/place/option/CommonOptions.java index 8a4074f..cb7ee6b 100644 --- a/src/main/java/dev/loki/satura/interaction/place/option/CommonOptions.java +++ b/src/main/java/dev/loki/satura/interaction/place/option/CommonOptions.java @@ -13,9 +13,9 @@ public final class CommonOptions { public static final Option REACH = new Option("reach", "Дальность", OptionType.DOUBLE, 3.0, 6.0, 0.1, 4.5); public static final Option HOVER = - new Option("hover", "Высота над слоем", OptionType.DOUBLE, 0.0, 1.5, 0.5, 1.0); + new Option("hover", "Высота над слоем", OptionType.DOUBLE, 0.0, 3.0, 0.5, 2.0); public static final Option FLY_SPEED = - new Option("flySpeed", "Скорость полёта", OptionType.DOUBLE, 0.05, 1.0, 0.05, 0.25); + new Option("flySpeed", "Скорость полёта", OptionType.DOUBLE, 0.05, 1.0, 0.05, 0.5); public static final Option BAND_LAYERS = new Option("bandLayers", "Слоёв за проход", OptionType.INT, MIN_LAYERS, MAX_LAYERS, 1, 2); diff --git a/src/main/java/dev/loki/satura/interaction/place/option/OptionValues.java b/src/main/java/dev/loki/satura/interaction/place/option/OptionValues.java index da33e55..497f723 100644 --- a/src/main/java/dev/loki/satura/interaction/place/option/OptionValues.java +++ b/src/main/java/dev/loki/satura/interaction/place/option/OptionValues.java @@ -29,6 +29,11 @@ public final class OptionValues { return get(option) >= 1.0; } + /** Back to the declared defaults. */ + public void reset() { + values.clear(); + } + /** Set the value by key; false if there is no such parameter. */ public boolean set(final String key, final double value) { final Option option = known.get(key); diff --git a/src/main/java/dev/loki/satura/interaction/place/strategy/BandStack.java b/src/main/java/dev/loki/satura/interaction/place/strategy/BandStack.java index cd38f51..1ca12ff 100644 --- a/src/main/java/dev/loki/satura/interaction/place/strategy/BandStack.java +++ b/src/main/java/dev/loki/satura/interaction/place/strategy/BandStack.java @@ -24,6 +24,11 @@ public final class BandStack implements PlaceStrategy { this.core = new ColumnPlacing(params, () -> params.getInt(CommonOptions.BAND_LAYERS), placer); } + @Override + public boolean needsFlight() { + return true; + } + @Override public String id() { return "band_stack"; diff --git a/src/main/java/dev/loki/satura/interaction/place/strategy/ColumnDrop.java b/src/main/java/dev/loki/satura/interaction/place/strategy/ColumnDrop.java index 7d18af7..e11c08c 100644 --- a/src/main/java/dev/loki/satura/interaction/place/strategy/ColumnDrop.java +++ b/src/main/java/dev/loki/satura/interaction/place/strategy/ColumnDrop.java @@ -23,6 +23,11 @@ public final class ColumnDrop implements PlaceStrategy { this.core = new ColumnPlacing(params, () -> 1, placer); } + @Override + public boolean needsFlight() { + return true; + } + @Override public String id() { return "column_drop"; diff --git a/src/main/java/dev/loki/satura/interaction/place/strategy/ColumnPlacing.java b/src/main/java/dev/loki/satura/interaction/place/strategy/ColumnPlacing.java index 1099d8d..7b76598 100644 --- a/src/main/java/dev/loki/satura/interaction/place/strategy/ColumnPlacing.java +++ b/src/main/java/dev/loki/satura/interaction/place/strategy/ColumnPlacing.java @@ -52,15 +52,14 @@ public final class ColumnPlacing { return PlaceResult.WAIT; } final BlockPos column = target.column(); - final int layerY = band.get(0).getY(); final int bandTop = band.get(band.size() - 1).getY(); ctx.enableFlight(); final double reach = values.get(CommonOptions.REACH); - final double height = FlightControl.height(layerY, bandTop, values.get(CommonOptions.HOVER), - reach, EYE_MARGIN); + final double height = FlightControl.height(target.windowFloor(), target.windowTop(), + values.get(CommonOptions.HOVER), reach, EYE_MARGIN); final Vec3d feet = ctx.feetPos(); final Vec3d goal = new Vec3d(column.getX() + CENTER, height, column.getZ() + CENTER); - final Vec3d v = FlightControl.velocity(feet, goal, values.get(CommonOptions.FLY_SPEED)); + final Vec3d v = FlightControl.smooth(feet, goal, values.get(CommonOptions.FLY_SPEED)); ctx.setVelocity(v.x, v.y, v.z); ctx.lookDown(); if (!overColumn(feet, column) || feet.y < bandTop + 1.0 - FEET_EPS) { diff --git a/src/main/java/dev/loki/satura/interaction/place/strategy/FlightControl.java b/src/main/java/dev/loki/satura/interaction/place/strategy/FlightControl.java index dc8ba89..6cb6aae 100644 --- a/src/main/java/dev/loki/satura/interaction/place/strategy/FlightControl.java +++ b/src/main/java/dev/loki/satura/interaction/place/strategy/FlightControl.java @@ -7,10 +7,36 @@ import net.minecraft.util.math.Vec3d; public final class FlightControl { private static final double ARRIVE_EPS = 0.05; + /** Horizontal approach: speed follows this share of the remaining distance (pveclient fly route). */ + private static final double APPROACH_GAIN = 0.35; + /** Slowest approach speed as a share of the maximum, so the final metre does not crawl. */ + private static final double MIN_SPEED_SHARE = 0.25; + /** Vertical correction per tick as a share of the height error (AutoBuild flight). */ + private static final double VERTICAL_GAIN = 0.25; private FlightControl() { } + /** + * Eased flight: horizontal speed shrinks towards the goal instead of stopping dead, vertical speed + * is proportional to the height error. No overshoot and no jerk when the target changes. + */ + public static Vec3d smooth(final Vec3d feet, final Vec3d goal, final double maxSpeed) { + final double dx = goal.x - feet.x; + final double dz = goal.z - feet.z; + final double dist = Math.hypot(dx, dz); + double vx = 0.0; + double vz = 0.0; + if (dist > ARRIVE_EPS) { + final double step = Math.min(dist, Math.min(maxSpeed, + Math.max(maxSpeed * MIN_SPEED_SHARE, dist * APPROACH_GAIN))); + vx = dx / dist * step; + vz = dz / dist * step; + } + final double vy = MathHelper.clamp((goal.y - feet.y) * VERTICAL_GAIN, -maxSpeed, maxSpeed); + return new Vec3d(vx, vy, vz); + } + public static Vec3d velocity(final Vec3d feet, final Vec3d goal, final double speed) { final double dx = goal.x - feet.x; final double dz = goal.z - feet.z; @@ -26,10 +52,10 @@ public final class FlightControl { return new Vec3d(vx, vy, vz); } - /** Flight height: min(bandTop+hover, layerY+reach-1.7), but not below the layer top (no standing in a block). */ - public static double height(final int layerY, final int bandTop, final double hover, - final double reach, final double eyeMargin) { - final double capped = Math.min(bandTop + hover, layerY + reach - eyeMargin); - return Math.max(capped, bandTop + 1.0); + /** Flight height: min(windowTop+hover, windowFloor+reach-1.7), never below the window top plus one. */ + public static double height(final int windowFloor, final int windowTop, final double hover, + final double reach, final double eyeMargin) { + final double capped = Math.min(windowTop + hover, windowFloor + reach - eyeMargin); + return Math.max(capped, windowTop + 1.0); } } diff --git a/src/main/java/dev/loki/satura/interaction/place/strategy/ground/BaritoneWalk.java b/src/main/java/dev/loki/satura/interaction/place/strategy/ground/BaritoneWalk.java index c4372ef..e16b5c4 100644 --- a/src/main/java/dev/loki/satura/interaction/place/strategy/ground/BaritoneWalk.java +++ b/src/main/java/dev/loki/satura/interaction/place/strategy/ground/BaritoneWalk.java @@ -10,22 +10,23 @@ import dev.loki.satura.interaction.place.option.Option; import dev.loki.satura.interaction.place.option.OptionValues; import dev.loki.satura.interaction.place.support.BlockPlacer; import java.util.List; +import java.util.Optional; +import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; /** - * S6 BaritoneWalk: Baritone (through the {@link WalkPort}) only walks to the column, - * the placement itself is precise (LOS) once in reach. Aithereal settings are applied - * by the bridge: allowBreak/allowPlace = false. + * S6 BaritoneWalk: Baritone (through the {@link WalkPort}) only walks to a stand block next to the + * cell (not into the column, or it would drop down into it); the placement itself is ours once the + * player stands there. Settings are applied by the bridge: allowBreak/allowPlace = false. */ public final class BaritoneWalk implements PlaceStrategy { private static final List