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
This commit is contained in:
Loki 2026-10-31 21:07:57 +01:00
parent e2bdf031a8
commit 2ae354f888
Signed by: boba
GPG key ID: 253067914055423B
88 changed files with 2652 additions and 823 deletions

View file

@ -9,4 +9,7 @@
<!-- Рендер: константы GPU/цветов/вершин, много параметров у draw-вызовов -->
<suppress checks="MagicNumber|ParameterNumber"
files="[\\/]satura[\\/]render[\\/]"/>
<!-- GUI: layout geometry (sizes, paddings, font sizes) is inherently numeric -->
<suppress checks="MagicNumber|ParameterNumber"
files="[\\/]satura[\\/]gui[\\/]"/>
</suppressions>

View file

@ -7,7 +7,9 @@
<description>Satura ruleset: errorprone, bestpractices, design, codestyle, performance, multithreading, security</description>
<rule ref="category/java/errorprone.xml"/>
<rule ref="category/java/errorprone.xml">
<exclude name="AvoidFieldNameMatchingMethodName"/>
</rule>
<rule ref="category/java/bestpractices.xml">
<exclude name="GuardLogStatement"/>

View file

@ -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<String> 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<String> 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);
}
}

View file

@ -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<String, String> 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());
}

View file

@ -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<String> 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);
}

View file

@ -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<StrategyInfo> 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;

View file

@ -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<Profile> persist;
private final ProfileBook profiles;
private String profileName;
private BuildEngine engine;
public BuilderFeature(final CommandRegistry commands, final Supplier<BlockPos> feet,
final EngineAssembler assembler, final BuildSettings settings,
final Consumer<Profile> 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<PlaceStrategy> 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<PlaceStrategy> 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<BuildSession.Snapshot> 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<String> profileIds() {
final List<String> 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<String> 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;
}
}

View file

@ -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);

View file

@ -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<PlaceStrategy> 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));
}
}

View file

@ -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();

View file

@ -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()));
}

View file

@ -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();

View file

@ -29,6 +29,12 @@ public interface BuildControl {
String applyPreset(String id);
List<String> profileIds();
String profile();
String switchProfile(String id);
List<String> blockIds();
List<String> strategyIds();

View file

@ -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));
}

View file

@ -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<String> blockReason() {
final Optional<String> 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<String> blocked = deps.game().blockReason();
final Optional<String> blocked = blockReason();
if (blocked.isPresent()) {
if (NO_FLIGHT.equals(blocked.get())) {
deps.chat().accept("Пауза: " + NO_FLIGHT + ". Продолжу сам, когда полёт включится");
}
session.pause(blocked.get(), true);
return;
}

View file

@ -8,6 +8,9 @@ public interface GameState {
/** Reason why building is not possible now (screen, death, no world); empty when it is possible. */
Optional<String> 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();
}

View file

@ -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;

View file

@ -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();
}

View file

@ -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<BlockPos> done;
private final Predicate<BlockPos> solid;
private final List<BlockPos> columns;
private int bandFloor;
public Planner(final Area area, final Shape shape, final int bandLayers,
final Predicate<BlockPos> 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<BlockPos> done, final Predicate<BlockPos> 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<BlockPos> 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<BlockPos> 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<BlockPos> pending(final BlockPos column, final int fromY, final int toY) {
final List<BlockPos> 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);
}
}

View file

@ -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()) {

View file

@ -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<Widget> out = new ArrayList<>();
final List<Bounds> pos = flow.cols(2, POS_H);
out.add(posCard(pos.get(0), POS1));
out.add(posCard(pos.get(1), 2));
final List<Bounds> 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<String> shapes = builder.shapeIds();
final List<Bounds> 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<BlockPos> 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());
}
}

View file

@ -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<String> action);
/** Runs the action quietly: only an error produces a toast (sliders, live edits). */
void apply(Supplier<String> action);
void notice(String text);
/** The page structure changed (selection, strategy, profile): lay the widgets out again. */
void rebuild();
}

View file

@ -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<Widget> widgets, float height) {
}
}

View file

@ -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<Widget> out = new ArrayList<>();
out.add(Label.caption(flow.row(CAPTION_H), Tr.t("satura.ui.preset")));
final List<String> presets = builder.presetIds();
final List<Bounds> 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<BuildSettings.StrategyInfo> 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);
}
}

View file

@ -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<Widget> out = new ArrayList<>();
final List<String> 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();
});
}
}

View file

@ -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<String> 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<Widget> 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());
}
}

View file

@ -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<Widget> out = new ArrayList<>();
final List<Theme> 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());
}
}

View file

@ -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<String> 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 extends ClickableWidget> W add(final W widget) {
return addDrawableChild(widget);
}
@Override
public void addField(final TextFieldWidget field) {
addSelectableChild(field);
}
@Override
public void run(final Supplier<String> 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);
}
}

View file

@ -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<String> titles;
private final float[] hover;
Nav(final Bounds area, final List<String> 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);
}
}

View file

@ -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<Page> 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));
}
}

View file

@ -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);
}
}

View file

@ -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<String> 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<Page> 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<String> 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<String> 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 : "");
}
}

View file

@ -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<BuildSession.Snapshot> 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;
};
}
}

View file

@ -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<Text> 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 extends ClickableWidget> 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<String> 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();
}
}

View file

@ -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<BlockPos> pos) {
return Text.translatable(key, pos.<String>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();
}
}

View file

@ -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<BuildSettings.Slider> sliders;
public PlaceTab(final Host host, final BuilderFeature builder, final int rowCap) {
this.host = host;
this.builder = builder;
final List<BuildSettings.Slider> 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<Text> 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);
}
}

View file

@ -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<Text> lines() {
return List.of(Text.translatable("satura.gui.supply.todo"),
Text.translatable("satura.gui.supply.todo2"));
}
}

View file

@ -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);
}
}

View file

@ -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();
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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<String> 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<String> 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);
}
}
}

View file

@ -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<Bounds> cols(final int count, final float height) {
final List<Bounds> 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);
}
}

View file

@ -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<Widget> 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<Widget> 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);
}
}

View file

@ -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<String> label;
private final Kind kind;
private final Runnable action;
private float hover;
public ActionButton(final Bounds bounds, final Supplier<String> 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;
}
}

View file

@ -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<String> 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<String> 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;
}
}

View file

@ -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);
}
}
}

View file

@ -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);
}
}

View file

@ -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<String> values;
private final String labelKey;
private final Consumer<String> onChange;
private int index;
public CycleButton(final int x, final int y, final int width, final int height,
final String labelKey, final List<String> values,
final String initial, final Consumer<String> 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)));
}
}

View file

@ -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<Text> label;
private final Consumer<Double> onChange;
public NumberSlider(final int x, final int y, final int width, final int height, final Spec spec,
final DoubleFunction<Text> label, final Consumer<Double> 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);
}
}

View file

@ -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();
}

View file

@ -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();
}

View file

@ -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

View file

@ -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();

View file

@ -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);

View file

@ -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);

View file

@ -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";

View file

@ -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";

View file

@ -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) {

View file

@ -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);
}
}

View file

@ -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<Option> DECLARED = List.of(CommonOptions.DELAY_MS, CommonOptions.REACH);
private static final double CENTER = 0.5;
private final OptionValues params = new OptionValues(DECLARED);
private final WalkPort walk;
private final BlockPlacer placer;
private boolean enRoute;
private Optional<BlockPos> goal = Optional.empty();
public BaritoneWalk(final WalkPort walk, final BlockPlacer placer) {
this.walk = walk;
@ -54,29 +55,29 @@ public final class BaritoneWalk implements PlaceStrategy {
@Override
public void reset() {
enRoute = false;
goal = Optional.empty();
walk.cancel();
}
@Override
public PlaceResult tick(final PlaceContext ctx, final ColumnTarget target) {
ctx.disableFlight();
final BlockPos cell = target.cells().get(0);
final Vec3d feet = ctx.feetPos();
final double dx = target.column().getX() + CENTER - feet.x;
final double dz = target.column().getZ() + CENTER - feet.z;
final double dist = Math.hypot(dx, dz);
final double reach = params.get(CommonOptions.REACH);
if (dist > reach - 1.0) {
return walkTo(target);
final Optional<BlockPos> stand = StandFinder.find(ctx, cell, feet);
if (stand.isEmpty() || StandFinder.at(feet, stand.get())) {
reset();
return placer.place(ctx, cell, reach, params.getInt(CommonOptions.DELAY_MS));
}
walk.cancel();
return placer.place(ctx, target.cells().get(0), reach, params.getInt(CommonOptions.DELAY_MS));
}
private PlaceResult walkTo(final ColumnTarget target) {
if (enRoute || walk.walkTo(target.column().getX() + CENTER, target.column().getZ() + CENTER)) {
enRoute = true;
if (stand.equals(goal)) {
return PlaceResult.WAIT;
}
return PlaceResult.FAILED;
final BlockPos spot = stand.get();
if (!walk.walkToBlock(spot.getX(), spot.getY(), spot.getZ())) {
return PlaceResult.FAILED;
}
goal = stand;
return PlaceResult.WAIT;
}
}

View file

@ -1,6 +1,7 @@
package dev.loki.satura.interaction.place.strategy.ground;
import dev.loki.satura.interaction.movement.MovementController;
import java.util.function.Predicate;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
@ -9,6 +10,11 @@ import net.minecraft.util.math.Vec3d;
public final class GroundMove {
private static final double CENTER = 0.5;
private static final double ARRIVE_EPS = 0.05;
/** How far ahead the floor is checked before a step, in blocks. */
private static final double STEP = 0.7;
/** Look-ahead that makes the player sneak before reaching an edge. */
private static final double SNEAK_LOOK = 1.2;
private final MovementController movement;
@ -16,9 +22,32 @@ public final class GroundMove {
this.movement = movement;
}
/** One walking tick towards the column; true when close enough to act. */
public boolean approach(final Vec3d feet, final BlockPos column) {
return movement.walkTo(column.getX() + CENTER, column.getZ() + CENTER);
/**
* One walking tick towards the stand block. Never steps into a drop deeper than one block:
* at an edge the player stops and sneaks (sneaking also keeps them from slipping off).
* Returns false when the way is blocked by such an edge.
*/
public boolean approach(final Vec3d feet, final BlockPos stand, final Predicate<BlockPos> solid) {
final double dx = stand.getX() + CENTER - feet.x;
final double dz = stand.getZ() + CENTER - feet.z;
final double dist = Math.hypot(dx, dz);
if (dist > ARRIVE_EPS && !ground(feet, dx / dist * STEP, dz / dist * STEP, solid)) {
movement.stop();
movement.sneak(true);
return false;
}
movement.walkTo(stand.getX() + CENTER, stand.getZ() + CENTER);
final boolean nearEdge = dist > ARRIVE_EPS
&& !ground(feet, dx / dist * SNEAK_LOOK, dz / dist * SNEAK_LOOK, solid);
movement.sneak(nearEdge);
return true;
}
/** Solid floor (at most one block lower) at the point {@code (dx, dz)} ahead of the feet. */
private static boolean ground(final Vec3d feet, final double dx, final double dz,
final Predicate<BlockPos> solid) {
final BlockPos ahead = BlockPos.ofFloored(feet.x + dx, feet.y, feet.z + dz);
return solid.test(ahead.down()) || solid.test(ahead.down(2));
}
public void stop() {

View file

@ -9,15 +9,16 @@ 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.Direction;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
/**
* S5 GroundWalk (AutoBuild style): fake-key walking to the column, pillar-jumping when the
* target is at or above the feet level, plain placement otherwise. For servers where flight
* is banned.
* S5 GroundWalk (AutoBuild style): fake-key walking to a stand block next to the cell (never into
* the column, never over an edge), pillar-jumping when no stand exists at the cell's level. For
* servers where flight is banned.
*/
public final class GroundWalk implements PlaceStrategy {
@ -63,10 +64,20 @@ public final class GroundWalk implements PlaceStrategy {
@Override
public PlaceResult tick(final PlaceContext ctx, final ColumnTarget target) {
ctx.disableFlight();
final BlockPos cell = target.cells().get(0);
final Vec3d feet = ctx.feetPos();
final Optional<BlockPos> stand = StandFinder.find(ctx, cell, feet);
if (stand.isPresent()) {
if (!StandFinder.at(feet, stand.get()) && move.approach(feet, stand.get(), ctx::isSolid)) {
return PlaceResult.WAIT;
}
move.stop();
return placer.place(ctx, cell, params.get(CommonOptions.REACH),
params.getInt(CommonOptions.DELAY_MS));
}
if (far(feet, target.column())) {
move.approach(feet, target.column());
move.approach(feet, target.column(), ctx::isSolid);
return PlaceResult.WAIT;
}
if (cell.getY() >= MathHelper.floor(feet.y)) {

View file

@ -0,0 +1,64 @@
package dev.loki.satura.interaction.place.strategy.ground;
import dev.loki.satura.interaction.place.PlaceContext;
import java.util.Optional;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
/**
* Picks the block the player should stand in to place a cell: solid ground underneath, two free
* blocks of headroom, next to the cell (never inside it). Walking strategies go there instead of
* running into the column itself, which dropped them off the build.
*/
public final class StandFinder {
private static final int[][] OFFSETS = {
{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1},
{2, 0}, {-2, 0}, {0, 2}, {0, -2}
};
private static final int LEVELS = 2;
private static final double SAME_LEVEL_BIAS = 0.5;
private static final double AT_STAND_HEIGHT = 0.6;
private StandFinder() {
}
/** Nearest standable spot around the cell, at the cell's level or one above; empty if there is none. */
public static Optional<BlockPos> find(final PlaceContext ctx, final BlockPos cell, final Vec3d feet) {
BlockPos best = null;
double bestScore = Double.MAX_VALUE;
for (int level = 0; level < LEVELS; level++) {
for (final int[] offset : OFFSETS) {
final BlockPos stand = new BlockPos(cell.getX() + offset[0], cell.getY() + level,
cell.getZ() + offset[1]);
if (!standable(ctx, stand)) {
continue;
}
final double score = distanceSq(feet, stand) + level * SAME_LEVEL_BIAS;
if (score < bestScore) {
bestScore = score;
best = stand;
}
}
}
return Optional.ofNullable(best);
}
/** Whether the feet are already in the stand block (on its floor, not falling past it). */
public static boolean at(final Vec3d feet, final BlockPos stand) {
return MathHelper.floor(feet.x) == stand.getX() && MathHelper.floor(feet.z) == stand.getZ()
&& Math.abs(feet.y - stand.getY()) < AT_STAND_HEIGHT;
}
private static boolean standable(final PlaceContext ctx, final BlockPos stand) {
return ctx.isSolid(stand.down()) && !ctx.isSolid(stand) && !ctx.isSolid(stand.up());
}
private static double distanceSq(final Vec3d feet, final BlockPos stand) {
final double dx = stand.getX() + 0.5 - feet.x;
final double dy = stand.getY() - feet.y;
final double dz = stand.getZ() + 0.5 - feet.z;
return dx * dx + dy * dy + dz * dz;
}
}

View file

@ -27,6 +27,11 @@ public final class HoldRmb implements PlaceStrategy {
this.core = new ColumnPlacing(params, () -> 1, placer, PlaceContext::useKeyDown);
}
@Override
public boolean needsFlight() {
return true;
}
@Override
public String id() {
return "hold_rmb";

View file

@ -42,6 +42,11 @@ public final class FlyHover implements PlaceStrategy {
this.placer = placer;
}
@Override
public boolean needsFlight() {
return true;
}
@Override
public String id() {
return "fly_hover";

View file

@ -32,6 +32,11 @@ public final class PrecisePlacement implements PlaceStrategy {
this.placer = placer;
}
@Override
public boolean needsFlight() {
return true;
}
@Override
public String id() {
return "precise";
@ -55,7 +60,7 @@ public final class PrecisePlacement implements PlaceStrategy {
@Override
public PlaceResult tick(final PlaceContext ctx, final ColumnTarget target) {
final BlockPos cell = target.cells().get(0);
hover(ctx, target.column(), cell.getY());
hover(ctx, target);
if (!ColumnPlacing.overColumn(ctx.feetPos(), target.column())) {
return PlaceResult.WAIT;
}
@ -71,14 +76,17 @@ public final class PrecisePlacement implements PlaceStrategy {
return result;
}
private void hover(final PlaceContext ctx, final BlockPos column, final int layerY) {
private void hover(final PlaceContext ctx, final ColumnTarget target) {
final BlockPos column = target.column();
final int windowFloor = target.windowFloor();
final int windowTop = target.windowTop();
ctx.enableFlight();
final Vec3d feet = ctx.feetPos();
final double height = FlightControl.height(layerY, layerY, params.get(CommonOptions.HOVER),
final double height = FlightControl.height(windowFloor, windowTop, params.get(CommonOptions.HOVER),
params.get(CommonOptions.REACH), ColumnPlacing.EYE_MARGIN);
final Vec3d goal = new Vec3d(column.getX() + ColumnPlacing.CENTER, height,
column.getZ() + ColumnPlacing.CENTER);
final Vec3d v = FlightControl.velocity(feet, goal, params.get(CommonOptions.FLY_SPEED));
final Vec3d v = FlightControl.smooth(feet, goal, params.get(CommonOptions.FLY_SPEED));
ctx.setVelocity(v.x, v.y, v.z);
ctx.lookDown();
}

View file

@ -3,10 +3,25 @@ package dev.loki.satura.interaction.place.target;
import java.util.List;
import net.minecraft.util.math.BlockPos;
/** Column with not yet built cells of the current Y window (ascending Y). */
public record ColumnTarget(BlockPos column, List<BlockPos> cells) {
/**
* Column with not yet built cells of the current Y window (ascending Y).
*
* @param windowFloor lowest Y of the whole window, not only of the pending cells
* @param windowTop highest Y of the whole window; flight height is derived from it so the
* player keeps one constant height while a window is built
*/
public record ColumnTarget(BlockPos column, List<BlockPos> cells, int windowFloor, int windowTop) {
public ColumnTarget {
cells = List.copyOf(cells);
}
/** Target whose window is exactly its pending cells (tests, planners without a window). */
public ColumnTarget(final BlockPos column, final List<BlockPos> cells) {
this(column, cells, edgeY(cells, column, 0), edgeY(cells, column, cells.size() - 1));
}
private static int edgeY(final List<BlockPos> cells, final BlockPos column, final int index) {
return cells.isEmpty() ? column.getY() : cells.get(index).getY();
}
}

View file

@ -19,7 +19,7 @@ import net.minecraft.util.Identifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Reads the atlas (.png) and description (.json, msdf-atlas-gen format) from assets/satura/font. */
/** Reads the atlas (.png) and description (.json, msdf-atlas-gen format) from assets/satura/msdf. */
@SuppressWarnings({"PMD.CloseResource", "PMD.GuardLogStatement", "PMD.AvoidCatchingGenericException",
"PMD.InvalidLogMessageFormat", "PMD.LooseCoupling"})
final class MsdfFontLoader {
@ -97,7 +97,7 @@ final class MsdfFontLoader {
}
private static InputStream open(String file) throws IOException {
Identifier id = Identifier.of(ShaderPass.NAMESPACE, "font/" + file);
Identifier id = Identifier.of(ShaderPass.NAMESPACE, "msdf/" + file);
return MinecraftClient.getInstance().getResourceManager().open(id);
}

View file

@ -3,23 +3,66 @@
"key.satura.open_menu": "Open builder menu",
"key.satura.toggle": "Pause / resume build",
"key.category.satura.main": "Satura",
"satura.gui.tab.build": "Build",
"satura.gui.tab.place": "Placement",
"satura.gui.tab.supply": "Supply",
"satura.gui.pos1": "Pos1: %s",
"satura.gui.pos2": "Pos2: %s",
"satura.gui.start": "Start",
"satura.gui.pause": "Pause",
"satura.gui.resume": "Resume",
"satura.gui.stop": "Stop",
"satura.gui.shape": "Shape: %s",
"satura.gui.strategy": "Strategy: %s",
"satura.gui.preset": "Preset: %s",
"satura.gui.theme": "Theme: %s",
"satura.gui.layers": "Layers: %s",
"satura.gui.delay": "Delay: %s ms",
"satura.gui.block": "Block",
"satura.gui.options.hidden": "Too many parameters - lower the GUI scale",
"satura.gui.supply.todo": "Supply (next plan phase): chest routes,",
"satura.gui.supply.todo2": "teleport there/back, automatic restock."
"satura.ui.nav.build": "Build",
"satura.ui.nav.place": "Placement",
"satura.ui.nav.supply": "Supply",
"satura.ui.nav.profiles": "Profiles",
"satura.ui.nav.themes": "Themes",
"satura.ui.build.title": "Build",
"satura.ui.build.subtitle": "Area, shape and block - then start",
"satura.ui.start": "Start",
"satura.ui.stop": "Stop",
"satura.ui.pause": "Pause",
"satura.ui.resume": "Resume",
"satura.ui.shape": "Shape",
"satura.ui.shape.box": "Box",
"satura.ui.shape.box.desc": "Solid volume",
"satura.ui.shape.checker": "Checker",
"satura.ui.shape.checker.desc": "Every other block",
"satura.ui.shape.walls": "Walls",
"satura.ui.shape.walls.desc": "Perimeter only",
"satura.ui.block": "Block",
"satura.ui.block.hint": "stone, minecraft:glass or hand",
"satura.ui.pos.unset": "not set",
"satura.ui.no.world": "Join a world first",
"satura.ui.place.title": "Placement",
"satura.ui.place.subtitle": "How blocks are placed and how the player flies",
"satura.ui.preset": "Preset",
"satura.ui.preset.max": "Max",
"satura.ui.preset.safe": "Safe",
"satura.ui.preset.custom": "Custom",
"satura.ui.strategy": "Strategy",
"satura.ui.params": "Parameters",
"satura.ui.fly": "FLY",
"satura.ui.walk": "WALK",
"satura.ui.strategy.band_stack": "1-3 layers per column visit",
"satura.ui.strategy.column_drop": "One layer per column visit",
"satura.ui.strategy.precise": "Exact support and ray check",
"satura.ui.strategy.fly_hover": "Hover over the click point",
"satura.ui.strategy.ground_walk": "On foot, jumps and pillars",
"satura.ui.strategy.baritone_walk": "Baritone walks, we place",
"satura.ui.strategy.hold_rmb": "Places while RMB is held",
"satura.ui.strategy.burst": "Several clicks per tick",
"satura.ui.supply.title": "Supply",
"satura.ui.supply.subtitle": "Fetch blocks when they run out",
"satura.ui.supply.route": "Routes",
"satura.ui.supply.route.desc": "Marked chests and what to take from them",
"satura.ui.supply.teleport": "Teleport",
"satura.ui.supply.teleport.desc": "Commands there and back, cooldown handling",
"satura.ui.supply.restock": "Auto restock",
"satura.ui.supply.restock.desc": "Take blocks and return to the build",
"satura.ui.soon": "SOON",
"satura.ui.profiles.title": "Profiles",
"satura.ui.profiles.subtitle": "Setting sets in one click",
"satura.ui.profiles.new": "New profile",
"satura.ui.profiles.hint": "name: a-z, 0-9, _ and -",
"satura.ui.profiles.active": "active",
"satura.ui.themes.title": "Themes",
"satura.ui.themes.subtitle": "Interface accent color",
"satura.ui.theme.orange": "Orange",
"satura.ui.theme.white": "White",
"satura.ui.theme.mint": "Mint",
"satura.ui.theme.sand": "Sand",
"satura.ui.status.idle": "idle",
"satura.ui.error": "error"
}

View file

@ -3,23 +3,66 @@
"key.satura.open_menu": "Открыть меню билдера",
"key.satura.toggle": "Пауза / продолжить билд",
"key.category.satura.main": "Satura",
"satura.gui.tab.build": "Стройка",
"satura.gui.tab.place": "Постановка",
"satura.gui.tab.supply": "Снабжение",
"satura.gui.pos1": "Pos1: %s",
"satura.gui.pos2": "Pos2: %s",
"satura.gui.start": "Старт",
"satura.gui.pause": "Пауза",
"satura.gui.resume": "Продолжить",
"satura.gui.stop": "Стоп",
"satura.gui.shape": "Форма: %s",
"satura.gui.strategy": "Стратегия: %s",
"satura.gui.preset": "Пресет: %s",
"satura.gui.theme": "Тема: %s",
"satura.gui.layers": "Слоёв: %s",
"satura.gui.delay": "Задержка: %s мс",
"satura.gui.block": "Блок",
"satura.gui.options.hidden": "Параметров слишком много — уменьшите масштаб GUI",
"satura.gui.supply.todo": "Снабжение (фаза 11): маршруты до сундуков,",
"satura.gui.supply.todo2": "телепорт туда/обратно, авто-подбор блоков."
"satura.ui.nav.build": "Стройка",
"satura.ui.nav.place": "Постановка",
"satura.ui.nav.supply": "Снабжение",
"satura.ui.nav.profiles": "Профили",
"satura.ui.nav.themes": "Темы",
"satura.ui.build.title": "Стройка",
"satura.ui.build.subtitle": "Область, форма и блок — затем старт",
"satura.ui.start": "Старт",
"satura.ui.stop": "Стоп",
"satura.ui.pause": "Пауза",
"satura.ui.resume": "Продолжить",
"satura.ui.shape": "Форма",
"satura.ui.shape.box": "Куб",
"satura.ui.shape.box.desc": "Сплошной объём",
"satura.ui.shape.checker": "Шахматка",
"satura.ui.shape.checker.desc": "Через один блок",
"satura.ui.shape.walls": "Стены",
"satura.ui.shape.walls.desc": "Только периметр",
"satura.ui.block": "Блок",
"satura.ui.block.hint": "stone, minecraft:glass или hand",
"satura.ui.pos.unset": "не задана",
"satura.ui.no.world": "Зайди в мир",
"satura.ui.place.title": "Постановка",
"satura.ui.place.subtitle": "Как мод ставит блоки и как летает",
"satura.ui.preset": "Пресет",
"satura.ui.preset.max": "Макс",
"satura.ui.preset.safe": "Безопасно",
"satura.ui.preset.custom": "Свой",
"satura.ui.strategy": "Стратегия",
"satura.ui.params": "Параметры",
"satura.ui.fly": "ПОЛЁТ",
"satura.ui.walk": "ХОДЬБА",
"satura.ui.strategy.band_stack": "1–3 слоя за визит колонны",
"satura.ui.strategy.column_drop": "По одному слою за визит",
"satura.ui.strategy.precise": "Точная опора и проверка луча",
"satura.ui.strategy.fly_hover": "Зависание над точкой клика",
"satura.ui.strategy.ground_walk": "Пешком, прыжки и пиллары",
"satura.ui.strategy.baritone_walk": "Ходит Baritone, ставим сами",
"satura.ui.strategy.hold_rmb": "Ставит, пока зажата ПКМ",
"satura.ui.strategy.burst": "Несколько кликов за тик",
"satura.ui.supply.title": "Снабжение",
"satura.ui.supply.subtitle": "Сходить за блоками, когда они кончились",
"satura.ui.supply.route": "Маршруты",
"satura.ui.supply.route.desc": "Отмеченные сундуки и что из них брать",
"satura.ui.supply.teleport": "Телепорт",
"satura.ui.supply.teleport.desc": "Команды туда и обратно, ожидание кулдауна",
"satura.ui.supply.restock": "Авто-пополнение",
"satura.ui.supply.restock.desc": "Брать блоки и возвращаться на стройку",
"satura.ui.soon": "СКОРО",
"satura.ui.profiles.title": "Профили",
"satura.ui.profiles.subtitle": "Наборы настроек одним кликом",
"satura.ui.profiles.new": "Новый профиль",
"satura.ui.profiles.hint": "имя: a-z, 0-9, _ и -",
"satura.ui.profiles.active": "активный",
"satura.ui.themes.title": "Темы",
"satura.ui.themes.subtitle": "Цвет акцента интерфейса",
"satura.ui.theme.orange": "Оранжевая",
"satura.ui.theme.white": "Белая",
"satura.ui.theme.mint": "Мятная",
"satura.ui.theme.sand": "Песочная",
"satura.ui.status.idle": "простой",
"satura.ui.error": "ошибка"
}

View file

Before

Width:  |  Height:  |  Size: 336 KiB

After

Width:  |  Height:  |  Size: 336 KiB

Before After
Before After

View file

Before

Width:  |  Height:  |  Size: 200 KiB

After

Width:  |  Height:  |  Size: 200 KiB

Before After
Before After

View file

Before

Width:  |  Height:  |  Size: 99 KiB

After

Width:  |  Height:  |  Size: 99 KiB

Before After
Before After

View file

Before

Width:  |  Height:  |  Size: 336 KiB

After

Width:  |  Height:  |  Size: 336 KiB

Before After
Before After

View file

@ -0,0 +1,51 @@
package dev.loki.satura.core.config;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class ConfigStoreTest {
@TempDir
Path dir;
@Test
void activeDefaultsAndPersists() {
final ConfigStore store = new ConfigStore(dir);
assertEquals(Profile.DEFAULT_NAME, store.active());
store.activate("pvp");
assertEquals("pvp", new ConfigStore(dir).active());
}
@Test
void namesSkipReservedAndSort() {
final ConfigStore store = new ConfigStore(dir);
store.saveQuietly(Profile.empty("pvp"));
store.saveQuietly(Profile.empty("default"));
store.saveQuietly(Profile.empty("render"));
assertEquals(List.of("default", "pvp"), store.names());
}
@Test
void roundTripKeepsValues() {
final ConfigStore store = new ConfigStore(dir);
store.saveQuietly(Profile.empty("a").with("block", "stone"));
assertEquals("stone", store.loadOrEmpty("a").get("block", ""));
assertTrue(store.loadOrEmpty("missing").settings().isEmpty());
}
@Test
void rejectsUnsafeNames() {
final ConfigStore store = new ConfigStore(dir);
assertFalse(Profile.isValidName("../x"));
assertFalse(Profile.isValidName("Big"));
assertTrue(Profile.isValidName("a_b-1"));
assertThrows(IllegalArgumentException.class, () -> store.saveQuietly(Profile.empty("../x")));
}
}

View file

@ -0,0 +1,55 @@
package dev.loki.satura.feature.builder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import dev.loki.satura.core.config.Profile;
import dev.loki.satura.interaction.place.PlaceStrategy;
import dev.loki.satura.interaction.place.strategy.BandStack;
import dev.loki.satura.interaction.place.strategy.ColumnDrop;
import dev.loki.satura.interaction.place.support.BlockPlacer;
import dev.loki.satura.interaction.place.support.Cooldown;
import dev.loki.satura.interaction.place.support.SupportFinder;
import java.util.List;
import org.junit.jupiter.api.Test;
class BuildSettingsTest {
private static BuildSettings settings(final Profile profile) {
final BlockPlacer placer = new BlockPlacer(new SupportFinder(), new Cooldown());
final List<PlaceStrategy> all = List.of(new BandStack(placer), new ColumnDrop(placer));
return new BuildSettings(profile, all);
}
@Test
void applyReplacesEverythingAndResetsMissingOptions() {
final BuildSettings s = settings(Profile.empty("a"));
s.setBlock("glass");
s.setShape("walls");
s.setStrategy("column_drop");
s.setOption("delayMs", "50");
s.apply(Profile.empty("b"));
assertEquals("hand", s.block());
assertEquals("box", s.shapeId());
assertEquals("band_stack", s.strategy().id());
s.setStrategy("column_drop");
assertEquals(0.0, s.optionRange("delayMs").orElseThrow().value());
}
@Test
void profileRoundTrip() {
final BuildSettings s = settings(Profile.empty("a"));
s.setBlock("stone");
s.setShape("checker");
s.setOption("delayMs", "40");
final Profile saved = s.toProfile("a");
final BuildSettings other = settings(Profile.empty("x"));
other.apply(saved);
assertEquals("stone", other.block());
assertEquals("checker", other.shapeId());
assertEquals(40.0, other.optionRange("delayMs").orElseThrow().value());
}
}

View file

@ -30,6 +30,9 @@ class BuildCommandTest {
@Override public String setLayers(final int n) { return log("layers " + n); }
@Override public List<String> presetIds() { return List.of("max", "safe", "custom"); }
@Override public String applyPreset(final String id) { return log("preset " + id); }
@Override public List<String> profileIds() { return List.of("default", "pvp"); }
@Override public String profile() { return "default"; }
@Override public String switchProfile(final String id) { return log("profile " + id); }
@Override public List<String> blockIds() { return List.of("stone"); }
@Override public List<String> strategyIds() { return List.of("band_stack", "column_drop"); }
@Override public List<String> optionKeys() { return List.of("delayMs"); }
@ -44,8 +47,9 @@ class BuildCommandTest {
command.execute(List.of("layers", "3"), replies::add);
command.execute(List.of("SHAPE", "walls"), replies::add);
command.execute(List.of("preset", "safe"), replies::add);
command.execute(List.of("profile", "pvp"), replies::add);
assertEquals(List.of("start", "block stone", "set delayMs=5", "layers 3", "shape walls",
"preset safe"), calls);
"preset safe", "profile pvp"), calls);
assertEquals(calls, replies);
}
@ -68,6 +72,7 @@ class BuildCommandTest {
assertTrue(command.suggest(List.of("")).contains("preset"));
assertEquals(List.of("band_stack", "column_drop"), command.suggest(List.of("strategy", "")));
assertEquals(List.of("max", "safe", "custom"), command.suggest(List.of("preset", "")));
assertEquals(List.of("default", "pvp"), command.suggest(List.of("profile", "")));
assertEquals(List.of("delayMs"), command.suggest(List.of("set", "")));
assertTrue(command.suggest(List.of("block", "")).contains("hand"));
}

View file

@ -125,6 +125,11 @@ final class EngineHarness {
return blocked;
}
@Override
public boolean canFly() {
return true;
}
@Override
public Object worldToken() {
return world;

View file

@ -111,4 +111,31 @@ class PlannerTest {
p.reset();
assertEquals(new BlockPos(0, 10, 0), p.next().orElseThrow().cells().get(0));
}
@Test
void onlyOffersCellsWithContact() {
final Set<BlockPos> built = new HashSet<>();
final Planner p = new Planner(area(2, 2, 1), new BoxShape(), 2, built::contains,
pos -> pos.getY() < ORIGIN.getY() || built.contains(pos));
final ColumnTarget first = p.next().orElseThrow();
assertEquals(List.of(new BlockPos(0, 10, 0)), first.cells());
}
@Test
void cellOverVoidWaitsUntilANeighbourIsBuilt() {
final Set<BlockPos> built = new HashSet<>();
final Planner p = new Planner(area(1, 1, 1), new BoxShape(), 1, built::contains, pos -> false);
assertTrue(p.next().isEmpty());
}
@Test
void sideContactIsEnough() {
final Set<BlockPos> built = new HashSet<>();
final BlockPos wall = new BlockPos(-1, 10, 0);
final Planner p = new Planner(area(2, 1, 1), new BoxShape(), 1, built::contains,
pos -> pos.equals(wall) || built.contains(pos));
assertEquals(new BlockPos(0, 10, 0), p.next().orElseThrow().column());
built.add(new BlockPos(0, 10, 0));
assertEquals(new BlockPos(1, 10, 0), p.next().orElseThrow().column());
}
}

View file

@ -1,6 +1,7 @@
package dev.loki.satura.interaction.place.strategy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import dev.loki.satura.interaction.place.target.ColumnTarget;
import dev.loki.satura.interaction.place.FakeContext;
@ -55,6 +56,39 @@ class StrategyTest {
assertEquals(0.0, FlightControl.velocity(new Vec3d(1, 5, 1), new Vec3d(1, 5, 1), 0.25).length(), 1e-9);
}
@Test
void smoothFlightSlowsDownNearTheGoal() {
final Vec3d far = FlightControl.smooth(new Vec3d(0, 5, 0), new Vec3d(10, 5, 0), 0.25);
final Vec3d near = FlightControl.smooth(new Vec3d(9.5, 5, 0), new Vec3d(10, 5, 0), 0.25);
assertEquals(0.25, far.x, 1e-9);
assertTrue(near.x < far.x && near.x > 0.0);
assertEquals(0.0, near.y, 1e-9);
}
@Test
void smoothFlightNeverOvershootsTheGoal() {
final Vec3d v = FlightControl.smooth(new Vec3d(9.9, 5, 0), new Vec3d(10, 5, 0), 0.25);
assertTrue(v.x <= 0.1 + 1e-9);
assertEquals(0.0, FlightControl.smooth(new Vec3d(1, 5, 1), new Vec3d(1, 5, 1), 0.25).length(), 1e-9);
}
@Test
void flightHeightComesFromTheWindowNotFromThePendingCells() {
final PlaceStrategy s = new ColumnDrop(placer);
final double fullWindow = verticalSpeed(s, new ColumnTarget(COLUMN,
List.of(new BlockPos(0, 10, 0), new BlockPos(0, 11, 0)), 10, 11));
final double lowerHalfDone = verticalSpeed(new ColumnDrop(placer), new ColumnTarget(COLUMN,
List.of(new BlockPos(0, 11, 0)), 10, 11));
assertEquals(fullWindow, lowerHalfDone, 1e-9);
assertTrue(fullWindow > 0.0);
}
private static double verticalSpeed(final PlaceStrategy strategy, final ColumnTarget target) {
final FakeContext ctx = ctxAt(10.0);
strategy.tick(ctx, target);
return ctx.velocity.y;
}
@Test
void waitsWhileNotOverColumn() {
final PlaceStrategy s = new ColumnDrop(placer);

View file

@ -41,13 +41,22 @@ class GroundWalkTest {
private static final class Keys implements KeyInput {
boolean forward;
boolean jump;
boolean sneak;
@Override public void setForward(final boolean p) { forward = p; }
@Override public void setBack(final boolean p) { }
@Override public void setLeft(final boolean p) { }
@Override public void setRight(final boolean p) { }
@Override public void setJump(final boolean p) { jump = p; }
@Override public void setSneak(final boolean p) { }
@Override public void setSneak(final boolean p) { sneak = p; }
}
private static void floor(final FakeContext ctx, final int fromX, final int toX) {
for (int x = fromX; x <= toX; x++) {
for (int z = -2; z <= 2; z++) {
ctx.solids.add(new BlockPos(x, 9, z));
}
}
}
private static ColumnTarget target(final int y) {
@ -65,7 +74,7 @@ class GroundWalkTest {
pose.x = 15;
final Keys keys = new Keys();
final FakeContext ctx = new FakeContext(new Vec3d(15, 10.0, 0.5));
ctx.solids.add(new BlockPos(0, 9, 0));
floor(ctx, -2, 16);
final GroundWalk s = strategy(pose, keys);
for (int i = 0; i < 4; i++) {
assertEquals(PlaceResult.WAIT, s.tick(ctx, target(10)));
@ -74,6 +83,49 @@ class GroundWalkTest {
assertTrue(ctx.clicks.isEmpty());
}
@Test
void stopsAndSneaksAtAnEdgeInsteadOfWalkingOff() {
final Pose pose = new Pose();
pose.x = 5.5;
pose.z = 0.5;
final Keys keys = new Keys();
final FakeContext ctx = new FakeContext(new Vec3d(5.5, 10.0, 0.5));
floor(ctx, -2, 5);
ctx.solids.add(new BlockPos(11, 9, 0));
final GroundWalk s = strategy(pose, keys);
s.tick(ctx, new ColumnTarget(new BlockPos(11, 0, 0), List.of(new BlockPos(11, 10, 0))));
assertFalse(keys.forward);
assertTrue(keys.sneak);
}
@Test
void walksToAStandBlockNextToTheCellNotIntoIt() {
final Pose pose = new Pose();
pose.x = 8.5;
pose.z = 0.5;
final Keys keys = new Keys();
final FakeContext ctx = new FakeContext(new Vec3d(8.5, 10.0, 0.5));
floor(ctx, -2, 10);
final GroundWalk s = strategy(pose, keys);
for (int i = 0; i < 4; i++) {
s.tick(ctx, target(10));
}
assertTrue(keys.forward);
assertTrue(ctx.clicks.isEmpty());
}
@Test
void placesFromTheStandBlockWithoutMoving() {
final Pose pose = new Pose();
pose.x = 1.5;
pose.z = 0.5;
final Keys keys = new Keys();
final FakeContext ctx = new FakeContext(new Vec3d(1.5, 10.0, 0.5));
floor(ctx, -2, 10);
assertEquals(PlaceResult.PLACED, strategy(pose, keys).tick(ctx, target(10)));
assertFalse(keys.forward);
}
@Test
void placesCellBelowFeetLevel() {
final Pose pose = new Pose();

View file

@ -0,0 +1,58 @@
package dev.loki.satura.interaction.place.strategy.ground;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import dev.loki.satura.interaction.place.FakeContext;
import java.util.Optional;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import org.junit.jupiter.api.Test;
class StandFinderTest {
private static FakeContext ground() {
final FakeContext ctx = new FakeContext(new Vec3d(5.5, 10.0, 0.5));
for (int x = -3; x <= 8; x++) {
for (int z = -3; z <= 3; z++) {
ctx.solids.add(new BlockPos(x, 9, z));
}
}
return ctx;
}
@Test
void picksANeighbourAtTheCellLevelAndNeverTheCellItself() {
final FakeContext ctx = ground();
final Optional<BlockPos> stand = StandFinder.find(ctx, new BlockPos(0, 10, 0), ctx.feet);
assertTrue(stand.isPresent());
assertFalse(stand.get().equals(new BlockPos(0, 10, 0)));
assertEquals(10, stand.get().getY());
assertTrue(Math.abs(stand.get().getX()) <= 2 && Math.abs(stand.get().getZ()) <= 2);
}
@Test
void nothingToStandOnMeansNoStand() {
final FakeContext ctx = new FakeContext(new Vec3d(0.5, 10.0, 0.5));
assertTrue(StandFinder.find(ctx, new BlockPos(0, 10, 0), ctx.feet).isEmpty());
}
@Test
void headroomIsRequired() {
final FakeContext ctx = ground();
for (int x = -3; x <= 8; x++) {
for (int z = -3; z <= 3; z++) {
ctx.solids.add(new BlockPos(x, 11, z));
}
}
assertTrue(StandFinder.find(ctx, new BlockPos(0, 10, 0), ctx.feet).isEmpty());
}
@Test
void atChecksTheBlockAndTheFloorHeight() {
assertTrue(StandFinder.at(new Vec3d(1.4, 10.0, 0.6), new BlockPos(1, 10, 0)));
assertFalse(StandFinder.at(new Vec3d(1.4, 12.0, 0.6), new BlockPos(1, 10, 0)));
assertFalse(StandFinder.at(new Vec3d(2.4, 10.0, 0.6), new BlockPos(1, 10, 0)));
}
}

View file

@ -36,8 +36,8 @@ class FlyHoverTest {
final FakeContext ctx = new FakeContext(new Vec3d(0.5, 11.1, 20.5));
ctx.solids.add(new BlockPos(0, 9, 0));
assertEquals(PlaceResult.WAIT, s.tick(ctx, target(10)));
// default flySpeed k = 0.25: speed = min(0.34k, max(0.08k, dist*0.35k)) = 0.085
assertEquals(-0.085, ctx.velocity.z, 1e-9);
// default flySpeed k = 0.5: speed = min(0.34k, max(0.08k, dist*0.35k)) = 0.17
assertEquals(-0.17, ctx.velocity.z, 1e-9);
ctx.feet = new Vec3d(0.5, 11.1, 0.5);
assertEquals(PlaceResult.PLACED, s.tick(ctx, target(10)));
assertEquals(new BlockPos(0, 9, 0), ctx.clicks.get(0).getBlockPos());