Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
# framework
- No game, platform or TeaVM types (`BoundaryTest`): features see the game only through this
module. A new capability is defined here in Incari's terms and filled in by `:client`'s
`incari.client.modules`.
- Compiled into the browser build: no reflection, no blocking, nothing TeaVM's class library lacks.
- Firing events and drawing the HUD are hot paths: don't allocate there. A channel nobody listens
to must cost no more than a length check.
- A new event: a constant in `Events` (next index, `COUNT` up), a listener interface, a `fire` method
on `EventBus`, and its hook in the game. Add it with the first module that needs it, and list it
in ADR 0046.
- A new kind of setting: a `Setting` subclass and a `SettingVisitor` method; the compiler then shows
every place to handle it (`ProfileCodec`, `:client`'s `SettingControls`).
- Features read the game through `Game` (`ModuleSystem.game()`, ADR 0050): views the client
reuses, never game objects. A game option a module changes is held with `Module.holdOption`, never
set and forgotten; a part of the game's HUD a module moves is a `GamePart` with a `GamePartElement`.
- What several features share and isn't a setting lives here, kept apart from profiles: the world's
waypoints (`ModuleSystem.waypoints()`, ADR 0051). What follows the camera is drawn every frame: a
live `HudElement`, or the `OVERLAY` event with `WorldOverlay.project`.
- Profile files must stay readable by older and newer builds: never rename an id, and keep reading
forgiving (`ProfileCodec`).
- Public types get Javadoc, with their threading rules.
- Test: `./gradlew :framework:check`; end to end, `./gradlew :app-desktop:smokeModules`.
+42
View File
@@ -0,0 +1,42 @@
# framework: the module framework
What every client feature is built on (ADR 0046). A `Module` declares its settings, HUD elements
and event listeners; the framework subscribes them while it's on, reads its keybinds, draws its HUD
where the player put it, and saves everything in the active profile. The client generates each
module's settings screen from its settings alone.
No game types: features see the game only through this module, and `client`'s
`incari.client.modules` fills it in.
## Code map
- `Module`: the base class. Settings in field initializers (`settings().bool(...)`), then `hud(...)`
and `on(Events.X, listener)` in the constructor; `onEnable`/`onDisable` hooks.
- `ModuleSystem`: holds the modules; ticks them with the game's `KeyInput`, draws the HUD on a
`HudCanvas`, manages profiles.
- `event`: `Events` (the channels), `EventBus`, `MovementInput`.
- `setting`: `BooleanSetting`, `IntSetting`, `FloatSetting`, `ChoiceSetting`, `ColorSetting`,
`KeySetting` (with `Key`), `Settings`, and `SettingVisitor` over them all.
- `hud`: `HudElement`, `HudCanvas`, `Anchor`, `Tone`; `WorldCanvas` for the world itself (beams,
`BlockGhosts`' ghost blocks, boxes).
- `game`: `Game`, the game as modules see it; `Blocks`, its block states and the world's blocks.
- `config`: `Profiles`, `ProfileCodec` (the JSON), `ConfigStorage`.
- Test fixtures: `incari.framework.testing.TestGame`, the game's side faked for feature tests;
`FakeBlocks`, a world of blocks.
## Invariants
- **No game, platform or TeaVM types** (`BoundaryTest`): the JDK's basics, JSpecify, and Gson's tree
API in `config`.
- **A disabled module costs nothing**: its listeners aren't subscribed and its HUD elements aren't in
the drawn list.
- **Firing an event allocates nothing**; nor do the listener arrays until someone (un)subscribes.
- **Game thread only.** Nothing here is thread-safe.
- **Ids are config keys**: a module's, a setting's or a HUD element's id never changes once shipped.
## How to test
```sh
./gradlew :framework:check
./gradlew :app-desktop:smokeModules # a display: the menu, Toggle Sprint in a world, the profile saved
```
@@ -0,0 +1,26 @@
plugins {
`java-library`
// Fakes of the game's side (storage, a canvas, keys) that feature modules test against.
`java-test-fixtures`
}
// The module framework (ADR 0046): the Module base class, the event bus, the typed settings
// schema, keybinds, HUD elements, profiles and their config. No game types: features/* see the game
// only through what this module defines, and :client's incari.client.modules fills it in.
dependencies {
api(libs.jspecify)
// Profiles are JSON through Gson's tree API (no reflection). The game ships Gson, so at run time
// its copy is on the class path; this is compile-only, like :net's Netty.
compileOnly(libs.gson)
testFixturesApi(libs.jspecify)
// A module system in a test reads profiles with Gson: the fixtures bring it, as the game does.
testFixturesRuntimeOnly(libs.gson)
testImplementation(libs.gson)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testImplementation(libs.assertj)
testImplementation(libs.archunit)
testRuntimeOnly(libs.junit.launcher)
}
@@ -0,0 +1,26 @@
package incari.framework;
/** Where a module is listed in the module menu, in this order. */
public enum Category {
/** Information drawn on the HUD: keystrokes, FPS, coordinates, armor. */
HUD("HUD"),
/** Combat: displays and the feel of fighting. */
COMBAT("Combat"),
/** How the player moves: toggle sprint, toggle sneak. */
MOVEMENT("Movement"),
/** How the world looks: zoom, freelook, the crosshair, presets. */
VISUAL("Visual"),
/** Everything else: chat, screenshots, waypoints. */
UTILITY("Utility");
private final String label;
Category(String label) {
this.label = label;
}
/** What the module menu calls it. */
public String label() {
return label;
}
}
@@ -0,0 +1,17 @@
package incari.framework;
import incari.framework.setting.KeySetting;
/**
* The game's side of keybinds: what each {@link KeySetting}'s key did since the last tick. The
* client answers through the game's own key handling, so binds follow the game's rules (nothing
* fires with a screen open, keys are released when one opens).
*/
public interface KeyInput {
/** How many times the setting's key went down since the last call; resets the count. */
int presses(KeySetting key);
/** Whether the setting's key is held now. */
boolean isDown(KeySetting key);
}
@@ -0,0 +1,12 @@
package incari.framework;
/**
* A button a module puts on the title screen and the pause menu while it's on (Screenshot
* Manager's "Screenshots"). The client lays them out in its menus' style.
*
* @param id unique among the module's buttons; stable
* @param label what the button says
* @param icon the client's icon for it, by name ("camera", "palette"); the client may have none
* @param action what pressing it does; game thread
*/
public record MenuButton(String id, String label, String icon, Runnable action) {}
@@ -0,0 +1,318 @@
package incari.framework;
import incari.framework.event.Channel;
import incari.framework.event.EventBus;
import incari.framework.event.Events;
import incari.framework.game.Game;
import incari.framework.game.GameOption;
import incari.framework.hud.HudElement;
import incari.framework.setting.Ids;
import incari.framework.setting.Key;
import incari.framework.setting.KeySetting;
import incari.framework.setting.Settings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.DoubleSupplier;
import org.jspecify.annotations.Nullable;
/**
* A client feature the player turns on and off: toggle sprint, keystrokes, zoom. A subclass
* declares everything in its constructor (its settings as fields, its HUD elements, the events it
* listens to) and the framework does the rest: the settings screen is generated from the settings,
* the profile saves them, and the listeners are subscribed only while the module is enabled, so a
* disabled module costs nothing.
*
* <p>A module sees the game only through the framework's events and canvases: no game types (ADR
* 0046). Everything runs on the game thread.
*
* <pre>{@code
* final class Fullbright extends Module {
* private final FloatSetting level = settings().decimal("level", "Brightness", 0, 1, 0.1F, 1);
*
* Fullbright() {
* super("fullbright", "Fullbright", "Lights everything up.", Category.VISUAL);
* on(Events.TICK, this::tick);
* }
* }
* }</pre>
*/
public abstract class Module {
private final String id;
private final String name;
private final String description;
private final Category category;
private final Settings settings = new Settings();
private final KeySetting toggleKey;
private final List<HudElement> hud = new ArrayList<>();
private final List<HudElement> hudView = Collections.unmodifiableList(hud);
/** Channel, listener, channel, listener... */
private final List<Object> subscriptions = new ArrayList<>();
private final List<OptionHold> holds = new ArrayList<>(0);
/** The resource pack this module is the switch for, or null ({@link #followPack}). */
private @Nullable String pack;
private final List<MenuButton> menuButtons = new ArrayList<>(0);
private final List<MenuButton> menuButtonsView = Collections.unmodifiableList(menuButtons);
private boolean enabled;
private boolean alwaysOn;
/** True while a throw turns the module off: an always-on module is turned off then too. */
private boolean failing;
private @Nullable ModuleSystem system;
/**
* @param id the config key and the module's name in logs: lowercase, stable forever
* @param name what the module menu calls it
* @param description one sentence: what it does
* @param category where the module menu lists it
*/
protected Module(String id, String name, String description, Category category) {
this.id = Ids.require(id);
this.name = name;
this.description = description;
this.category = category;
this.toggleKey = settings.key("toggle", "Toggle key", Key.NONE).describedAs("Turns " + name + " on and off.");
}
/** The config key. */
public final String id() {
return id;
}
/** What the module menu calls it. */
public final String name() {
return name;
}
/** One sentence: what it does. */
public final String description() {
return description;
}
/** Where the module menu lists it. */
public final Category category() {
return category;
}
/** Its settings, the toggle key first. Declare a module's own in field initializers. */
public final Settings settings() {
return settings;
}
/** The key that turns it on and off; unbound by default. It fires while the module is off too. */
public final KeySetting toggleKey() {
return toggleKey;
}
/** Its HUD elements, in the order they were added. */
public final List<HudElement> hudElements() {
return hudView;
}
/** Whether it's on. */
public final boolean isEnabled() {
return enabled;
}
/**
* Whether it's part of the client rather than a choice ({@link #alwaysOn()}).
*/
public final boolean isAlwaysOn() {
return alwaysOn;
}
/**
* Turns it on or off: its listeners are subscribed or unsubscribed, then its hook runs. An
* {@linkplain #isAlwaysOn() always-on} module isn't turned off.
*/
public final void setEnabled(boolean on) {
if (on == enabled || (alwaysOn && !on && !failing)) {
return;
}
ModuleSystem owner = system();
EventBus bus = owner.events();
enabled = on;
for (int i = 0; i < subscriptions.size(); i += 2) {
if (on) {
subscribe(bus, (Channel<?>) subscriptions.get(i), subscriptions.get(i + 1));
} else {
unsubscribe(bus, (Channel<?>) subscriptions.get(i), subscriptions.get(i + 1));
}
}
owner.enabledChanged(this);
Game game = owner.game();
try {
if (on) {
for (int i = 0; i < holds.size(); i++) {
holds.get(i).take(game);
}
onEnable();
} else {
onDisable();
for (int i = 0; i < holds.size(); i++) {
holds.get(i).release(game);
}
}
if (pack != null) {
owner.selectPack(this, pack, on);
}
} catch (RuntimeException e) {
// Reported and, if it was turning on, turned off again.
owner.failed(this, on ? "turning on" : "turning off", e);
}
}
/** Turns it on if it's off, off if it's on. */
public final void toggle() {
setEnabled(!enabled);
}
/** Runs after it's turned on (also when a profile loads with it on). */
protected void onEnable() {}
/** Runs after it's turned off (also when a profile loads with it off, or the game leaves). */
protected void onDisable() {}
/**
* Listens to {@code channel} while the module is enabled. Call from the constructor; the
* listener should be a field or a method reference made once.
*/
protected final <L> void on(Channel<L> channel, L listener) {
if (system != null) {
throw new IllegalStateException(id + ": subscribe in the constructor");
}
subscriptions.add(channel);
subscriptions.add(listener);
}
/**
* Holds a game option at {@code value} while the module is on, following it as the settings
* change (Clear Chat holds the chat's background opacity at 0); the player's value comes back
* when it turns off. Moving the option's slider turns the module off and keeps the player's
* value. Call from the constructor.
*/
protected final void holdOption(GameOption option, DoubleSupplier value) {
for (OptionHold hold : holds) {
if (hold.option() == option) {
throw new IllegalArgumentException(id + ": holds " + option + " twice");
}
}
OptionHold hold = new OptionHold(this, option, value);
holds.add(hold);
on(Events.TICK, hold);
}
/**
* Makes the module the switch for the game's resource pack {@code packId} (Old Textures for
* {@code programmer_art}): the module and the pack turn on and off together, from either side.
* At start the module follows the pack, whatever the profile says. Call from the constructor.
*/
protected final void followPack(String packId) {
if (system != null) {
throw new IllegalStateException(id + ": follow a pack in the constructor");
}
if (pack != null) {
throw new IllegalArgumentException(id + ": follows " + pack + " already");
}
pack = packId;
}
/**
* Makes the module part of the client, not a choice (the Theme Editor): always on, with no
* toggle key, and left out of the module menu's cards and presets. Its settings screen opens
* from elsewhere. Call from the constructor.
*/
protected final void alwaysOn() {
if (system != null) {
throw new IllegalStateException(id + ": be always on from the constructor");
}
alwaysOn = true;
toggleKey.hidden();
}
/** The resource pack it's the switch for, or null. */
final @Nullable String pack() {
return pack;
}
/**
* Puts a button on the title screen and the pause menu while the module is on. Call from the
* constructor.
*/
protected final MenuButton menuButton(String buttonId, String label, String icon, Runnable action) {
if (system != null) {
throw new IllegalStateException(id + ": add menu buttons in the constructor");
}
MenuButton button = new MenuButton(Ids.require(buttonId), label, icon, action);
menuButtons.add(button);
return button;
}
/** Its menu buttons, in the order they were added. */
public final List<MenuButton> menuButtons() {
return menuButtonsView;
}
/** Adds a HUD element, drawn while the module is enabled. Call from the constructor. */
protected final <E extends HudElement> E hud(E element) {
if (system != null) {
throw new IllegalStateException(id + ": add HUD elements in the constructor");
}
for (HudElement other : hud) {
if (other.id().equals(element.id())) {
throw new IllegalArgumentException(id + ": two HUD elements with the id " + element.id());
}
}
hud.add(element);
return element;
}
/** The module system it belongs to. */
protected final ModuleSystem system() {
ModuleSystem owner = system;
if (owner == null) {
throw new IllegalStateException(id + " isn't in a module system yet");
}
return owner;
}
final void register(ModuleSystem owner) {
if (system != null) {
throw new IllegalStateException(id + " is already in a module system");
}
system = owner;
}
/** Turned off because it threw: like {@link #setEnabled(boolean) setEnabled(false)}, quietly. */
final void disableAfterFailure() {
if (enabled) {
failing = true;
try {
setEnabled(false);
} finally {
failing = false;
}
}
}
@SuppressWarnings("unchecked")
private <L> void subscribe(EventBus bus, Channel<L> channel, Object listener) {
// The module is the owner a listener's failure is reported against.
bus.add(channel, this, (L) listener);
}
@SuppressWarnings("unchecked")
private static <L> void unsubscribe(EventBus bus, Channel<L> channel, Object listener) {
bus.remove(channel, (L) listener);
}
@Override
public String toString() {
return id;
}
}
@@ -0,0 +1,575 @@
package incari.framework;
import incari.framework.config.ConfigStorage;
import incari.framework.config.ProfileCodec;
import incari.framework.config.Profiles;
import incari.framework.event.Channel;
import incari.framework.event.EventBus;
import incari.framework.event.Events;
import incari.framework.game.Game;
import incari.framework.game.GamePart;
import incari.framework.hud.GamePartElement;
import incari.framework.hud.HudCanvas;
import incari.framework.hud.HudElement;
import incari.framework.online.Online;
import incari.framework.setting.KeySetting;
import incari.framework.setting.Setting;
import incari.framework.waypoint.Waypoints;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jspecify.annotations.Nullable;
/**
* Every module, the events they listen to, their keybinds, their HUD and the profiles that store
* them. The client makes one at start-up with the build's modules and calls in from the game's
* hooks; everything else (screens, the HUD editor, server feature control) goes through it.
*
* <p>Game thread only. Changes are saved a second after the last one ({@link #tick}), or at once
* by {@link #flush()}; the browser's files are in memory and stored behind (ADR 0011), so a save
* never waits on the disk.
*/
public final class ModuleSystem {
/** Where the system reports problems: the client's log. */
public interface Log {
/** Something went wrong; {@code error} is null if there's no exception. */
void warn(String message, @Nullable Throwable error);
}
/** Ticks from the last change to the save: a slider's drag is one save, not dozens. */
static final int SAVE_DELAY_TICKS = 20;
/**
* The game's effect icons in the top right: four 25-unit boxes in from the right edge, and two
* rows (helpful, then harmful) 52 units tall from the top.
*/
static final int EFFECT_ICONS_WIDTH = 100;
static final int EFFECT_ICONS_HEIGHT = 52;
/** {@link #effectIconsShift}'s scratch: an element's bounds. */
private final int[] iconBounds = new int[4];
private final List<Module> modules;
private final EventBus events;
private final Profiles profiles;
private final Log log;
private final Game game;
private final Online online;
private final Waypoints waypoints;
/** Every keybind, with the module it belongs to at the same index. */
private final KeySetting[] keys;
private final Module[] keyOwners;
/** Whether each keybind is its module's toggle key, which fires while the module is off. */
private final boolean[] toggleKeys;
/** The HUD elements of enabled modules drawn with the HUD: the only ones drawn there. */
private HudElement[] activeHud = new HudElement[0];
private Module[] activeHudOwners = new Module[0];
/** Those drawn every frame ({@link HudElement#isLive()}). */
private HudElement[] liveHud = new HudElement[0];
private Module[] liveHudOwners = new Module[0];
/** The parts of the game's HUD an enabled module's element draws. */
private final EnumSet<GamePart> heldParts = EnumSet.noneOf(GamePart.class);
/** The modules that are switches for resource packs ({@link Module#followPack}). */
private final Module[] packSwitches;
private long revision;
private int saveCountdown = -1;
private boolean loading;
/**
* True while {@link #load} applies the profile the client started with: only then is what the
* profile says of the game's state (a held option's player value) current.
*/
private boolean startingUp;
/**
* True while the profile first loads and while a module follows the game's packs: the module's
* state comes from the game's, not the other way round.
*/
private boolean followingGame;
/** With no game and no online service; see the full constructor. */
public ModuleSystem(List<? extends Module> modules, ConfigStorage storage, Log log) {
this(modules, storage, log, Game.NONE);
}
/** With no online service; see the full constructor. */
public ModuleSystem(List<? extends Module> modules, ConfigStorage storage, Log log, Game game) {
this(modules, storage, log, game, Online.NONE);
}
/**
* @param modules every module of the build, in menu order within a category; each in no other
* system
* @param storage where profiles are kept
* @param log where problems go
* @param game what modules can read of the game
* @param online the player's Incari account and the Incari players around them (ADR 0058)
*/
public ModuleSystem(List<? extends Module> modules, ConfigStorage storage, Log log, Game game, Online online) {
this.modules = List.copyOf(modules);
this.log = log;
this.game = game;
this.online = online;
this.events = new EventBus(this::listenerFailed);
this.profiles = new Profiles(storage, this.modules, message -> log.warn(message, null));
this.waypoints = new Waypoints(storage, message -> log.warn(message, null));
List<KeySetting> keyList = new ArrayList<>();
List<Module> ownerList = new ArrayList<>();
List<Module> switches = new ArrayList<>();
Set<String> ids = new HashSet<>();
for (Module module : this.modules) {
if (!ids.add(module.id())) {
throw new IllegalArgumentException("Two modules with the id " + module.id());
}
module.register(this);
module.settings().attach(this::changed);
if (module.pack() != null) {
switches.add(module);
}
for (HudElement element : module.hudElements()) {
element.settings().attach(this::changed);
}
for (Setting<?> setting : module.settings()) {
if (setting instanceof KeySetting key) {
keyList.add(key);
ownerList.add(module);
}
}
}
this.packSwitches = switches.toArray(new Module[0]);
this.keys = keyList.toArray(new KeySetting[0]);
this.keyOwners = ownerList.toArray(new Module[0]);
this.toggleKeys = new boolean[keys.length];
for (int i = 0; i < keys.length; i++) {
toggleKeys[i] = keys[i].equals(keyOwners[i].toggleKey());
}
}
/** Every module, in the order given. */
public List<Module> modules() {
return modules;
}
/** The module with this id, or null. */
public @Nullable Module module(String id) {
for (Module module : modules) {
if (module.id().equals(id)) {
return module;
}
}
return null;
}
/** The events, for the game's hooks to fire. */
public EventBus events() {
return events;
}
/** What modules can read of the game. */
public Game game() {
return game;
}
/**
* The player's Incari account and which players in the world are Incari players (ADR 0058).
* Accounts aren't a module: they're there, or not, whatever the profile says.
*/
public Online online() {
return online;
}
/**
* The waypoints of the world the player is in. The client opens a world's as the player joins
* it and closes them as they leave.
*/
public Waypoints waypoints() {
return waypoints;
}
/**
* Whether an enabled module draws the game's {@code part} itself: the game then leaves it out
* where it would draw it. A field read; the HUD asks every frame.
*/
public boolean holds(GamePart part) {
return heldParts.contains(part);
}
/**
* A number that goes up whenever a module is turned on or off, a setting changes or a profile is
* applied: a screen compares it to know when to refresh.
*/
public long revision() {
return revision;
}
/**
* Applies the active profile, before the first tick; a failure leaves every default. A resource
* pack's switch follows the pack, not the profile: the resources already loaded with the packs,
* and changing them would reload them all.
*/
public void load() {
loading = true;
startingUp = true;
followingGame = true;
try {
profiles.load();
} catch (IOException | RuntimeException e) {
log.warn("Couldn't load the module profiles", e);
}
try {
followPacks();
// Always-on modules are on even when the profile couldn't be read.
for (Module module : modules) {
if (module.isAlwaysOn()) {
module.setEnabled(true);
}
}
} finally {
loading = false;
startingUp = false;
followingGame = false;
}
revision++;
}
/**
* A client tick: keybinds fire, then {@link incari.framework.event.Events#TICK}'s listeners, then
* a due save.
*/
public void tick(KeyInput input) {
followPacks();
boolean toggled = false;
for (int i = 0; i < keys.length; i++) {
KeySetting key = keys[i];
Module owner = keyOwners[i];
// Every key's presses are taken, so a module turned on later doesn't see stale ones.
// An unbound key is never pressed, whatever the input says of "no key".
boolean bound = key.get().isBound();
int presses = bound ? input.presses(key) : 0;
boolean live = owner.isEnabled() || toggleKeys[i];
key.update(bound && live && input.isDown(key));
for (int p = 0; p < presses && live; p++) {
try {
if (toggleKeys[i]) {
owner.toggle();
toggled = true;
} else {
key.press();
}
} catch (RuntimeException e) {
failed(owner, "its key " + key.id(), e);
}
live = owner.isEnabled() || toggleKeys[i];
}
}
events.fireTick();
if (toggled) {
// A key's toggle is one change, not a drag: saved now, as the tab may close next.
flush();
} else if (saveCountdown > 0 && --saveCountdown == 0) {
flush();
}
waypoints.tick();
}
/** The menu buttons of every enabled module, in module order: the title's and pause menu's. */
public List<MenuButton> menuButtons() {
List<MenuButton> buttons = new ArrayList<>();
for (Module module : modules) {
if (module.isEnabled()) {
buttons.addAll(module.menuButtons());
}
}
return buttons;
}
/** Whether any HUD element could draw: false lets the game skip the HUD hook's setup. */
public boolean hasHud() {
return activeHud.length > 0;
}
/**
* Whether anything is drawn every frame: a live HUD element ({@link HudElement#isLive()}) or a
* listener to {@link incari.framework.event.Events#OVERLAY}.
*/
public boolean hasLiveHud() {
return liveHud.length > 0 || events.count(Events.OVERLAY) > 0;
}
/**
* How far down the game draws its effect icons, in GUI units, so they clear the HUD elements in
* their place in the top right (the minimap): below the lowest in the way, but never off the
* bottom of the screen. 0 leaves them where the game puts them. Render thread, as the game's HUD
* draws them; reads where each element was last drawn, allocating nothing.
*/
public int effectIconsShift(int screenWidth, int screenHeight) {
int shift = 0;
int lowest = Math.max(0, screenHeight - EFFECT_ICONS_HEIGHT);
// Each element in the way moves them below it, until none is: a handful of elements.
for (int pass = 0; pass <= activeHud.length + liveHud.length; pass++) {
int below = Math.max(below(activeHud, shift, screenWidth), below(liveHud, shift, screenWidth));
if (below <= shift) {
break;
}
if (below > lowest) {
return lowest;
}
shift = below;
}
return shift;
}
/** The lowest bottom of the {@code elements} over the icons' place {@code shift} down, plus a gap. */
private int below(HudElement[] elements, int shift, int screenWidth) {
int[] b = iconBounds;
int lowest = shift;
for (HudElement element : elements) {
if (element.lastDrawn(b)
&& b[0] + b[2] > screenWidth - EFFECT_ICONS_WIDTH
&& b[1] < shift + EFFECT_ICONS_HEIGHT
&& b[1] + b[3] > shift) {
lowest = Math.max(lowest, b[1] + b[3] + 1);
}
}
return lowest;
}
/**
* Draws every enabled module's visible HUD elements, but for the live ones. Render thread, during
* the HUD's extraction.
*/
public void drawHud(HudCanvas canvas) {
draw(canvas, activeHud, activeHudOwners);
}
/** Draws every enabled module's visible live HUD elements. Render thread, every frame. */
public void drawLiveHud(HudCanvas canvas) {
draw(canvas, liveHud, liveHudOwners);
}
private void draw(HudCanvas canvas, HudElement[] elements, Module[] owners) {
for (int i = 0; i < elements.length; i++) {
try {
elements[i].render(canvas);
} catch (RuntimeException e) {
failed(owners[i], "its HUD element " + elements[i].id(), e);
}
}
}
/**
* Draws one of {@code owner}'s HUD elements, as {@link #drawHud} does: the HUD editor's, which
* draws each element over its own frame. A throw turns the module off, as there.
*/
public void drawHud(HudCanvas canvas, Module owner, HudElement element) {
try {
element.render(canvas);
} catch (RuntimeException e) {
failed(owner, "its HUD element " + element.id(), e);
}
}
/** The active profile's name. */
public String activeProfile() {
return profiles.active();
}
/** Every profile's name. */
public List<String> profiles() {
return profiles.names();
}
/** Saves the active profile, then applies {@code name}. False if there's no such profile. */
public boolean switchProfile(String name) {
return profileChange("switch to profile " + name, () -> profiles.switchTo(name));
}
/** Makes a copy of the active profile called {@code name} and switches to it. False if it can't. */
public boolean createProfile(String name) {
return profileChange("create profile " + name, () -> profiles.create(name));
}
/** Deletes a profile; the first left becomes active if it was. False if it's the only one. */
public boolean deleteProfile(String name) {
return profileChange("delete profile " + name, () -> profiles.delete(name));
}
/**
* Applies a preset (1.8 PvP, Modern PvP, QoL): switches to the profile {@code name} (copying the
* active one if it doesn't exist), then turns on exactly the modules in {@code on} and the rest
* off. Always-on modules aren't switched, and unknown ids are skipped. Settings stay as they were
* except those in {@code settings}, which maps {@code "module.setting"} to config text (e.g.
* {@code "togglesprint.sprint"} to {@code "always"}). False if the profile can't be made.
*/
public boolean applyPreset(String name, Set<String> on, Map<String, String> settings) {
boolean ready =
profiles.names().stream().anyMatch(name::equalsIgnoreCase) ? switchProfile(name) : createProfile(name);
if (!ready) {
return false;
}
for (Module module : modules) {
if (!module.isAlwaysOn()) {
module.setEnabled(on.contains(module.id()));
}
for (Setting<?> setting : module.settings()) {
String text = settings.get(module.id() + "." + setting.id());
if (text != null && !ProfileCodec.setFromText(setting, text)) {
log.warn(
"Preset " + name + " has a value " + module.id() + "." + setting.id() + " can't take: "
+ text,
null);
}
}
}
// The module states are the change: saved like any other.
changed();
return true;
}
/** {@link #applyPreset(String, Set, Map)} with no settings changed. */
public boolean applyPreset(String name, Set<String> on) {
return applyPreset(name, on, Map.of());
}
/** Saves the profile and the waypoints now if anything changed since the last save. */
public void flush() {
waypoints.flush();
if (saveCountdown < 0) {
return;
}
saveCountdown = -1;
try {
profiles.save();
} catch (IOException | RuntimeException e) {
log.warn("Couldn't save module profile " + profiles.active(), e);
}
}
/**
* Turns each pack's switch on or off as the game has its pack: the player may have changed it
* in the Resource Packs screen, or a pack asked for may not be there. A few list lookups a tick.
*/
private void followPacks() {
boolean was = followingGame;
followingGame = true;
try {
for (Module module : packSwitches) {
String pack = module.pack();
if (pack != null) {
module.setEnabled(game.packSelected(pack));
}
}
} finally {
followingGame = was;
}
}
/** Whether the profile the client started with is being applied ({@link #load}). */
boolean startingUp() {
return startingUp;
}
/** {@link Module#setEnabled}'s report for a pack's switch: the pack goes with it. */
void selectPack(Module module, String pack, boolean on) {
if (followingGame || game.packSelected(pack) == on) {
return;
}
if (!game.selectPack(pack, on)) {
// The next tick turns the module back as the pack is.
log.warn(
"Module " + module.id() + " couldn't turn the resource pack " + pack + (on ? " on" : " off"), null);
}
}
/** {@link Module#setEnabled}'s report. */
void enabledChanged(Module module) {
List<HudElement> elements = new ArrayList<>();
List<Module> owners = new ArrayList<>();
List<HudElement> live = new ArrayList<>();
List<Module> liveOwners = new ArrayList<>();
heldParts.clear();
for (Module m : modules) {
if (m.isEnabled()) {
for (HudElement element : m.hudElements()) {
(element.isLive() ? live : elements).add(element);
(element.isLive() ? liveOwners : owners).add(m);
if (element instanceof GamePartElement part) {
heldParts.add(part.part());
}
}
}
}
activeHud = elements.toArray(new HudElement[0]);
activeHudOwners = owners.toArray(new Module[0]);
liveHud = live.toArray(new HudElement[0]);
liveHudOwners = liveOwners.toArray(new Module[0]);
changed();
}
private void changed() {
revision++;
if (!loading) {
saveCountdown = SAVE_DELAY_TICKS;
}
}
private interface ProfileAction {
boolean run() throws IOException;
}
private boolean profileChange(String what, ProfileAction action) {
loading = true;
try {
// What the action applies isn't a change to save; a change pending from before still is.
return action.run();
} catch (IOException | RuntimeException e) {
log.warn("Couldn't " + what, e);
return false;
} finally {
loading = false;
revision++;
}
}
private void listenerFailed(Object owner, Channel<?> channel, RuntimeException error) {
failed((Module) owner, "a " + channel.name() + " event", error);
}
/**
* A module threw: it's turned off (it would likely throw again every tick), the error logged,
* and the player told, so it isn't left off without their knowing.
*/
void failed(Module module, String where, RuntimeException error) {
log.warn("Module " + module.id() + " failed in " + where + " and was turned off", error);
boolean wasOn = module.isEnabled();
try {
module.disableAfterFailure();
} catch (RuntimeException again) {
log.warn("Module " + module.id() + " failed again while turning off", again);
}
if (wasOn) {
try {
game.showMessage(module.name() + " was turned off", "It hit a problem. You can turn it on again.");
} catch (RuntimeException e) {
log.warn("Couldn't tell the player module " + module.id() + " was turned off", e);
}
}
}
}
@@ -0,0 +1,119 @@
package incari.framework;
import incari.framework.event.TickListener;
import incari.framework.game.Game;
import incari.framework.game.GameOption;
import incari.framework.setting.BooleanSetting;
import incari.framework.setting.FloatSetting;
import java.util.Locale;
import java.util.function.DoubleSupplier;
/**
* One game option a module holds while it's on ({@link Module#holdOption}): set to the module's
* value when it turns on, given back when it turns off.
*
* <p>The player's own value is kept in memory while the hold lasts, and in two hidden settings so
* it comes back even after a restart with the module on (by then the game's options have saved the
* module's value). The hidden settings are trusted only at start-up: a profile switch, a preset or
* Reset All can load copies that say nothing of the option now. During the hold they're set from
* memory each tick, so the saved profile is right.
*
* <p>The option's slider stays the player's: moving it while the module is on turns the module
* off and keeps what they chose. Checked once a tick, as a comparison of two numbers.
*/
final class OptionHold implements TickListener {
/** Sliders store doubles; a module's values come from float settings. */
private static final double SAME = 1e-4;
private final Module module;
private final GameOption option;
private final DoubleSupplier value;
/** What the player had before the module took it, for after a restart. */
private final FloatSetting before;
/** Whether the game's option has the module's value, so {@link #before} is the player's. */
private final BooleanSetting held;
/** What the module set it to; NaN while it doesn't hold it. */
private double applied = Double.NaN;
/** What the player had before the module took it; NaN while it doesn't hold it. */
private double original = Double.NaN;
OptionHold(Module module, GameOption option, DoubleSupplier value) {
this.module = module;
this.option = option;
this.value = value;
String suffix = option.name().toLowerCase(Locale.ROOT).replace('_', '-');
this.before = module.settings()
.decimal("before-" + suffix, option.label() + " before", 0, (float) option.max(), 0.01F, (float)
option.defaultValue())
.hidden();
this.held = module.settings()
.bool("held-" + suffix, option.label() + " held", false)
.hidden();
}
/** The option held. */
GameOption option() {
return option;
}
/** The module turned on: the option takes the module's value. */
void take(Game game) {
double now = game.option(option);
double want = value.getAsDouble();
// The module's value left from before a restart: the player's is the one kept from then.
boolean resumed = module.system().startingUp() && held.get() && same(now, want);
original = resumed ? before.get() : now;
if (!same(now, want)) {
game.setOption(option, want);
}
applied = want;
remember();
}
/** The module turned off: the player's value back, unless they've set one since. */
void release(Game game) {
double was = applied;
double players = original;
applied = Double.NaN;
original = Double.NaN;
held.set(false);
if (!Double.isNaN(was) && same(game.option(option), was)) {
game.setOption(option, players);
}
}
@Override
public void onTick() {
if (Double.isNaN(applied)) {
return;
}
Game game = module.system().game();
double now = game.option(option);
if (!same(now, applied)) {
// The player moved the slider: their value stands, and the module lets go.
applied = Double.NaN;
original = Double.NaN;
held.set(false);
module.setEnabled(false);
return;
}
double want = value.getAsDouble();
if (!same(want, applied)) {
// The module's own setting changed.
game.setOption(option, want);
applied = want;
}
remember();
}
/** The hidden settings as the hold is: no change, so no save, when they're so already. */
private void remember() {
before.set((float) original);
held.set(true);
}
private static boolean same(double a, double b) {
return Math.abs(a - b) < SAME;
}
}
@@ -0,0 +1,24 @@
package incari.framework.config;
import java.io.IOException;
import org.jspecify.annotations.Nullable;
/**
* Where the module config lives: small text files by relative path ({@code profiles.json},
* {@code profiles/PvP.json}). The client puts them under the game directory's {@code incari/modules},
* which the browser build keeps in OPFS (ADR 0011): writes are to memory, stored behind.
*
* <p>Game thread. Must not block: the browser's files are in memory, so these return at once.
*/
public interface ConfigStorage {
/** The file's text, or null if there's no such file. */
@Nullable
String read(String path) throws IOException;
/** Writes the file whole, making its folder if needed. */
void write(String path, String text) throws IOException;
/** Deletes the file; nothing if it isn't there. */
void delete(String path) throws IOException;
}
@@ -0,0 +1,341 @@
package incari.framework.config;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import incari.framework.Module;
import incari.framework.hud.HudElement;
import incari.framework.setting.ActionSetting;
import incari.framework.setting.BooleanSetting;
import incari.framework.setting.ChoiceSetting;
import incari.framework.setting.ColorSetting;
import incari.framework.setting.FloatSetting;
import incari.framework.setting.GridSetting;
import incari.framework.setting.IntSetting;
import incari.framework.setting.Key;
import incari.framework.setting.KeySetting;
import incari.framework.setting.Setting;
import incari.framework.setting.SettingVisitor;
import incari.framework.setting.Settings;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.jspecify.annotations.Nullable;
/**
* A profile as JSON: which modules are on and every setting's value, by id.
*
* <pre>{@code
* {
* "format": 1,
* "modules": {
* "togglesprint": {
* "enabled": true,
* "settings": { "toggle": "none", "sprint": "toggle", "color": "#FFFFFFFF" },
* "hud": { "status": { "anchor": "top_left", "x": 2, "y": 2, "scale": 1.0 } }
* }
* }
* }
* }</pre>
*
* <p>Reading is forgiving: a value that doesn't fit its setting leaves the default, and a module
* this build doesn't have is kept as it was and written back, so a profile survives a build
* without that module.
*/
public final class ProfileCodec {
/** The format's version; a newer one is read as far as it's understood. */
public static final int FORMAT = 1;
private ProfileCodec() {}
/**
* Writes the modules' state.
*
* @param unknown what {@link #read} kept of modules this build doesn't have, written back as it was
*/
public static JsonObject write(List<Module> modules, JsonObject unknown) {
JsonObject entries = new JsonObject();
for (Map.Entry<String, JsonElement> entry : unknown.entrySet()) {
entries.add(entry.getKey(), entry.getValue());
}
for (Module module : modules) {
JsonObject entry = new JsonObject();
entry.addProperty("enabled", module.isEnabled());
entry.add("settings", writeSettings(module.settings()));
if (!module.hudElements().isEmpty()) {
JsonObject hud = new JsonObject();
for (HudElement element : module.hudElements()) {
hud.add(element.id(), writeSettings(element.settings()));
}
entry.add("hud", hud);
}
entries.add(module.id(), entry);
}
JsonObject root = new JsonObject();
root.addProperty("format", FORMAT);
root.add("modules", entries);
return root;
}
/**
* Sets every module's settings from {@code root} (the default where it has none), then turns
* each on or off as it says (off where it doesn't say).
*
* @return the entries of modules this build doesn't have, to write back later
*/
public static JsonObject read(JsonObject root, List<Module> modules) {
JsonObject entries = object(root, "modules");
JsonObject unknown = new JsonObject();
if (entries != null) {
for (Map.Entry<String, JsonElement> entry : entries.entrySet()) {
if (find(modules, entry.getKey()) == null) {
unknown.add(entry.getKey(), entry.getValue());
}
}
}
// Settings first, so a module's onEnable sees the profile's values.
boolean[] enable = new boolean[modules.size()];
for (int i = 0; i < modules.size(); i++) {
Module module = modules.get(i);
JsonObject entry = entries == null ? null : object(entries, module.id());
readSettings(module.settings(), entry == null ? null : object(entry, "settings"));
JsonObject hud = entry == null ? null : object(entry, "hud");
for (HudElement element : module.hudElements()) {
readSettings(element.settings(), hud == null ? null : object(hud, element.id()));
}
enable[i] = module.isAlwaysOn() || (entry != null && bool(entry, "enabled"));
}
for (int i = 0; i < modules.size(); i++) {
modules.get(i).setEnabled(enable[i]);
}
return unknown;
}
private static JsonObject writeSettings(Settings settings) {
JsonObject values = new JsonObject();
for (Setting<?> setting : settings) {
JsonElement value = setting.accept(WRITER);
// A button has no value to keep.
if (!value.isJsonNull()) {
values.add(setting.id(), value);
}
}
return values;
}
/**
* Sets {@code setting} from its config text, as a profile would have it ({@code "true"},
* {@code "7"}, {@code "always"}). False, and the setting left as it was, if the text doesn't fit.
*/
public static boolean setFromText(Setting<?> setting, String text) {
JsonPrimitive value;
if (text.equals("true") || text.equals("false")) {
value = new JsonPrimitive(Boolean.parseBoolean(text));
} else {
try {
value = new JsonPrimitive(Double.parseDouble(text));
} catch (NumberFormatException notANumber) {
value = new JsonPrimitive(text);
}
}
return setting.accept(new Reader(value));
}
private static void readSettings(Settings settings, @Nullable JsonObject values) {
for (Setting<?> setting : settings) {
JsonElement value = values == null ? null : values.get(setting.id());
if (value == null || !value.isJsonPrimitive() || !setting.accept(new Reader(value.getAsJsonPrimitive()))) {
setting.reset();
}
}
}
private static @Nullable Module find(List<Module> modules, String id) {
for (Module module : modules) {
if (module.id().equals(id)) {
return module;
}
}
return null;
}
private static @Nullable JsonObject object(JsonObject parent, String key) {
JsonElement element = parent.get(key);
return element != null && element.isJsonObject() ? element.getAsJsonObject() : null;
}
private static boolean bool(JsonObject parent, String key) {
JsonElement element = parent.get(key);
return element != null
&& element.isJsonPrimitive()
&& element.getAsJsonPrimitive().isBoolean()
&& element.getAsBoolean();
}
/** {@code 0xAARRGGBB} as {@code #AARRGGBB}. */
static String colorText(int argb) {
String hex = Integer.toHexString(argb).toUpperCase(Locale.ROOT);
return "#" + "00000000".substring(hex.length()) + hex;
}
/** {@code #AARRGGBB} or {@code #RRGGBB} (opaque) as {@code 0xAARRGGBB}, or null. */
static @Nullable Integer parseColor(String text) {
if (!text.startsWith("#") || (text.length() != 7 && text.length() != 9)) {
return null;
}
try {
long value = Long.parseLong(text.substring(1), 16);
return text.length() == 7 ? (int) value | 0xFF000000 : (int) value;
} catch (NumberFormatException e) {
return null;
}
}
private static final SettingVisitor<JsonElement> WRITER = new SettingVisitor<>() {
@Override
public JsonElement visit(BooleanSetting setting) {
return new JsonPrimitive(setting.get());
}
@Override
public JsonElement visit(IntSetting setting) {
return new JsonPrimitive(setting.get());
}
@Override
public JsonElement visit(FloatSetting setting) {
return new JsonPrimitive(setting.get());
}
@Override
public JsonElement visit(ChoiceSetting<?> setting) {
return new JsonPrimitive(setting.key());
}
@Override
public JsonElement visit(ColorSetting setting) {
return new JsonPrimitive(colorText(setting.get()));
}
@Override
public JsonElement visit(KeySetting setting) {
return new JsonPrimitive(setting.get().encode());
}
@Override
public JsonElement visit(ActionSetting setting) {
return JsonNull.INSTANCE;
}
@Override
public JsonElement visit(GridSetting setting) {
StringBuilder text = new StringBuilder();
for (int y = 0; y < setting.size(); y++) {
if (y > 0) {
text.append(',');
}
text.append(Long.toHexString(setting.row(y)));
}
return new JsonPrimitive(text.toString());
}
};
/** Sets a setting from one JSON value; false if the value doesn't fit it. */
private static final class Reader implements SettingVisitor<Boolean> {
private final JsonPrimitive value;
Reader(JsonPrimitive value) {
this.value = value;
}
@Override
public Boolean visit(BooleanSetting setting) {
if (!value.isBoolean()) {
return false;
}
setting.set(value.getAsBoolean());
return true;
}
@Override
public Boolean visit(IntSetting setting) {
if (!value.isNumber()) {
return false;
}
setting.set(value.getAsInt());
return true;
}
@Override
public Boolean visit(FloatSetting setting) {
if (!value.isNumber()) {
return false;
}
setting.set(value.getAsFloat());
return true;
}
@Override
public Boolean visit(ChoiceSetting<?> setting) {
return value.isString() && choose(setting, value.getAsString());
}
private static <E extends Enum<E>> boolean choose(ChoiceSetting<E> setting, String key) {
E choice = setting.fromKey(key);
if (choice == null) {
return false;
}
setting.set(choice);
return true;
}
@Override
public Boolean visit(ColorSetting setting) {
Integer color = value.isString() ? parseColor(value.getAsString()) : null;
if (color == null) {
return false;
}
setting.set(color);
return true;
}
@Override
public Boolean visit(KeySetting setting) {
Key key = value.isString() ? Key.decode(value.getAsString()) : null;
if (key == null) {
return false;
}
setting.set(key);
return true;
}
@Override
public Boolean visit(ActionSetting setting) {
return true;
}
@Override
public Boolean visit(GridSetting setting) {
if (!value.isString()) {
return false;
}
String[] parts = value.getAsString().split(",", -1);
if (parts.length != setting.size()) {
return false;
}
long[] rows = new long[parts.length];
try {
for (int i = 0; i < parts.length; i++) {
rows[i] = Long.parseUnsignedLong(parts[i], 16);
}
} catch (NumberFormatException e) {
return false;
}
setting.setRows(rows);
return true;
}
}
}
@@ -0,0 +1,217 @@
package incari.framework.config;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import incari.framework.Module;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.function.Consumer;
import org.jspecify.annotations.Nullable;
/**
* The player's profiles: named sets of module states and settings ("PvP", "Building"), one active.
* Each is a file, {@code profiles/<name>.json} ({@link ProfileCodec}); {@code profiles.json} lists
* them and names the active one. A new profile starts as a copy of the active one.
*
* <p>Game thread. A file that can't be parsed is reported and read as empty (every default), and
* isn't overwritten until something changes.
*/
public final class Profiles {
/** The first profile's name. */
public static final String DEFAULT = "Default";
private static final String INDEX = "profiles.json";
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private static final int MAX_NAME = 24;
private final ConfigStorage storage;
private final List<Module> modules;
private final Consumer<String> warnings;
private final List<String> names = new ArrayList<>();
private final List<String> namesView = Collections.unmodifiableList(names);
private String active = DEFAULT;
/** The active profile's entries for modules this build doesn't have. */
private JsonObject unknown = new JsonObject();
/**
* @param warnings where problems with the files go (one line each, for the log)
*/
public Profiles(ConfigStorage storage, List<Module> modules, Consumer<String> warnings) {
this.storage = storage;
this.modules = modules;
this.warnings = warnings;
names.add(DEFAULT);
}
/** Every profile's name, in the order they were made. */
public List<String> names() {
return namesView;
}
/** The active profile's name. */
public String active() {
return active;
}
/** Reads the profile list and applies the active profile; every default if there's none yet. */
public void load() throws IOException {
JsonObject index = parse(INDEX, storage.read(INDEX));
names.clear();
JsonElement listed = index.get("profiles");
if (listed != null && listed.isJsonArray()) {
for (JsonElement name : listed.getAsJsonArray()) {
if (name.isJsonPrimitive() && validName(name.getAsString()) && indexOf(name.getAsString()) < 0) {
names.add(name.getAsString());
}
}
}
if (names.isEmpty()) {
names.add(DEFAULT);
}
JsonElement chosen = index.get("active");
String wanted = chosen != null && chosen.isJsonPrimitive() ? chosen.getAsString() : DEFAULT;
int at = indexOf(wanted);
active = names.get(at < 0 ? 0 : at);
apply(active);
}
/** Writes the active profile and the list. */
public void save() throws IOException {
storage.write(file(active), pretty(ProfileCodec.write(modules, unknown)));
writeIndex();
}
/**
* Saves the active profile, then makes {@code name} active and applies it.
*
* @return false if there's no such profile
*/
public boolean switchTo(String name) throws IOException {
int at = indexOf(name);
if (at < 0) {
return false;
}
save();
active = names.get(at);
apply(active);
writeIndex();
return true;
}
/**
* Saves the active profile, then makes a copy of it called {@code name} and makes that active.
*
* @return false if the name isn't {@linkplain #validName valid} or is taken
*/
public boolean create(String name) throws IOException {
if (!validName(name) || indexOf(name) >= 0) {
return false;
}
save();
names.add(name);
active = name;
save();
return true;
}
/**
* Deletes the profile {@code name}. If it's the active one, the first one left becomes active.
*
* @return false if there's no such profile or it's the only one
*/
public boolean delete(String name) throws IOException {
int at = indexOf(name);
if (at < 0 || names.size() == 1) {
return false;
}
String deleted = names.remove(at);
storage.delete(file(deleted));
if (deleted.equals(active)) {
active = names.get(0);
apply(active);
}
writeIndex();
return true;
}
/**
* Whether {@code name} can name a profile: 1 to 24 letters, digits, spaces, {@code _}, {@code -}
* or {@code .}, not starting or ending with a space and not starting with a dot (the 1.8 PvP
* preset's name has one). It's also the file's name.
*/
public static boolean validName(String name) {
if (name.isEmpty()
|| name.length() > MAX_NAME
|| name.isBlank()
|| !name.strip().equals(name)
|| name.charAt(0) == '.') {
return false;
}
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (!(Character.isLetterOrDigit(c) || c == ' ' || c == '_' || c == '-' || c == '.') || c > 0x7F) {
return false;
}
}
return true;
}
private void apply(String name) throws IOException {
unknown = ProfileCodec.read(parse(file(name), storage.read(file(name))), modules);
}
private void writeIndex() throws IOException {
JsonObject index = new JsonObject();
index.addProperty("format", ProfileCodec.FORMAT);
index.addProperty("active", active);
JsonArray list = new JsonArray();
for (String name : names) {
list.add(name);
}
index.add("profiles", list);
storage.write(INDEX, pretty(index));
}
/** Profile names are matched without case: the browser's files and Windows' don't tell them apart. */
private int indexOf(String name) {
for (int i = 0; i < names.size(); i++) {
if (names.get(i).toLowerCase(Locale.ROOT).equals(name.toLowerCase(Locale.ROOT))) {
return i;
}
}
return -1;
}
private static String file(String name) {
return "profiles/" + name + ".json";
}
private JsonObject parse(String path, @Nullable String text) {
if (text == null) {
return new JsonObject();
}
try {
JsonElement root = JsonParser.parseString(text);
if (root.isJsonObject()) {
return root.getAsJsonObject();
}
warnings.accept(path + " isn't a JSON object; using the defaults");
} catch (JsonParseException e) {
warnings.accept(path + " can't be read (" + e.getMessage() + "); using the defaults");
}
return new JsonObject();
}
private static String pretty(JsonObject root) {
return GSON.toJson(root) + "\n";
}
}
@@ -0,0 +1,150 @@
package incari.framework.config;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import incari.framework.hud.Shape;
import incari.framework.waypoint.Waypoint;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.function.Consumer;
import org.jspecify.annotations.Nullable;
/**
* A world's waypoints as JSON.
*
* <pre>{@code
* {
* "format": 1,
* "waypoints": [
* { "name": "Base", "x": 120, "y": 64, "z": -48, "dimension": "minecraft:overworld",
* "color": "#5B8CFF", "icon": "circle", "visible": true, "beam": true, "death": false }
* ]
* }
* }</pre>
*
* <p>Reading is forgiving: a waypoint without a name or a position is left out (and reported), and
* a value missing or out of place takes its default.
*/
public final class WaypointCodec {
/** The format's version; a newer one is read as far as it's understood. */
public static final int FORMAT = 1;
private WaypointCodec() {}
/** The waypoints as the file's text. */
public static String write(List<Waypoint> waypoints) {
JsonArray array = new JsonArray();
for (Waypoint waypoint : waypoints) {
JsonObject entry = new JsonObject();
entry.addProperty("name", waypoint.name());
entry.addProperty("x", waypoint.x());
entry.addProperty("y", waypoint.y());
entry.addProperty("z", waypoint.z());
entry.addProperty("dimension", waypoint.dimension());
// #RRGGBB: colorText's #AARRGGBB less the alpha, which a waypoint hasn't.
entry.addProperty(
"color", "#" + ProfileCodec.colorText(waypoint.rgb()).substring(3));
entry.addProperty("icon", waypoint.icon().name().toLowerCase(Locale.ROOT));
entry.addProperty("visible", waypoint.isVisible());
entry.addProperty("beam", waypoint.hasBeam());
entry.addProperty("death", waypoint.isDeath());
array.add(entry);
}
JsonObject root = new JsonObject();
root.addProperty("format", FORMAT);
root.add("waypoints", array);
return root.toString();
}
/**
* The waypoints in a file's text.
*
* @param problems told about each waypoint left out
*/
public static List<Waypoint> read(String text, Consumer<String> problems) {
List<Waypoint> waypoints = new ArrayList<>();
JsonElement parsed = JsonParser.parseString(text);
if (!parsed.isJsonObject()) {
problems.accept("not a waypoints file");
return waypoints;
}
JsonElement entries = parsed.getAsJsonObject().get("waypoints");
if (entries == null || !entries.isJsonArray()) {
return waypoints;
}
for (JsonElement element : entries.getAsJsonArray()) {
Waypoint waypoint = element.isJsonObject() ? waypoint(element.getAsJsonObject()) : null;
if (waypoint == null) {
problems.accept("left out a waypoint that couldn't be read: " + element);
} else {
waypoints.add(waypoint);
}
}
return waypoints;
}
private static @Nullable Waypoint waypoint(JsonObject entry) {
String name = string(entry, "name");
JsonPrimitive x = number(entry, "x");
JsonPrimitive y = number(entry, "y");
JsonPrimitive z = number(entry, "z");
if (name == null || x == null || y == null || z == null) {
return null;
}
String dimension = string(entry, "dimension");
String colorText = string(entry, "color");
Integer color = colorText == null ? null : ProfileCodec.parseColor(colorText);
Waypoint waypoint = new Waypoint(
name,
x.getAsInt(),
y.getAsInt(),
z.getAsInt(),
dimension == null ? "minecraft:overworld" : dimension,
color == null ? Waypoint.COLORS.get(0) : color,
shape(string(entry, "icon")));
waypoint.setVisible(bool(entry, "visible", true));
waypoint.setBeam(bool(entry, "beam", true));
waypoint.setDeath(bool(entry, "death", false));
return waypoint;
}
private static Shape shape(@Nullable String key) {
if (key != null) {
for (Shape shape : Shape.MARKERS) {
if (shape.name().toLowerCase(Locale.ROOT).equals(key)) {
return shape;
}
}
}
return Shape.CIRCLE;
}
private static @Nullable String string(JsonObject entry, String key) {
JsonElement element = entry.get(key);
boolean fits = element != null
&& element.isJsonPrimitive()
&& element.getAsJsonPrimitive().isString();
return fits ? element.getAsString() : null;
}
private static @Nullable JsonPrimitive number(JsonObject entry, String key) {
JsonElement element = entry.get(key);
boolean fits = element != null
&& element.isJsonPrimitive()
&& element.getAsJsonPrimitive().isNumber();
return fits ? element.getAsJsonPrimitive() : null;
}
private static boolean bool(JsonObject entry, String key, boolean otherwise) {
JsonElement element = entry.get(key);
boolean fits = element != null
&& element.isJsonPrimitive()
&& element.getAsJsonPrimitive().isBoolean();
return fits ? element.getAsBoolean() : otherwise;
}
}
@@ -0,0 +1,5 @@
/** Profiles and their files: which modules are on and how they're set, as JSON. */
@NullMarked
package incari.framework.config;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,14 @@
package incari.framework.event;
/** Receives {@link Events#ATTACK}. */
@FunctionalInterface
public interface AttackListener {
/**
* The player attacked an entity.
*
* @param reach how far the hit was from the player's eyes, in blocks: to the point on the
* target's box the crosshair met
*/
void onAttack(double reach);
}
@@ -0,0 +1,41 @@
package incari.framework.event;
/**
* Which way the camera looks this frame, as {@link Events#CAMERA} hands it to listeners: the
* player's view, which a listener may turn ({@link #set}) without turning the player. Degrees,
* the game's: yaw 0 faces south and grows toward the west; pitch 90 looks straight down. One object,
* reused every frame.
*/
public final class CameraAngles {
private float yaw;
private float pitch;
private boolean changed;
/** The game's side: the player's view, before the listeners run. */
public void reset(float yaw, float pitch) {
this.yaw = yaw;
this.pitch = pitch;
this.changed = false;
}
public float yaw() {
return yaw;
}
public float pitch() {
return pitch;
}
/** Turns the camera to {@code yaw}, {@code pitch}; the player keeps facing their way. */
public void set(float yaw, float pitch) {
this.yaw = yaw;
this.pitch = pitch;
this.changed = true;
}
/** Whether a listener turned it. */
public boolean changed() {
return changed;
}
}
@@ -0,0 +1,9 @@
package incari.framework.event;
/** Receives {@link Events#CAMERA}. */
@FunctionalInterface
public interface CameraListener {
/** The camera is being placed for this frame. */
void onCamera(CameraAngles camera);
}
@@ -0,0 +1,30 @@
package incari.framework.event;
/**
* One kind of event and the listener interface that receives it. The channels are the constants in
* {@link Events}; a module subscribes to them in its constructor ({@code Module.on}).
*
* @param <L> the listener interface
*/
// L is only read by the compiler: it ties a channel to its listener type in Module.on and EventBus.add.
@SuppressWarnings("UnusedTypeParameter")
public final class Channel<L> {
final int index;
private final String name;
Channel(int index, String name) {
this.index = index;
this.name = name;
}
/** The channel's name, for logs. */
public String name() {
return name;
}
@Override
public String toString() {
return name;
}
}
@@ -0,0 +1,44 @@
package incari.framework.event;
/**
* Counts a mouse button's clicks over the last second: clicks a second, as CPS and Keystrokes show
* them. Fed from {@link Events#CLICK}; read at any time. Allocates nothing.
*/
public final class ClickCounter {
/** The window counted, in milliseconds. */
public static final long WINDOW = 1000;
/** More than anyone clicks in a second: older clicks beyond it are forgotten. */
private static final int MAX = 64;
private final long[] times = new long[MAX];
private int next;
private int size;
/** A click at {@code millis}. */
public void click(long millis) {
times[next] = millis;
next = (next + 1) % MAX;
size = Math.min(size + 1, MAX);
}
/** Clicks in the second up to {@code millis}. */
public int perSecond(long millis) {
int count = 0;
for (int i = 0; i < size; i++) {
long at = times[(next - 1 - i + MAX) % MAX];
if (millis - at >= WINDOW) {
break;
}
count++;
}
return count;
}
/** Forgets every click. */
public void clear() {
size = 0;
next = 0;
}
}
@@ -0,0 +1,22 @@
package incari.framework.event;
/** Receives {@link Events#CLICK}. */
@FunctionalInterface
public interface ClickListener {
/** The left mouse button. */
int LEFT = 0;
/** The right mouse button. */
int RIGHT = 1;
/** The middle button (the wheel). */
int MIDDLE = 2;
/**
* A mouse button went down over the game, with no screen open.
*
* @param button {@link #LEFT}, {@link #RIGHT}, {@link #MIDDLE} or a side button (3 up)
*/
void onClick(int button);
}
@@ -0,0 +1,44 @@
package incari.framework.event;
/**
* A tooltip about to be shown for an item holding others (a shulker box), as {@link
* Events#CONTAINER_TOOLTIP} hands it to listeners. A listener may show the contents as a grid of
* items instead of the game's lines of text. One object, reused.
*/
public final class ContainerTooltip {
private boolean shiftDown;
private boolean preview;
private boolean tinted;
/** The game's side: this tooltip, before the listeners run. */
public void reset(boolean shiftDown) {
this.shiftDown = shiftDown;
this.preview = false;
this.tinted = false;
}
/** Whether Shift is held as the tooltip shows. */
public boolean shiftDown() {
return shiftDown;
}
/** Whether the contents show as a grid of items, in place of the game's lines. */
public boolean preview() {
return preview;
}
/** Shows the contents as a grid of items. */
public void setPreview(boolean on) {
this.preview = on;
}
/** Whether the grid takes the box's dye color. */
public boolean tinted() {
return tinted;
}
public void setTinted(boolean on) {
this.tinted = on;
}
}
@@ -0,0 +1,9 @@
package incari.framework.event;
/** Receives {@link Events#CONTAINER_TOOLTIP}. */
@FunctionalInterface
public interface ContainerTooltipListener {
/** A container item's tooltip is being made. */
void onContainerTooltip(ContainerTooltip tooltip);
}
@@ -0,0 +1,64 @@
package incari.framework.event;
import incari.framework.hud.HudCanvas;
import org.jspecify.annotations.Nullable;
/**
* The crosshair about to be drawn, as {@link Events#CROSSHAIR} hands it to listeners: where its
* middle is, how big a screen pixel is, and the attack's state. A listener draws its own on {@link
* #canvas()}; while anyone listens the game's isn't drawn. One object, reused every frame.
*/
public final class Crosshair {
private @Nullable HudCanvas canvas;
private float centerX;
private float centerY;
private float pixel;
private float attackStrength;
private boolean onTarget;
/** The game's side: this frame's crosshair, before the listeners run. */
public void reset(
HudCanvas canvas, float centerX, float centerY, float pixel, float attackStrength, boolean onTarget) {
this.canvas = canvas;
this.centerX = centerX;
this.centerY = centerY;
this.pixel = pixel;
this.attackStrength = attackStrength;
this.onTarget = onTarget;
}
/** What to draw with, in GUI units. */
public HudCanvas canvas() {
HudCanvas current = canvas;
if (current == null) {
throw new IllegalStateException("No crosshair is being drawn");
}
return current;
}
/** The screen's middle across, in GUI units (a half when the screen's pixels are odd). */
public float centerX() {
return centerX;
}
/** The screen's middle down. */
public float centerY() {
return centerY;
}
/** One screen pixel in GUI units: 1 over the GUI scale. */
public float pixel() {
return pixel;
}
/** How charged the next attack is, 0 just swung to 1 ready. */
public float attackStrength() {
return attackStrength;
}
/** Whether the crosshair is on a living entity in reach. */
public boolean onTarget() {
return onTarget;
}
}
@@ -0,0 +1,9 @@
package incari.framework.event;
/** Receives {@link Events#CROSSHAIR}. */
@FunctionalInterface
public interface CrosshairListener {
/** The crosshair is to be drawn: draw one on its canvas. */
void onCrosshair(Crosshair crosshair);
}
@@ -0,0 +1,278 @@
package incari.framework.event;
import incari.framework.hud.WorldCanvas;
import incari.framework.hud.WorldOverlay;
/**
* The listeners of every {@link Channel}, and the game's way to fire them. Game thread only.
*
* <p>Each channel's listeners are one array, replaced on every subscribe or unsubscribe: firing
* walks the array it read without allocating, and a listener may (un)subscribe during a fire,
* taking effect at the next one. A channel no enabled module listens to costs only a length check.
*
* <p>A listener that throws is reported to the {@link Failures} with its owner, and the fire goes
* on to the next listener: one broken module doesn't take the game down.
*/
public final class EventBus {
/** What happens to a listener's exception. */
@FunctionalInterface
public interface Failures {
/**
* A listener threw.
*
* @param owner the object it was subscribed with (its module)
* @param channel the event being fired
* @param error what it threw
*/
void failed(Object owner, Channel<?> channel, RuntimeException error);
}
private static final Object[] EMPTY = new Object[0];
/** Per channel: owner, listener, owner, listener... */
private final Object[][] lists = new Object[Events.COUNT][];
private final Failures failures;
/** A bus with no listeners. */
public EventBus(Failures failures) {
this.failures = failures;
for (int i = 0; i < lists.length; i++) {
lists[i] = EMPTY;
}
}
/** Subscribes {@code listener} to {@code channel} on behalf of {@code owner}. */
public <L> void add(Channel<L> channel, Object owner, L listener) {
Object[] old = lists[channel.index];
Object[] grown = new Object[old.length + 2];
System.arraycopy(old, 0, grown, 0, old.length);
grown[old.length] = owner;
grown[old.length + 1] = listener;
lists[channel.index] = grown;
}
/** Unsubscribes {@code listener} (the same object) from {@code channel}; nothing if it isn't there. */
@SuppressWarnings("ReferenceEquality") // A listener is the object subscribed, not an equal one.
public <L> void remove(Channel<L> channel, L listener) {
Object[] old = lists[channel.index];
for (int i = 1; i < old.length; i += 2) {
if (old[i] == listener) {
Object[] shrunk = old.length == 2 ? EMPTY : new Object[old.length - 2];
System.arraycopy(old, 0, shrunk, 0, i - 1);
System.arraycopy(old, i + 1, shrunk, i - 1, old.length - i - 1);
lists[channel.index] = shrunk;
return;
}
}
}
/** How many listeners {@code channel} has. */
public int count(Channel<?> channel) {
return lists[channel.index].length / 2;
}
/** Fires {@link Events#TICK}. */
public void fireTick() {
Object[] list = lists[Events.TICK.index];
for (int i = 0; i < list.length; i += 2) {
try {
((TickListener) list[i + 1]).onTick();
} catch (RuntimeException e) {
failures.failed(list[i], Events.TICK, e);
}
}
}
/**
* Fires {@link Events#MOVEMENT}.
*
* @return whether a listener changed {@code input}
*/
public boolean fireMovement(MovementInput input) {
Object[] list = lists[Events.MOVEMENT.index];
for (int i = 0; i < list.length; i += 2) {
try {
((MovementListener) list[i + 1]).onMovementInput(input);
} catch (RuntimeException e) {
failures.failed(list[i], Events.MOVEMENT, e);
}
}
return input.changed();
}
/** Fires {@link Events#JOIN}. */
public void fireJoin(String server) {
Object[] list = lists[Events.JOIN.index];
for (int i = 0; i < list.length; i += 2) {
try {
((JoinListener) list[i + 1]).onJoin(server);
} catch (RuntimeException e) {
failures.failed(list[i], Events.JOIN, e);
}
}
}
/** Fires {@link Events#LEAVE}. */
public void fireLeave() {
Object[] list = lists[Events.LEAVE.index];
for (int i = 0; i < list.length; i += 2) {
try {
((LeaveListener) list[i + 1]).onLeave();
} catch (RuntimeException e) {
failures.failed(list[i], Events.LEAVE, e);
}
}
}
/**
* Fires {@link Events#FIRE_OVERLAY}.
*
* @return how far down the listeners moved the flames, in flame heights
*/
public float fireFireOverlay(FireOverlay overlay) {
Object[] list = lists[Events.FIRE_OVERLAY.index];
for (int i = 0; i < list.length; i += 2) {
try {
((FireOverlayListener) list[i + 1]).onFireOverlay(overlay);
} catch (RuntimeException e) {
failures.failed(list[i], Events.FIRE_OVERLAY, e);
}
}
return overlay.lower();
}
/** Fires {@link Events#OVERLAY}. */
public void fireOverlay(WorldOverlay overlay) {
Object[] list = lists[Events.OVERLAY.index];
for (int i = 0; i < list.length; i += 2) {
try {
((OverlayListener) list[i + 1]).onOverlay(overlay);
} catch (RuntimeException e) {
failures.failed(list[i], Events.OVERLAY, e);
}
}
}
/** Fires {@link Events#WORLD}. */
public void fireWorld(WorldCanvas canvas) {
Object[] list = lists[Events.WORLD.index];
for (int i = 0; i < list.length; i += 2) {
try {
((WorldListener) list[i + 1]).onWorld(canvas);
} catch (RuntimeException e) {
failures.failed(list[i], Events.WORLD, e);
}
}
}
/** Fires {@link Events#CLICK}. */
public void fireClick(int button) {
Object[] list = lists[Events.CLICK.index];
for (int i = 0; i < list.length; i += 2) {
try {
((ClickListener) list[i + 1]).onClick(button);
} catch (RuntimeException e) {
failures.failed(list[i], Events.CLICK, e);
}
}
}
/** Fires {@link Events#ATTACK}. */
public void fireAttack(double reach) {
Object[] list = lists[Events.ATTACK.index];
for (int i = 0; i < list.length; i += 2) {
try {
((AttackListener) list[i + 1]).onAttack(reach);
} catch (RuntimeException e) {
failures.failed(list[i], Events.ATTACK, e);
}
}
}
/** Fires {@link Events#CROSSHAIR}. */
public void fireCrosshair(Crosshair crosshair) {
Object[] list = lists[Events.CROSSHAIR.index];
for (int i = 0; i < list.length; i += 2) {
try {
((CrosshairListener) list[i + 1]).onCrosshair(crosshair);
} catch (RuntimeException e) {
failures.failed(list[i], Events.CROSSHAIR, e);
}
}
}
/** Fires {@link Events#TURN}. */
public void fireTurn(Turn turn) {
Object[] list = lists[Events.TURN.index];
for (int i = 0; i < list.length; i += 2) {
try {
((TurnListener) list[i + 1]).onTurn(turn);
} catch (RuntimeException e) {
failures.failed(list[i], Events.TURN, e);
}
}
}
/** Fires {@link Events#CAMERA}. */
public void fireCamera(CameraAngles camera) {
Object[] list = lists[Events.CAMERA.index];
for (int i = 0; i < list.length; i += 2) {
try {
((CameraListener) list[i + 1]).onCamera(camera);
} catch (RuntimeException e) {
failures.failed(list[i], Events.CAMERA, e);
}
}
}
/** Fires {@link Events#HELD_ITEM}. */
public void fireHeldItem(HeldItem item) {
Object[] list = lists[Events.HELD_ITEM.index];
for (int i = 0; i < list.length; i += 2) {
try {
((HeldItemListener) list[i + 1]).onHeldItem(item);
} catch (RuntimeException e) {
failures.failed(list[i], Events.HELD_ITEM, e);
}
}
}
/** Fires {@link Events#CONTAINER_TOOLTIP}. */
public void fireContainerTooltip(ContainerTooltip tooltip) {
Object[] list = lists[Events.CONTAINER_TOOLTIP.index];
for (int i = 0; i < list.length; i += 2) {
try {
((ContainerTooltipListener) list[i + 1]).onContainerTooltip(tooltip);
} catch (RuntimeException e) {
failures.failed(list[i], Events.CONTAINER_TOOLTIP, e);
}
}
}
/** Fires {@link Events#SCREENSHOT}. */
public void fireScreenshot(String fileName) {
Object[] list = lists[Events.SCREENSHOT.index];
for (int i = 0; i < list.length; i += 2) {
try {
((ScreenshotListener) list[i + 1]).onScreenshot(fileName);
} catch (RuntimeException e) {
failures.failed(list[i], Events.SCREENSHOT, e);
}
}
}
/** Fires {@link Events#KILL}. */
public void fireKill() {
Object[] list = lists[Events.KILL.index];
for (int i = 0; i < list.length; i += 2) {
try {
((KillListener) list[i + 1]).onKill();
} catch (RuntimeException e) {
failures.failed(list[i], Events.KILL, e);
}
}
}
}
@@ -0,0 +1,99 @@
package incari.framework.event;
/**
* The events a module can listen to. Each is fired on the game thread by one hook in the game.
*
* <p>Events are in the game's terms but carry no game types: what a listener gets is defined here
* and filled in by {@code :client}. A new event comes with the first module that needs it, with
* its hook (ADR 0046 lists what's planned).
*/
public final class Events {
/** Once a client tick (20 a second), in or out of a world, before the game reads its keybinds. */
public static final Channel<TickListener> TICK = new Channel<>(0, "tick");
/**
* Once a tick while the player is in a world, after the game reads the movement keys and before
* the player moves: listeners may change what the keys say ({@link MovementInput}).
*/
public static final Channel<MovementListener> MOVEMENT = new Channel<>(1, "movement");
/** When the player arrives in a world: a server's, or singleplayer's. */
public static final Channel<JoinListener> JOIN = new Channel<>(2, "join");
/** When the player leaves a world (to the title screen or another server). */
public static final Channel<LeaveListener> LEAVE = new Channel<>(3, "leave");
/**
* Each frame the fire overlay is drawn (the player burning, in first person), before it's
* drawn: listeners may move it ({@link FireOverlay}). Render thread.
*/
public static final Channel<FireOverlayListener> FIRE_OVERLAY = new Channel<>(4, "fire-overlay");
/**
* Each frame with the HUD shown, before the game's HUD and with the crosshair: listeners draw
* what follows the world on screen (a waypoint's label) on a {@link
* incari.framework.hud.WorldOverlay}. Drawn every frame, not with the HUD's refreshes. Render
* thread; a hot path.
*/
public static final Channel<OverlayListener> OVERLAY = new Channel<>(5, "overlay");
/**
* Each frame the world is drawn, while it's put together: listeners add to it (a waypoint's
* beam) on a {@link incari.framework.hud.WorldCanvas}. Render thread; a hot path.
*/
public static final Channel<WorldListener> WORLD = new Channel<>(6, "world");
/**
* When a mouse button goes down over the game with no screen open (CPS counts them). Game
* thread, as the press arrives.
*/
public static final Channel<ClickListener> CLICK = new Channel<>(7, "click");
/** When the player attacks an entity: how far the hit reached (Reach Display). Game thread. */
public static final Channel<AttackListener> ATTACK = new Channel<>(8, "attack");
/**
* Each frame the game would draw its crosshair (first person, the HUD shown): listeners draw
* their own ({@link Crosshair}); while anyone listens, the game's isn't drawn. Render thread; a
* hot path.
*/
public static final Channel<CrosshairListener> CROSSHAIR = new Channel<>(9, "crosshair");
/**
* When the mouse turns the view over the world: a listener may take the turn ({@link Turn}).
* Game thread, as the mouse moves.
*/
public static final Channel<TurnListener> TURN = new Channel<>(10, "turn");
/**
* Each frame the camera is placed: listeners may turn it without turning the player ({@link
* CameraAngles}). Render thread; a hot path.
*/
public static final Channel<CameraListener> CAMERA = new Channel<>(11, "camera");
/**
* Each frame, for each hand, before its item is drawn in first person: listeners say how
* ({@link HeldItem}). Render thread; a hot path.
*/
public static final Channel<HeldItemListener> HELD_ITEM = new Channel<>(12, "held-item");
/**
* When the tooltip of an item holding others (a shulker box) is made: listeners may show the
* contents as a grid ({@link ContainerTooltip}). Render thread, as the pointer hovers.
*/
public static final Channel<ContainerTooltipListener> CONTAINER_TOOLTIP = new Channel<>(13, "container-tooltip");
/** When a screenshot (F2) has been saved. Game thread. */
public static final Channel<ScreenshotListener> SCREENSHOT = new Channel<>(14, "screenshot");
/**
* When an entity the player hit in the last few seconds dies (Hit Effects' kill effect). Game
* thread, on the tick the client sees it die.
*/
public static final Channel<KillListener> KILL = new Channel<>(15, "kill");
static final int COUNT = 16;
private Events() {}
}
@@ -0,0 +1,26 @@
package incari.framework.event;
/**
* The flames drawn over the view while the player burns, as {@link Events#FIRE_OVERLAY} hands them
* to listeners. One object, reused every frame: listeners change it during the call and keep no
* reference.
*/
public final class FireOverlay {
private float lower;
/** The game's side: the flames where the game puts them, before the listeners run. */
public void reset() {
lower = 0;
}
/** How far down the flames are moved, in flame heights. */
public float lower() {
return lower;
}
/** Moves the flames down by {@code heights} of their height (0.3 for 30%). */
public void setLower(float heights) {
this.lower = heights;
}
}
@@ -0,0 +1,9 @@
package incari.framework.event;
/** Receives {@link Events#FIRE_OVERLAY}. */
@FunctionalInterface
public interface FireOverlayListener {
/** The fire overlay is about to be drawn; change {@code overlay} to move it. */
void onFireOverlay(FireOverlay overlay);
}
@@ -0,0 +1,119 @@
package incari.framework.event;
/**
* An item held in first person, about to be drawn, as {@link Events#HELD_ITEM} hands it to
* listeners: which hand, whether it's a shield or a sword, whether it's in use. Listeners say how it's
* drawn: lower (Low Shield), smaller (Short Items), or in 1.7's poses (1.7 Animations). One object, reused for each hand each
* frame.
*/
public final class HeldItem {
private boolean mainHand;
private boolean shield;
private boolean sword;
private boolean using;
private float lower;
private float scale;
private boolean legacyItems;
private boolean legacyRod;
private boolean legacyBlock;
private boolean swingWhileUsing;
/** The game's side: this hand's item, not a sword, before the listeners run. */
public void reset(boolean mainHand, boolean shield, boolean using) {
reset(mainHand, shield, false, using);
}
/** The game's side: this hand's item, before the listeners run. */
public void reset(boolean mainHand, boolean shield, boolean sword, boolean using) {
this.mainHand = mainHand;
this.shield = shield;
this.sword = sword;
this.using = using;
this.lower = 0;
this.scale = 1;
this.legacyItems = false;
this.legacyRod = false;
this.legacyBlock = false;
this.swingWhileUsing = false;
}
/** Whether it's in the main hand. */
public boolean mainHand() {
return mainHand;
}
/** Whether it's a shield. */
public boolean shield() {
return shield;
}
/** Whether it's a sword (the game's swords tag). */
public boolean sword() {
return sword;
}
/** Whether the player is using it now: blocking, eating, drawing a bow. */
public boolean using() {
return using;
}
/** How far down it's moved, in the view's units (about a screen's height is 1). */
public float lower() {
return lower;
}
/** Moves it down by {@code amount} of the view's units. */
public void setLower(float amount) {
this.lower = amount;
}
/** How big it's drawn against the game's size: 1 as the game draws it. */
public float scale() {
return scale;
}
/** Draws it {@code factor} times the game's size, toward the hand that holds it. */
public void setScale(float factor) {
this.scale = factor;
}
/** Whether flat items (swords, tools, most items) are held as 1.7 held them. */
public boolean legacyItems() {
return legacyItems;
}
public void setLegacyItems(boolean on) {
this.legacyItems = on;
}
/** Whether a fishing rod points the way 1.7's did. */
public boolean legacyRod() {
return legacyRod;
}
public void setLegacyRod(boolean on) {
this.legacyRod = on;
}
/** Whether a blocking sword takes 1.7's pose. */
public boolean legacyBlock() {
return legacyBlock;
}
public void setLegacyBlock(boolean on) {
this.legacyBlock = on;
}
/**
* Whether the arm swings while the item's in use (1.7's block-hit): attacking while blocking,
* eating or drawing a bow swings it, as 1.7 drew it. Only the drawing: nothing is sent.
*/
public boolean swingWhileUsing() {
return swingWhileUsing;
}
public void setSwingWhileUsing(boolean on) {
this.swingWhileUsing = on;
}
}
@@ -0,0 +1,9 @@
package incari.framework.event;
/** Receives {@link Events#HELD_ITEM}. */
@FunctionalInterface
public interface HeldItemListener {
/** A hand's item is about to be drawn in first person. */
void onHeldItem(HeldItem item);
}
@@ -0,0 +1,13 @@
package incari.framework.event;
/** Receives {@link Events#JOIN}. */
@FunctionalInterface
public interface JoinListener {
/**
* The player is in a world.
*
* @param server the server's address as the server list has it, or empty for singleplayer
*/
void onJoin(String server);
}
@@ -0,0 +1,9 @@
package incari.framework.event;
/** Receives {@link Events#KILL}. */
@FunctionalInterface
public interface KillListener {
/** An entity the player hit in the last few seconds died. */
void onKill();
}
@@ -0,0 +1,9 @@
package incari.framework.event;
/** Receives {@link Events#LEAVE}. */
@FunctionalInterface
public interface LeaveListener {
/** The player left the world. */
void onLeave();
}
@@ -0,0 +1,140 @@
package incari.framework.event;
/**
* The movement keys for one tick, as {@link Events#MOVEMENT} hands them to listeners. One object,
* reused every tick: listeners read and change it during the call and keep no reference.
*
* <p>Each value starts as the game read it: the key held, or latched if the game's own toggle
* option is on for it. The press counts are how many times the sprint and sneak keys went down
* since the last tick, so a tap shorter than a tick still counts.
*/
public final class MovementInput {
private boolean forward;
private boolean backward;
private boolean left;
private boolean right;
private boolean jump;
private boolean sneak;
private boolean sprint;
private int sneakPresses;
private int sprintPresses;
private boolean sneakToggledByGame;
private boolean sprintToggledByGame;
private boolean changed;
/**
* The game's side: this tick's keys, before the listeners run.
*
* @param sneakPresses presses of the sneak key since the last tick
* @param sprintPresses presses of the sprint key since the last tick
*/
public void reset(
boolean forward,
boolean backward,
boolean left,
boolean right,
boolean jump,
boolean sneak,
boolean sprint,
int sneakPresses,
int sprintPresses) {
this.forward = forward;
this.backward = backward;
this.left = left;
this.right = right;
this.jump = jump;
this.sneak = sneak;
this.sprint = sprint;
this.sneakPresses = sneakPresses;
this.sprintPresses = sprintPresses;
this.sneakToggledByGame = false;
this.sprintToggledByGame = false;
this.changed = false;
}
/**
* The game's side, after {@link #reset}: whether the game's own toggle options (Sneak: Toggle,
* Sprint: Toggle) are on, so {@link #sneak()} and {@link #sprint()} are the game's latches.
*/
public void gameToggles(boolean sneak, boolean sprint) {
this.sneakToggledByGame = sneak;
this.sprintToggledByGame = sprint;
}
/** Whether the game latches the sneak key itself (Sneak: Toggle in its controls). */
public boolean sneakToggledByGame() {
return sneakToggledByGame;
}
/** Whether the game latches the sprint key itself (Sprint: Toggle in its controls). */
public boolean sprintToggledByGame() {
return sprintToggledByGame;
}
/** Whether forward is held. */
public boolean forward() {
return forward;
}
/** Whether back is held. */
public boolean backward() {
return backward;
}
/** Whether strafe left is held. */
public boolean left() {
return left;
}
/** Whether strafe right is held. */
public boolean right() {
return right;
}
/** Whether jump is held. */
public boolean jump() {
return jump;
}
/** Whether the player sneaks this tick. */
public boolean sneak() {
return sneak;
}
/** Whether the player tries to sprint this tick (the game still decides whether they can). */
public boolean sprint() {
return sprint;
}
/** Presses of the sneak key since the last tick. */
public int sneakPresses() {
return sneakPresses;
}
/** Presses of the sprint key since the last tick. */
public int sprintPresses() {
return sprintPresses;
}
/** Makes the player sneak this tick, or not. */
public void setSneak(boolean sneak) {
if (this.sneak != sneak) {
this.sneak = sneak;
changed = true;
}
}
/** Makes the player try to sprint this tick, or not. */
public void setSprint(boolean sprint) {
if (this.sprint != sprint) {
this.sprint = sprint;
changed = true;
}
}
/** The game's side: whether any listener changed a value, so the game's copy needs replacing. */
public boolean changed() {
return changed;
}
}
@@ -0,0 +1,13 @@
package incari.framework.event;
/** Receives {@link Events#MOVEMENT}. */
@FunctionalInterface
public interface MovementListener {
/**
* The movement keys have been read for this tick. Hot path: don't allocate.
*
* @param input what the keys say; changes go to the player's movement
*/
void onMovementInput(MovementInput input);
}
@@ -0,0 +1,11 @@
package incari.framework.event;
import incari.framework.hud.WorldOverlay;
/** Receives {@link Events#OVERLAY}. */
@FunctionalInterface
public interface OverlayListener {
/** Draws over the world this frame. Hot path: don't allocate. */
void onOverlay(WorldOverlay overlay);
}
@@ -0,0 +1,13 @@
package incari.framework.event;
/** Receives {@link Events#SCREENSHOT}. */
@FunctionalInterface
public interface ScreenshotListener {
/**
* A screenshot was saved.
*
* @param fileName its file's name in the screenshots folder ("2026-10-10_22.41.03.png")
*/
void onScreenshot(String fileName);
}
@@ -0,0 +1,9 @@
package incari.framework.event;
/** Receives {@link Events#TICK}. */
@FunctionalInterface
public interface TickListener {
/** A client tick. */
void onTick();
}
@@ -0,0 +1,55 @@
package incari.framework.event;
/**
* The mouse turning the view, as {@link Events#TURN} hands it to listeners, in degrees after the
* player's sensitivity and inversion. A listener that takes the turn ({@link #consume()}) keeps it
* from the player: Freelook turns the camera instead. One that {@link #scale}s it turns the player
* less: Zoom, while zoomed in. One object, reused.
*/
public final class Turn {
private float yaw;
private float pitch;
private boolean consumed;
private boolean scaled;
/** The game's side: this turn, before the listeners run. */
public void reset(float yaw, float pitch) {
this.yaw = yaw;
this.pitch = pitch;
this.consumed = false;
this.scaled = false;
}
/** Degrees to the right. */
public float yaw() {
return yaw;
}
/** Degrees down. */
public float pitch() {
return pitch;
}
/** Keeps the turn from the player. */
public void consume() {
consumed = true;
}
/** Whether a listener took it. */
public boolean consumed() {
return consumed;
}
/** Turns the player {@code factor} times as far (0.25: a quarter as far). */
public void scale(float factor) {
yaw *= factor;
pitch *= factor;
scaled = true;
}
/** Whether a listener scaled it: the player turns by {@link #yaw()} and {@link #pitch()} as they are now. */
public boolean scaled() {
return scaled;
}
}
@@ -0,0 +1,9 @@
package incari.framework.event;
/** Receives {@link Events#TURN}. */
@FunctionalInterface
public interface TurnListener {
/** The mouse moved over the world. */
void onTurn(Turn turn);
}
@@ -0,0 +1,11 @@
package incari.framework.event;
import incari.framework.hud.WorldCanvas;
/** Receives {@link Events#WORLD}. */
@FunctionalInterface
public interface WorldListener {
/** Adds to the world drawn this frame. Hot path: don't allocate. */
void onWorld(WorldCanvas canvas);
}
@@ -0,0 +1,5 @@
/** The events modules listen to, and the bus the game's hooks fire them through. */
@NullMarked
package incari.framework.event;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,88 @@
package incari.framework.game;
import java.util.Map;
/**
* The game's block states and the world's blocks, as modules see them ({@link Game#blocks()}): a
* state is an int the client hands out, the same for the same state while the game runs; never
* saved. Game and render thread. Reads of the world must not block: a block in a chunk the client
* hasn't loaded is {@link #UNKNOWN}.
*/
public interface Blocks {
/** Air: no block. */
int AIR = 0;
/** No such state, or a block the client can't see (an unloaded chunk, out of the world's height). */
int UNKNOWN = -1;
/** No game: every state unknown, the world empty. */
Blocks NONE = new Blocks() {
@Override
public int state(String name, Map<String, String> properties, int dataVersion) {
return UNKNOWN;
}
@Override
public int transform(int state, Mirror mirror, int clockwiseTurns) {
return state;
}
@Override
public int at(int x, int y, int z) {
return UNKNOWN;
}
@Override
public boolean isAir(int state) {
return state == AIR;
}
@Override
public int block(int state) {
return state;
}
@Override
public String itemId(int state) {
return "";
}
@Override
public String name(int state) {
return "";
}
};
/**
* The state named {@code name} ({@code minecraft:oak_stairs}) with these {@code properties}
* ({@code facing=north}), as saved by the game at {@code dataVersion} and upgraded to this one;
* properties left out take the block's defaults. {@link #UNKNOWN} if the game has no such block.
* Slow-ish: call it once per palette entry, not per block.
*/
int state(String name, Map<String, String> properties, int dataVersion);
/**
* {@code state} mirrored, then turned {@code clockwiseTurns} quarter turns seen from above, as
* the game turns a structure's blocks: stairs face the other way, logs lie along the other axis.
*/
int transform(int state, Mirror mirror, int clockwiseTurns);
/** The block at {@code x, y, z} in the player's world; {@link #UNKNOWN} where the client has none. */
int at(int x, int y, int z);
/** Whether {@code state} is air of any kind (cave air too). */
boolean isAir(int state);
/**
* One number per block, whatever its state: two states are of the same block when these are
* equal (oak stairs facing north and south).
*/
int block(int state);
/** The id of the item that places {@code state} ({@code minecraft:torch} for a wall torch); empty for none. */
String itemId(int state);
/** {@code state}'s block's name in the player's language ("Oak Stairs"). */
String name(int state);
}
@@ -0,0 +1,39 @@
package incari.framework.game;
/**
* A burst of particles a module shows on what the player hit ({@link Game#effectOnTarget}): the
* game's own particles, on this client only.
*/
public enum Effect {
/** The game's critical hit stars. */
CRITS("Crits"),
/** The blue stars of an enchanted weapon's hit. */
MAGIC("Magic"),
/** Little electric sparks. */
SPARKS("Sparks"),
/** Hearts. */
HEARTS("Hearts"),
/** Flames. */
FLAMES("Flames"),
/** Snowflakes. */
SNOW("Snow"),
/** A firework's burst of sparkles. */
FIREWORK("Firework"),
/** Souls rising. */
SOULS("Souls"),
/** A puff of smoke. */
SMOKE("Smoke"),
/** A totem's green and gold. */
TOTEM("Totem");
private final String label;
Effect(String label) {
this.label = label;
}
/** What the settings screen calls it. */
public String label() {
return label;
}
}
@@ -0,0 +1,11 @@
package incari.framework.game;
/** Whether an effect helps the player or hurts them. */
public enum EffectCategory {
/** Speed, strength, regeneration. */
BENEFICIAL,
/** Poison, slowness, weakness. */
HARMFUL,
/** Neither: glowing, say. */
NEUTRAL
}
@@ -0,0 +1,23 @@
package incari.framework.game;
/**
* A status effect on the player, as modules see it. Drawn with {@code HudCanvas.effect}. Reused by
* the client: read it during the call that handed it out.
*/
public interface EffectView {
/** The effect's name in the player's language ("Speed"); the same string each call. */
String name();
/** 0 for level I, 1 for level II, and so on. */
int amplifier();
/** Ticks left (20 a second); meaningless if {@link #isInfinite()}. */
int duration();
/** Whether it never runs out. */
boolean isInfinite();
/** Whether it helps or hurts. */
EffectCategory category();
}
@@ -0,0 +1,17 @@
package incari.framework.game;
/** Where the player wears or holds an item. */
public enum EquipmentSlot {
/** The helmet. */
HEAD,
/** The chestplate (or elytra). */
CHEST,
/** The leggings. */
LEGS,
/** The boots. */
FEET,
/** The item in the main hand. */
MAINHAND,
/** The item in the off hand. */
OFFHAND
}
@@ -0,0 +1,414 @@
package incari.framework.game;
import incari.framework.waypoint.Waypoint;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import org.jspecify.annotations.Nullable;
/**
* The game as modules see it: the local player, the world they're in, the options a module may
* hold ({@link incari.framework.Module#holdOption}) and the client's screens a module may open. The
* client fills it in; {@link #NONE} stands in where there's no game. Game and render thread (the
* same thread in Incari's builds).
*/
public interface Game {
/** No player and no options to hold: every read is empty, every write dropped. */
Game NONE = new Game() {
@Override
public @Nullable PlayerView player() {
return null;
}
@Override
public PlayerView samplePlayer() {
return PlayerView.EMPTY;
}
@Override
public double option(GameOption option) {
return option.defaultValue();
}
@Override
public void setOption(GameOption option, double value) {}
@Override
public boolean packSelected(String packId) {
return false;
}
@Override
public boolean selectPack(String packId, boolean on) {
return false;
}
@Override
public @Nullable String world() {
return null;
}
@Override
public void openWaypoints() {}
@Override
public void editWaypoint(Waypoint waypoint, boolean adding) {}
@Override
public void openWorldMap() {}
@Override
public void rememberMap(boolean remember) {}
@Override
public boolean isDown(GameKey key) {
return false;
}
@Override
public String keyName(GameKey key) {
return "";
}
@Override
public int fps() {
return 0;
}
@Override
public ItemView item(String itemId) {
return PlayerView.NO_ITEM;
}
@Override
public float attackStrength() {
return 1;
}
@Override
public boolean onTarget() {
return false;
}
@Override
public Perspective perspective() {
return Perspective.FIRST_PERSON;
}
@Override
public void setPerspective(Perspective perspective) {}
@Override
public void overrideSky(@Nullable Weather weather, int timeOfDay) {}
@Override
public void applyTheme(@Nullable ThemeColors theme) {}
@Override
public void applyFont(UiFont font) {}
@Override
public String clipboard() {
return "";
}
@Override
public void copy(String text) {}
@Override
public void showMessage(String title, String message) {}
@Override
public void askText(String title, String prompt, String initial, Consumer<String> entered) {}
@Override
public Blocks blocks() {
return Blocks.NONE;
}
@Override
public void chooseFile(
String title, String folder, List<String> extensions, BiConsumer<String, byte[]> chosen) {}
@Override
public void openScreenshots() {}
@Override
public boolean copyScreenshot(String fileName) {
return false;
}
@Override
public void overrideBlockOutline(int argb, float width, int fillArgb) {}
@Override
public void overrideHitboxes(@Nullable Hitboxes hitboxes) {}
@Override
public void overrideNoRender(@Nullable NoRender noRender) {}
@Override
public void predictBreaks(boolean crystals, boolean anchors) {}
@Override
public void overrideBrightness(float level) {}
@Override
public void showPackSkies(float brightness) {}
@Override
public void overrideHitColor(int rgb, int strength) {}
@Override
public void overrideGlintColor(int rgb) {}
@Override
public void overrideFov(float scale) {}
@Override
public void overrideSmoothCamera(boolean on) {}
@Override
public void overrideSaturation(int rgb) {}
@Override
public void effectOnTarget(Effect effect, int count, boolean sound) {}
};
/**
* The local player, or null outside a world. The view is reused: read it during the call that
* asked for it, and keep no reference to what it hands out.
*/
@Nullable
PlayerView player();
/**
* A made-up player in diamond armor with a couple of effects, for the HUD editor to show where
* an element goes while the real player has nothing to show.
*/
PlayerView samplePlayer();
/** {@code option}'s value now, in the game's options. */
double option(GameOption option);
/** Sets {@code option} in the game's options and saves them, as its slider would. */
void setOption(GameOption option, double value);
/**
* Whether the resource pack {@code packId} ({@code programmer_art}) is on, as the game's
* Resource Packs screen last left it.
*/
boolean packSelected(String packId);
/**
* Turns the resource pack {@code packId} on (on top of the others) or off, as the Resource
* Packs screen would: the game's options are saved and its resources reload if that changed
* anything. The reload takes a moment; {@link #packSelected} says so at once.
*
* @return whether the pack is now as asked: false if the game has no such pack
*/
boolean selectPack(String packId, boolean on);
/**
* Which world the player is in, as a name to keep things by: {@code server/<address>} on a
* server, {@code world/<folder>} in singleplayer; null outside a world. The same world gives the
* same name each time it's joined.
*/
@Nullable
String world();
/** Opens the waypoint list over the game ({@link incari.framework.ModuleSystem#waypoints()}). */
void openWaypoints();
/**
* Opens the waypoint editor over the game for {@code waypoint}: a new one the player may still
* cancel ({@code adding}; added only if they save it), or one of the world's to change.
*/
void editWaypoint(Waypoint waypoint, boolean adding);
/**
* Opens the world map over the game: the land the map has seen, to drag about and zoom, with
* the player and the waypoints on it.
*/
void openWorldMap();
/**
* Whether what the map sees is saved per world and dimension, so the world map shows land the
* player has left, even on a later day. Off, it shows what the map saw since joining, while it
* has room. The minimap's setting.
*/
void rememberMap(boolean remember);
/**
* Whether the player holds {@code key} down, as the game reads its keybinds: false while a
* screen is open.
*/
boolean isDown(GameKey key);
/** What {@code key} is bound to, short, as the controls screen writes it ("W", "LMB"). */
String keyName(GameKey key);
/** Frames drawn in the last second, as the debug screen counts them. */
int fps();
/**
* Milliseconds on a clock that only goes forward, for timing what happens between ticks (clicks
* a second). Not the time of day.
*/
default long millis() {
return System.nanoTime() / 1_000_000L;
}
/**
* One of the item with this id ({@code minecraft:totem_of_undying}), to draw its icon; {@link
* ItemView#isEmpty()} if there's no such item. The same view for the same id.
*/
ItemView item(String itemId);
/** How charged the player's next attack is, 0 just swung to 1 ready (1.9's cooldown); 1 outside a world. */
float attackStrength();
/** Whether the crosshair is on a living entity the player can reach. */
boolean onTarget();
/** Where the camera is (F5). */
Perspective perspective();
/** Moves the camera, as F5 would. */
void setPerspective(Perspective perspective);
/**
* Shows the sky as the player chose, on this client only: {@code weather} (null for the
* world's) and {@code timeOfDay} in ticks from dawn, 0 to 23999 (6000 noon, 18000 midnight; -1
* for the world's). Clearing both brings the world's back. The holding module calls it every
* tick; the client restores the server's weather after.
*/
void overrideSky(@Nullable Weather weather, int timeOfDay);
/** Opens the screenshot gallery over whatever's shown. */
void openScreenshots();
/**
* Puts the screenshot {@code fileName} on the clipboard as an image, without waiting.
*
* @return false if this platform can't put images on the clipboard
*/
boolean copyScreenshot(String fileName);
/**
* Draws the outline of the block the crosshair is on in {@code argb}, {@code width} screen
* pixels wide (0 for the game's width), its faces filled in {@code fillArgb} (0: not filled);
* {@code argb} 0 gives the game's own back. Held until changed.
*/
void overrideBlockOutline(int argb, float width, int fillArgb);
/**
* Draws entities' hitboxes as {@code hitboxes} says, every frame, whatever the server's debug
* rules; null draws none. F3+B's own boxes show instead while the player has those on. Held until
* changed.
*/
void overrideHitboxes(@Nullable Hitboxes hitboxes);
/**
* Leaves out of the world what {@code noRender} hides, from the next frame (particles: from the
* next one made); null draws everything again. Held until changed.
*/
void overrideNoRender(@Nullable NoRender noRender);
/**
* Takes away an end crystal the player hits ({@code crystals}), and a charged respawn anchor the
* player sets off where it explodes ({@code anchors}), on this client at once, not a round trip
* later when the server says so: the next one can go in its place without waiting for the ping.
* Only what the player's own click already sent the server: no packet more, none sooner. One
* the server keeps comes back. Both false gives the game's own back. Held until changed.
*/
void predictBreaks(boolean crystals, boolean anchors);
/**
* Lights the world as night vision would, at {@code level} from 0 (the game's own light) to 1
* (everything fully lit), on this client only; a real night vision effect still shows if it's
* stronger. Held until changed.
*/
void overrideBrightness(float level);
/**
* Draws the custom skies the resource packs bring (OptiFine's {@code optifine/sky/world0}), in
* the overworld on this client only, at {@code brightness} from 0 (none: the game's own sky) to
* 1 (as the pack made them). The game's sky is drawn under them. Held until changed.
*/
void showPackSkies(float brightness);
/**
* Tints hurt entities {@code rgb} instead of red, {@code strength} percent of the way from their
* own colors to it (the game's red is 30%); a strength of 0 gives the game's own tint back. Held
* until changed.
*/
void overrideHitColor(int rgb, int strength);
/** Colors the enchantment glint {@code rgb} instead of its purple; -1 for the game's own. */
void overrideGlintColor(int rgb);
/**
* Narrows the world's field of view to {@code scale} of the game's (0.25: a quarter, four times
* zoomed), on this client only; the hand and the HUD keep theirs. 1 gives the game's own back.
* Held until changed.
*/
void overrideFov(float scale);
/**
* Turns the game's cinematic camera (smooth turning, F8's) on while held; false gives the player's
* own back.
*/
void overrideSmoothCamera(boolean on);
/**
* Shows the player's saturation on the hunger bar: the saturated shanks outlined in {@code rgb}. -1 for
* the game's own bar. Held until changed.
*/
void overrideSaturation(int rgb);
/**
* Shows {@code count} of {@code effect}'s particles on the entity the player last hit, or where
* it was when it died, with the effect's sound if {@code sound}; on this client only. Nothing if
* the player hasn't hit anything in this world.
*/
void effectOnTarget(Effect effect, int count, boolean sound);
/** Draws the client in {@code theme} from the next frame; null for Frost, its own. */
void applyTheme(@Nullable ThemeColors theme);
/**
* Draws the game's and the client's text in {@code font} from the next frame or two (a new font
* loads in the background first).
*/
void applyFont(UiFont font);
/** The clipboard's text; empty if it holds none (in the browser: the last text pasted). */
String clipboard();
/** Puts {@code text} on the clipboard. */
void copy(String text);
/** Shows {@code message} under {@code title} for a few seconds, in a corner over what's shown. */
void showMessage(String title, String message);
/**
* Asks the player for a line of text: {@code title} and {@code prompt} above a field holding
* {@code initial}. {@code entered} gets the text on Done (game thread, field closed), and isn't
* called on cancel. In the browser this is how a module reads the clipboard: a page only gets
* clipboard text on a paste (Ctrl+V), and {@link #clipboard()} has only the last one.
*/
void askText(String title, String prompt, String initial, Consumer<String> entered);
/** The game's block states and the world's blocks. */
Blocks blocks();
/**
* Lets the player choose one of the files in the game directory's {@code folder} ending in one of
* {@code extensions} ({@code .schem}), on a screen over the game that also shows them the
* folder, to add files to it (in the browser: from their computer). {@code chosen} gets the
* file's name and contents (game thread, screen closed), and isn't called on cancel.
*/
void chooseFile(String title, String folder, List<String> extensions, BiConsumer<String, byte[]> chosen);
}
@@ -0,0 +1,16 @@
package incari.framework.game;
/** One of the game's own keybinds, as the player has bound it ({@link Game#isDown}). */
public enum GameKey {
FORWARD,
LEFT,
BACK,
RIGHT,
JUMP,
SNEAK,
SPRINT,
/** Attack / destroy: the left mouse button by default. */
ATTACK,
/** Use item / place block: the right mouse button by default. */
USE
}
@@ -0,0 +1,44 @@
package incari.framework.game;
/**
* A game option a module may hold while it's on ({@link incari.framework.Module#holdOption}): the
* option's own control shows the module's value, and changing it gives control back to the player.
* A slider's is a fraction from 0 to 1; a choice's is its index.
*/
public enum GameOption {
/** Chat Settings' Text Background Opacity: the dark box behind chat lines. */
TEXT_BACKGROUND_OPACITY("Text Background Opacity", 0.5),
/** Accessibility's Damage Tilt: how far the camera shakes when the player is hurt. */
DAMAGE_TILT("Damage Tilt", 1.0),
/** Video Settings' Attack Indicator: 0 Off, 1 Crosshair, 2 Hotbar. */
ATTACK_INDICATOR("Attack Indicator", 1.0, 2.0);
private final String label;
private final double defaultValue;
private final double max;
GameOption(String label, double defaultValue) {
this(label, defaultValue, 1.0);
}
GameOption(String label, double defaultValue, double max) {
this.label = label;
this.defaultValue = defaultValue;
this.max = max;
}
/** The largest value: 1 for a slider, the last index for a choice. */
public double max() {
return max;
}
/** What the game's options screen calls it. */
public String label() {
return label;
}
/** The game's default, put back when a module lets go and the player's own value is unknown. */
public double defaultValue() {
return defaultValue;
}
}
@@ -0,0 +1,21 @@
package incari.framework.game;
/**
* A part of the game's own HUD a module can take over ({@code GamePartElement}): the game stops
* drawing it in its place, and the module's HUD element draws it wherever the player puts it.
*/
public enum GamePart {
/** The scoreboard sidebar a server shows on the right. */
SCOREBOARD("Scoreboard");
private final String label;
GamePart(String label) {
this.label = label;
}
/** What the settings screen and the HUD editor call it. */
public String label() {
return label;
}
}
@@ -0,0 +1,39 @@
package incari.framework.game;
/**
* How the client draws entities' hitboxes ({@link Game#overrideHitboxes}): the box each entity is hit
* by, in the world, on this client only. Colors are {@code 0xAARRGGBB}.
*
* @param color the boxes' color
* @param targetColor the box of the entity the crosshair is on; the same as {@code color} for no
* difference
* @param width the lines' width in screen pixels, as the block outline's
* @param show which entities get a box
* @param eyeLine a line round the box at the entity's eye height
* @param lookLine an arrow from the entity's eyes the way it looks
* @param own the player's own box too, in third person
*/
public record Hitboxes(
int color, int targetColor, float width, Show show, boolean eyeLine, boolean lookLine, boolean own) {
/** Which entities get a box. */
public enum Show {
/** Other players only. */
PLAYERS("Players"),
/** Players and mobs: anything with health. */
LIVING("Players and mobs"),
/** Every entity the game draws: items, arrows, boats and the rest too. */
ALL("Everything");
private final String label;
Show(String label) {
this.label = label;
}
/** What the settings screen calls it. */
public String label() {
return label;
}
}
}
@@ -0,0 +1,46 @@
package incari.framework.game;
/**
* An item stack as modules see it: enough to show it and how worn it is. Drawn with {@code
* HudCanvas.item}. Reused by the client: read it during the call that handed it out.
*/
public interface ItemView {
/** Whether there's nothing there. */
boolean isEmpty();
/** How many are in the stack. */
int count();
/** Whether it wears out with use (armor, tools, weapons). */
boolean isDamageable();
/** How much wear it has taken; 0 for new. */
int damage();
/** The wear it can take before it breaks; 0 if it isn't damageable. */
int maxDamage();
/** The item's name in the player's language ("Oak Planks"); its id where there's no game. */
default String name() {
return id();
}
/** The item's id ({@code minecraft:shield}); empty for an empty stack. */
default String id() {
return "";
}
/**
* How much of the item's cooldown is left, 1 just begun to 0 ready: a shield an axe disabled,
* an ender pearl just thrown. 0 if it has none.
*/
default float cooldown() {
return 0;
}
/** Uses left before it breaks: {@code maxDamage() - damage()}. */
default int remaining() {
return maxDamage() - damage();
}
}
@@ -0,0 +1,22 @@
package incari.framework.game;
/** How a structure is mirrored before it's turned ({@link Blocks#transform}). */
public enum Mirror {
/** As built. */
NONE("None"),
/** East and west swap: x runs the other way. */
X("East-west"),
/** North and south swap: z runs the other way. */
Z("North-south");
private final String label;
Mirror(String label) {
this.label = label;
}
/** What the player is shown. */
public String label() {
return label;
}
}
@@ -0,0 +1,49 @@
package incari.framework.game;
/**
* What the client leaves out of the world it draws ({@link Game#overrideNoRender}), on this client
* only: what's hidden is still there, to pick up, hit and collide with. Mostly for frames: a bone
* meal farm's items and sparkles can take a Chromebook to no frames at all.
*
* @param items how items on the ground are drawn
* @param oneCopy a stack on the ground drawn as one item, not as the game's pile of up to five
* @param orbs experience orbs hidden
* @param fallingBlocks falling sand, gravel, anvils and the rest hidden
* @param fireworks firework rockets and their bursts hidden
* @param growth the green sparkles of bone meal and growing crops hidden
* @param breaking the bits of blocks being broken, and the dust of running and landing, hidden
* @param explosions explosions' smoke clouds hidden
* @param allParticles every particle hidden
*/
public record NoRender(
Items items,
boolean oneCopy,
boolean orbs,
boolean fallingBlocks,
boolean fireworks,
boolean growth,
boolean breaking,
boolean explosions,
boolean allParticles) {
/** How items on the ground are drawn. */
public enum Items {
/** As the game draws them, bobbing and spinning. */
SHOWN("Shown"),
/** Lying still: no bobbing or spinning. */
STILL("Still"),
/** Not drawn at all. */
HIDDEN("Hidden");
private final String label;
Items(String label) {
this.label = label;
}
/** What the settings screen calls it. */
public String label() {
return label;
}
}
}
@@ -0,0 +1,8 @@
package incari.framework.game;
/** Where the camera is: the game's three views (F5). */
public enum Perspective {
FIRST_PERSON,
THIRD_PERSON_BACK,
THIRD_PERSON_FRONT
}
@@ -0,0 +1,135 @@
package incari.framework.game;
/**
* The local player as modules see it: where they are and which way they face, what they wear and
* hold, and their effects. Reused by the client and refreshed each time {@link Game#player()} hands
* it out; what it returns is reused too. On the render thread the position and heading are where
* the player is drawn this frame (between ticks), so what follows them moves smoothly.
*/
public interface PlayerView {
/** A player with nothing: no items, no effects. */
PlayerView EMPTY = new PlayerView() {
@Override
public ItemView item(EquipmentSlot slot) {
return NO_ITEM;
}
@Override
public int effectCount() {
return 0;
}
@Override
public EffectView effect(int index) {
throw new IndexOutOfBoundsException(index);
}
@Override
public double x() {
return 0;
}
@Override
public double y() {
return 0;
}
@Override
public double z() {
return 0;
}
@Override
public float heading() {
return 0;
}
@Override
public String dimension() {
return OVERWORLD;
}
@Override
public boolean isDead() {
return false;
}
};
/** The overworld's {@link #dimension()}. */
String OVERWORLD = "minecraft:overworld";
/** The Nether's. */
String NETHER = "minecraft:the_nether";
/** The End's. */
String END = "minecraft:the_end";
/** An empty stack. */
ItemView NO_ITEM = new ItemView() {
@Override
public boolean isEmpty() {
return true;
}
@Override
public int count() {
return 0;
}
@Override
public boolean isDamageable() {
return false;
}
@Override
public int damage() {
return 0;
}
@Override
public int maxDamage() {
return 0;
}
};
/** What's in {@code slot}; {@link ItemView#isEmpty()} if nothing. */
ItemView item(EquipmentSlot slot);
/** How many effects show, as the game's HUD would show them (hidden ones left out). */
int effectCount();
/** The {@code index}th effect, the game's HUD order (longest-lasting first). */
EffectView effect(int index);
/** Where the player's feet are: x, toward the east. */
double x();
/** Their feet's height. */
double y();
/** z, toward the south. */
double z();
/** The compass bearing they face, degrees clockwise from north: 0 north, 90 east, 180 south. */
float heading();
/** The dimension they're in, by the game's id ({@link #OVERWORLD}, {@link #NETHER}, {@link #END}). */
String dimension();
/** Whether they've died and not yet respawned. */
boolean isDead();
/** The biome at their feet, by name in the player's language ("Plains"); empty if unknown. */
default String biome() {
return "";
}
/**
* How many of the item with this id ({@code minecraft:totem_of_undying}) they carry: the
* inventory, both hands and the armor.
*/
default int count(String itemId) {
return 0;
}
}
@@ -0,0 +1,19 @@
package incari.framework.game;
/**
* The client's look as a few colors ({@link Game#applyTheme}): every other shade is made from these.
* Colors are {@code 0xRRGGBB}.
*
* @param accent what's on, chosen or focused
* @param text ordinary text
* @param muted secondary text
* @param panel the panels' and the HUD's glass
* @param panelOpacity the menus' panels, 0 to 100 percent (where they aren't blurred behind)
* @param hudOpacity the HUD's glass, 0 to 100 percent
* @param radius a control's corner radius in GUI units
*/
public record ThemeColors(int accent, int text, int muted, int panel, int panelOpacity, int hudOpacity, int radius) {
/** Frost, the client's own. */
public static final ThemeColors FROST = new ThemeColors(0xA9DCFF, 0xFFFFFF, 0xB4BDC6, 0x242A32, 86, 42, 3);
}
@@ -0,0 +1,46 @@
package incari.framework.game;
import org.jspecify.annotations.Nullable;
/**
* The fonts the client's text can be drawn in (a theme's font): Incari's own, the game's pixel
* font, or one of the open fonts in Incari's pack. A theme's share code keeps the font as its
* {@link #code()}, which never changes.
*/
public enum UiFont {
RED_HAT_DISPLAY(0, "Red Hat Display"),
MINECRAFT(1, "Minecraft"),
INTER(2, "Inter"),
NUNITO(3, "Nunito"),
POPPINS(4, "Poppins"),
JETBRAINS_MONO(5, "JetBrains Mono"),
MICHROMA(6, "Michroma");
private final int code;
private final String label;
UiFont(int code, String label) {
this.code = code;
this.label = label;
}
/** Its number in a share code. */
public int code() {
return code;
}
/** The font numbered {@code code}, or null if this client has none so numbered. */
public static @Nullable UiFont byCode(int code) {
for (UiFont font : values()) {
if (font.code == code) {
return font;
}
}
return null;
}
/** What the settings screen calls it. */
public String label() {
return label;
}
}
@@ -0,0 +1,21 @@
package incari.framework.game;
/** What the sky does, as the client may show it ({@link Game#overrideSky}). */
public enum Weather {
CLEAR("Clear"),
RAIN("Rain"),
THUNDER("Thunder"),
/** Snow wherever it falls, whatever the biome. */
SNOW("Snow");
private final String label;
Weather(String label) {
this.label = label;
}
/** What the settings screen calls it. */
public String label() {
return label;
}
}
@@ -0,0 +1,9 @@
/**
* What modules can read of the game, and the few game options they may hold: the player's
* equipment and effects, the parts of the game's HUD a module can take over. In Incari's terms,
* filled in by {@code :client} (ADR 0050).
*/
@NullMarked
package incari.framework.game;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,116 @@
package incari.framework.hud;
/**
* Which point of the screen a HUD element is placed from. The element's matching corner, edge
* middle or center sits there, moved inward by its offsets, so it stays put in its corner however
* the window or the GUI scale changes.
*/
public enum Anchor {
TOP_LEFT(0, 0, "Top left"),
TOP(1, 0, "Top"),
TOP_RIGHT(2, 0, "Top right"),
LEFT(0, 1, "Left"),
CENTER(1, 1, "Center"),
RIGHT(2, 1, "Right"),
BOTTOM_LEFT(0, 2, "Bottom left"),
BOTTOM(1, 2, "Bottom"),
BOTTOM_RIGHT(2, 2, "Bottom right");
/** 0 left, 1 center, 2 right. */
private final int column;
/** 0 top, 1 middle, 2 bottom. */
private final int row;
private final String label;
Anchor(int column, int row, String label) {
this.column = column;
this.row = row;
this.label = label;
}
/** What the settings screen calls it. */
public String label() {
return label;
}
/** Across the screen: 0 left, 1 the middle, 2 right. */
public int column() {
return column;
}
/** Down the screen: 0 top, 1 the middle, 2 bottom. */
public int row() {
return row;
}
/**
* Where an element starts across the screen.
*
* @param offset the element's offset: inward from a side, rightward from the middle
* @param size the element's width, scaled
* @param screen the screen's width
* @return the element's left edge, kept on screen
*/
public int x(int offset, int size, int screen) {
return place(column, offset, size, screen);
}
/** Where an element starts down the screen; {@link #x}'s rules, top to bottom. */
public int y(int offset, int size, int screen) {
return place(row, offset, size, screen);
}
/** The offset across that puts an element's left edge at {@code start}: {@link #x}'s inverse. */
public int offsetX(int start, int size, int screen) {
return offset(column, start, size, screen);
}
/** The offset down that puts an element's top edge at {@code start}: {@link #y}'s inverse. */
public int offsetY(int start, int size, int screen) {
return offset(row, start, size, screen);
}
/**
* The anchor for an element placed at {@code x, y}: the screen's corner, edge or middle in
* whose third its middle lies, so it keeps its place from the nearest side as the window
* changes.
*/
public static Anchor nearest(int x, int y, int width, int height, int screenWidth, int screenHeight) {
int column = third(x * 2 + width, screenWidth * 2);
int row = third(y * 2 + height, screenHeight * 2);
for (Anchor anchor : values()) {
if (anchor.column == column && anchor.row == row) {
return anchor;
}
}
throw new AssertionError("No anchor at " + column + ", " + row);
}
/** Which third of {@code size} {@code at} is in: 0, 1 or 2. */
private static int third(int at, int size) {
if (size <= 0) {
return 0;
}
return Math.max(0, Math.min(2, at * 3 / size));
}
private static int offset(int third, int start, int size, int screen) {
return switch (third) {
case 0 -> start;
case 1 -> start - (screen - size) / 2;
default -> screen - size - start;
};
}
private static int place(int third, int offset, int size, int screen) {
int start =
switch (third) {
case 0 -> offset;
case 1 -> (screen - size) / 2 + offset;
default -> screen - size - offset;
};
// An element bigger than the screen stays at its start rather than off the far side.
return Math.max(0, Math.min(start, screen - size));
}
}
@@ -0,0 +1,40 @@
package incari.framework.hud;
/**
* Blocks a module wants drawn in the world as see-through ghosts ({@link WorldCanvas#ghosts}): what
* a schematic still needs built. The client meshes them 16 blocks a side at a time (a section, as
* the world's own: {@code x >> 4}) and keeps each mesh until {@link #revision} says it changed, so
* a frame costs only drawing. Render thread.
*/
public interface BlockGhosts {
/** The box the ghosts are in, in world blocks: the lowest corner, x. */
int minX();
/** The lowest corner's y. */
int minY();
/** The lowest corner's z. */
int minZ();
/** The highest corner, one past the last block: x. */
int maxX();
/** One past the last block's y. */
int maxY();
/** One past the last block's z. */
int maxZ();
/**
* The {@link incari.framework.game.Blocks} state to draw a ghost of at {@code x, y, z};
* {@link incari.framework.game.Blocks#AIR} for none. Called while a section is meshed.
*/
int ghostAt(int x, int y, int z);
/**
* A number that changes whenever what {@link #ghostAt} gives in the section {@code sectionX,
* sectionY, sectionZ} might have: the section is meshed again when it does.
*/
long revision(int sectionX, int sectionY, int sectionZ);
}
@@ -0,0 +1,47 @@
package incari.framework.hud;
import incari.framework.game.GamePart;
/**
* A part of the game's own HUD, taken over by a module (Custom Scoreboard's sidebar): while the
* module is on, the game no longer draws the part in its place ({@code ModuleSystem.holds}), and
* this element draws it where the player puts it, at the scale they choose.
*/
public class GamePartElement extends HudElement {
private final GamePart part;
/**
* @param part what it draws
* @param id the config key, unique within the module
* @param anchor where it goes by default
* @param offsetX how far in from the anchor by default
* @param offsetY how far in from the anchor by default
*/
public GamePartElement(GamePart part, String id, Anchor anchor, int offsetX, int offsetY) {
super(id, part.label(), anchor, offsetX, offsetY);
this.part = part;
}
/** What it draws. */
public final GamePart part() {
return part;
}
@Override
public int width(HudCanvas canvas) {
return canvas.partWidth(part);
}
@Override
public int height(HudCanvas canvas) {
return canvas.partHeight(part);
}
@Override
public void draw(HudCanvas canvas) {
if (canvas.hasPart(part)) {
canvas.part(part, 0, 0);
}
}
}
@@ -0,0 +1,128 @@
package incari.framework.hud;
import incari.framework.game.EffectView;
import incari.framework.game.GamePart;
import incari.framework.game.ItemView;
/**
* What a HUD element draws with, in GUI units (the game's scaled pixels). The client implements it
* over the game's GUI and its theme; elements draw at their own origin, already placed and scaled.
*
* <p>Render thread, during the HUD's extraction only. In the browser the HUD is drawn into a
* texture a few dozen times a second and reused in between (ADR 0030), so an element is drawn
* at most that often: draw from current state, never count frames here.
*/
public interface HudCanvas {
/** The screen's width in GUI units. */
int screenWidth();
/** The screen's height in GUI units. */
int screenHeight();
/**
* Whether the HUD editor is drawing: an element with nothing to show now draws a sample
* instead (Toggle Sprint's line while nothing is latched), so the player can see where it goes.
*/
default boolean editing() {
return false;
}
/** How wide {@code text} is in the HUD's font. */
int textWidth(String text);
/** A line of text's height in the HUD's font. */
int lineHeight();
/** Draws {@code text} with its top left at {@code x, y}, in the theme's color for {@code tone}. */
void text(String text, int x, int y, Tone tone);
/** Draws {@code text} in a color the player chose, {@code 0xAARRGGBB}. */
void text(String text, int x, int y, int argb);
/** Fills a rectangle in the theme's color for {@code tone}. */
void fill(int x, int y, int width, int height, Tone tone);
/** Fills a rectangle in a color the player chose, {@code 0xAARRGGBB}. */
void fill(int x, int y, int width, int height, int argb);
/**
* Draws {@code item}'s icon, 16 by 16, with its top left at {@code x, y}; with {@code
* decorations}, the game's durability bar and stack count on it too. Nothing for an empty item.
*/
void item(ItemView item, int x, int y, boolean decorations);
/** Draws {@code effect}'s icon, 18 by 18, with its top left at {@code x, y}. */
void effect(EffectView effect, int x, int y);
/**
* Whether the game has {@code part} to show now (a server's scoreboard, say). In the HUD editor
* there's always one: a sample, if the game has none.
*/
boolean hasPart(GamePart part);
/** How wide {@code part} is as the game draws it, in GUI units; 0 if there's none. */
int partWidth(GamePart part);
/** How tall {@code part} is as the game draws it; 0 if there's none. */
int partHeight(GamePart part);
/** Draws the game's {@code part} with its top left at {@code x, y}; nothing if there's none. */
void part(GamePart part, int x, int y);
/**
* Draws {@code shape} centred on {@code centerX, centerY}, {@code size} GUI units across, turned
* {@code rotation} degrees clockwise, in the theme's color for {@code tone}, with a thin dark rim.
*/
void shape(Shape shape, float centerX, float centerY, float size, float rotation, Tone tone);
/** {@link #shape(Shape, float, float, float, float, Tone)} in a color the player chose. */
void shape(Shape shape, float centerX, float centerY, float size, float rotation, int argb);
/** Fills a circle, smooth at any size, in the theme's color for {@code tone}. */
void disc(float centerX, float centerY, float radius, Tone tone);
/** Draws a circle's outline {@code width} GUI units thick, just inside {@code radius}. */
void ring(float centerX, float centerY, float radius, float width, Tone tone);
/** {@link #disc(float, float, float, Tone)} in a color the player chose. */
void disc(float centerX, float centerY, float radius, int argb);
/** {@link #ring(float, float, float, float, Tone)} in a color the player chose. */
void ring(float centerX, float centerY, float radius, float width, int argb);
/**
* Draws the part of a circle's outline from straight up, {@code fraction} of the way round
* clockwise (a cooldown filling), {@code width} thick just inside {@code radius}.
*/
void arc(float centerX, float centerY, float radius, float width, float fraction, int argb);
/** {@link #arc(float, float, float, float, float, int)} in the theme's color for {@code tone}. */
void arc(float centerX, float centerY, float radius, float width, float fraction, Tone tone);
/**
* Draws the loaded world around a point as seen from above (the minimap): {@code size} GUI units
* across with its top left at {@code x, y}, a circle if {@code round}, else a square. Each block
* is its top's color, shaded by the slope; where nothing is loaded is left clear.
*
* <p>Up on the map faces the compass bearing {@code rotation} (degrees clockwise from north: 0
* is north up, 90 east up). North is toward the game's −z, east toward +x. Only what's drawn is
* kept up to date, so a map nobody draws costs nothing.
*
* @param centerX the world x at the map's middle
* @param centerZ the world z at the map's middle
* @param blocksAcross how many blocks the map's width shows
*/
void terrain(
int x, int y, int size, boolean round, double centerX, double centerZ, float blocksAcross, float rotation);
/**
* The framework's, around each element: moves the origin to {@code x, y} and scales what follows
* by {@code scale}, until {@link #pop()}. Elements may use it too, for what they place between
* whole GUI units (a marker following the world).
*/
void push(float x, float y, float scale);
/** The framework's: undoes the last {@link #push}. */
void pop();
}
@@ -0,0 +1,217 @@
package incari.framework.hud;
import incari.framework.setting.ChoiceSetting;
import incari.framework.setting.FloatSetting;
import incari.framework.setting.Ids;
import incari.framework.setting.IntSetting;
import incari.framework.setting.Settings;
/**
* Something a module draws on the HUD: its size, how to draw it, and where it goes. The placement
* is settings of its own (an anchor, offsets from it, a scale), saved with the profile; the anchor
* and scale show in the module's settings screen, and the HUD editor drags it about and resizes it
* ({@link #place}).
*
* <p>Drawn only while its module is enabled and {@link #isVisible()} holds; in the HUD editor
* while {@link #isPlaceable()} does, with a sample if there's nothing to show ({@link
* HudCanvas#editing()}). Render thread.
*/
public abstract class HudElement {
private final String id;
private final String name;
private final Settings settings = new Settings();
private final ChoiceSetting<Anchor> anchor;
private final IntSetting offsetX;
private final IntSetting offsetY;
private final FloatSetting scale;
/** Where it was last drawn on the game's HUD (not the HUD editor's): left, top, width, height. */
private int drawnX;
private int drawnY;
private int drawnWidth;
private int drawnHeight;
/** Whether it showed the last time the game's HUD drew it. */
private boolean drawn;
/**
* @param id the config key, unique within the module
* @param name what the settings screen and the HUD editor call it
* @param anchor where it goes by default
* @param offsetX how far in from the anchor by default, in GUI units
* @param offsetY how far in from the anchor by default
*/
protected HudElement(String id, String name, Anchor anchor, int offsetX, int offsetY) {
this.id = Ids.require(id);
this.name = name;
this.anchor = settings.choice("anchor", "Position", Anchor.values(), anchor, Anchor::label);
this.offsetX =
settings.integer("x", "Offset across", -4096, 4096, offsetX).hidden();
this.offsetY =
settings.integer("y", "Offset down", -4096, 4096, offsetY).hidden();
this.scale = settings.decimal("scale", "Scale", 0.5F, 3.0F, 0.25F, 1.0F).formattedAs(HudElement::formatScale);
}
/** The config key. */
public final String id() {
return id;
}
/** What the settings screen calls it. */
public final String name() {
return name;
}
/** Its placement settings, and any of its own a subclass adds. */
public final Settings settings() {
return settings;
}
/** Where it's placed from. */
public final ChoiceSetting<Anchor> anchor() {
return anchor;
}
/** How far in from the anchor across, in GUI units. */
public final IntSetting offsetX() {
return offsetX;
}
/** How far in from the anchor down. */
public final IntSetting offsetY() {
return offsetY;
}
/** How much bigger than the GUI scale it's drawn. */
public final FloatSetting scale() {
return scale;
}
/** Whether it has anything to show now; drawn only then. */
public boolean isVisible() {
return true;
}
/**
* Whether the HUD editor shows it, its module being on: false only when a setting of its own
* hides it for good (Toggle Sprint's status with Show status off).
*/
public boolean isPlaceable() {
return true;
}
/**
* Whether it's drawn every frame rather than with the rest of the HUD, which the browser draws
* only a few dozen times a second (ADR 0030). True for what follows the camera (a turning
* minimap), which would otherwise lag. Live elements draw under the game's HUD, with the
* crosshair; keep them cheap.
*/
public boolean isLive() {
return false;
}
/** Its width unscaled, in GUI units. */
public abstract int width(HudCanvas canvas);
/** Its height unscaled. */
public abstract int height(HudCanvas canvas);
/** Draws it with its top left at 0, 0, unscaled. Don't allocate per call where avoidable. */
public abstract void draw(HudCanvas canvas);
/** "1x", "1.25x", "2.5x". */
private static String formatScale(double value) {
long hundredths = Math.round(value * 100);
String text = hundredths / 100 + "." + (hundredths % 100 < 10 ? "0" : "") + hundredths % 100;
while (text.endsWith("0")) {
text = text.substring(0, text.length() - 1);
}
if (text.endsWith(".")) {
text = text.substring(0, text.length() - 1);
}
return text + "x";
}
/**
* Where it's drawn on {@code canvas}, scaled: {@code out} gets its left, top, width and height
* in GUI units. Allocates nothing.
*/
public final void bounds(HudCanvas canvas, int[] out) {
float s = scale.get();
int w = Math.round(width(canvas) * s);
int h = Math.round(height(canvas) * s);
Anchor a = anchor.get();
out[0] = a.x(offsetX.get(), w, canvas.screenWidth());
out[1] = a.y(offsetY.get(), h, canvas.screenHeight());
out[2] = w;
out[3] = h;
}
/**
* The HUD editor's: puts it with its top left at {@code x, y} on a screen of this size, its
* size {@code width} by {@code height} scaled. The anchor becomes the nearest one ({@link
* Anchor#nearest}) and the offsets are measured from it.
*/
public final void place(int x, int y, int width, int height, int screenWidth, int screenHeight) {
Anchor a = Anchor.nearest(x, y, width, height, screenWidth, screenHeight);
anchor.set(a);
offsetX.set(a.offsetX(x, width, screenWidth));
offsetY.set(a.offsetY(y, height, screenHeight));
}
/**
* Where it was last drawn on the game's HUD, into {@code out} as left, top, width and height in
* GUI units; false if it showed nothing then. The module system's, to keep the game's own HUD
* clear of it ({@link incari.framework.ModuleSystem#effectIconsShift}). Allocates nothing.
*/
public final boolean lastDrawn(int[] out) {
if (!drawn) {
return false;
}
out[0] = drawnX;
out[1] = drawnY;
out[2] = drawnWidth;
out[3] = drawnHeight;
return true;
}
/** Back where its module put it, at its default size. */
public final void resetPlacement() {
anchor.reset();
offsetX.reset();
offsetY.reset();
scale.reset();
}
/** The module system's: places, scales and draws it, if visible (placeable in the editor). */
public final void render(HudCanvas canvas) {
boolean editing = canvas.editing();
if (editing ? !isPlaceable() : !isVisible()) {
if (!editing) {
drawn = false;
}
return;
}
float s = scale.get();
int w = Math.round(width(canvas) * s);
int h = Math.round(height(canvas) * s);
Anchor a = anchor.get();
int x = a.x(offsetX.get(), w, canvas.screenWidth());
int y = a.y(offsetY.get(), h, canvas.screenHeight());
if (!editing) {
drawn = w > 0 && h > 0;
drawnX = x;
drawnY = y;
drawnWidth = w;
drawnHeight = h;
}
canvas.push(x, y, s);
try {
draw(canvas);
} finally {
canvas.pop();
}
}
}
@@ -0,0 +1,35 @@
package incari.framework.hud;
import java.util.List;
/**
* A small filled shape the canvas draws smooth at any size ({@link HudCanvas#shape}): a waypoint's
* icon, a marker on the minimap, the player's arrow. Each is drawn with a thin dark rim so it reads
* over any terrain or sky.
*/
public enum Shape {
CIRCLE("Circle"),
SQUARE("Square"),
DIAMOND("Diamond"),
TRIANGLE("Triangle"),
STAR("Star"),
HEART("Heart"),
HEXAGON("Hexagon"),
CROSS("Cross"),
/** A pointer, its tip up at rotation 0: the player on the minimap, an arrow to what's off screen. */
ARROW("Arrow");
/** The shapes a waypoint can take, in the order the editor offers them. */
public static final List<Shape> MARKERS = List.of(CIRCLE, SQUARE, DIAMOND, TRIANGLE, STAR, HEART, HEXAGON, CROSS);
private final String label;
Shape(String label) {
this.label = label;
}
/** What the editor calls it. */
public String label() {
return label;
}
}
@@ -0,0 +1,104 @@
package incari.framework.hud;
import incari.framework.setting.BooleanSetting;
import incari.framework.setting.ColorSetting;
import org.jspecify.annotations.Nullable;
/**
* A HUD element that's one line of text, on the theme's glass unless the player turns the
* background off: FPS, CPS, reach. The player may color the text themselves; otherwise it's drawn
* in the element's {@link #tone()}.
*
* <p>A subclass hands out its text from {@link #text}, made again only when what it says changes
* (the HUD asks a few dozen times a second).
*/
public abstract class TextElement extends HudElement {
/** Space between the glass's edge and the text, across. */
public static final int PAD_X = 4;
/** Space between the glass's edge and the text, down. */
public static final int PAD_Y = 3;
private final BooleanSetting background;
private final BooleanSetting customColor;
private final ColorSetting color;
/** As {@link HudElement#HudElement}. */
@SuppressWarnings("this-escape") // settings() is final: it hands out the list, nothing overridable runs.
protected TextElement(String id, String name, Anchor anchor, int offsetX, int offsetY) {
super(id, name, anchor, offsetX, offsetY);
background = settings().bool("background", "Background", true).describedAs("Draws a panel behind the text.");
customColor = settings()
.bool("custom-color", "Custom color", false)
.describedAs("Off: the text takes the theme's colors.");
color = settings().color("color", "Text color", 0xFFFFFF).visibleWhen(customColor::get);
}
/**
* What it says now, or null for nothing (it's then hidden). In the HUD editor ({@link
* HudCanvas#editing()}) a sample if there's nothing to say.
*/
protected abstract @Nullable String text(HudCanvas canvas);
/** The tone its text takes when the player hasn't colored it: {@link Tone#TEXT}. */
protected Tone tone() {
return Tone.TEXT;
}
/**
* The widest text it's likely to say ("000 FPS"), so its width holds still as the numbers
* change; null to follow the text.
*/
protected @Nullable String widest() {
return null;
}
/** Whether the glass is drawn behind the text. */
protected final boolean hasBackground() {
return background.get();
}
@Override
public int width(HudCanvas canvas) {
String text = text(canvas);
if (text == null) {
return 0;
}
int width = canvas.textWidth(text);
String widest = widest();
if (widest != null) {
width = Math.max(width, canvas.textWidth(widest));
}
return width + (background.get() ? PAD_X * 2 : 0);
}
@Override
public int height(HudCanvas canvas) {
// The font's line height has a pixel of space below the letters: one pad less below.
return canvas.lineHeight() + (background.get() ? PAD_Y * 2 - 1 : 0);
}
@Override
public void draw(HudCanvas canvas) {
String text = text(canvas);
if (text == null) {
return;
}
int width = width(canvas);
int x = 0;
int y = 0;
if (background.get()) {
canvas.fill(0, 0, width, height(canvas), Tone.BACKGROUND);
x = PAD_X;
y = PAD_Y;
}
// Centered in the width {@link #widest} holds.
x += (width - (background.get() ? PAD_X * 2 : 0) - canvas.textWidth(text)) / 2;
if (customColor.get()) {
canvas.text(text, x, y, color.get());
} else {
canvas.text(text, x, y, tone());
}
}
}
@@ -0,0 +1,27 @@
package incari.framework.hud;
/**
* What a color is for, not which color it is. HUD elements draw in tones and the client's theme
* decides the colors, so restyling the client restyles every module's HUD with it. A color the
* player picked (a {@code ColorSetting}) is drawn as given instead.
*/
public enum Tone {
/** Ordinary text. */
TEXT,
/** Secondary text: labels, units, what's off. */
MUTED,
/** The client's accent: what's on, what's chosen. */
ACCENT,
/** Good news: full, ready, safe. */
POSITIVE,
/** Worth a look: running low. */
WARNING,
/** Bad news: empty, broken, in danger. */
NEGATIVE,
/** A panel behind an element's text. */
BACKGROUND,
/** A panel's edge, catching the light: a frame around a map. */
EDGE,
/** Text on an {@link #ACCENT} fill: a pressed key's name. */
ON_ACCENT
}
@@ -0,0 +1,39 @@
package incari.framework.hud;
/**
* What {@link incari.framework.event.Events#WORLD}'s listeners draw into the world itself, with
* its blocks in front of and behind it. Render thread, while the frame's world is put together.
*/
public interface WorldCanvas {
/**
* A beacon's beam in {@code rgb} up from {@code x, y, z} (the block's corner, as a beacon's
* block position) into the sky. A beam farther than the world is drawn is moved in along the
* line of sight to where it's drawn, looking the same: the player sees it from any distance.
*/
void beam(int x, int y, int z, int rgb);
/**
* {@code ghosts}' blocks as the game draws them, see-through at {@code alpha} (0 to 255) and
* fully lit, within {@code range} blocks of the camera. The client keeps each section's mesh
* between frames ({@link BlockGhosts#revision}) and meshes a few changed sections a frame, nearest
* first; hand it the same object each frame.
*/
void ghosts(BlockGhosts ghosts, int alpha, int range);
/**
* A box's edges in {@code argb}, its faces filled in {@code fillArgb} (0 for none), from block
* corner {@code minX, minY, minZ} to {@code maxX, maxY, maxZ} (one past the last block). Behind
* blocks it's hidden, as the world's other things.
*/
void box(int minX, int minY, int minZ, int maxX, int maxY, int maxZ, int argb, int fillArgb);
/** The camera's position in the world this frame: x. */
double cameraX();
/** The camera's y. */
double cameraY();
/** The camera's z. */
double cameraZ();
}
@@ -0,0 +1,28 @@
package incari.framework.hud;
/**
* The canvas for {@link incari.framework.event.Events#OVERLAY}: the HUD's canvas, drawn every
* frame over the world (under the game's HUD), with a way to find where a point in the world shows
* on screen. What follows the world (a waypoint's label) is drawn here, so it keeps up with the
* camera at any frame rate. Render thread.
*/
public interface WorldOverlay extends HudCanvas {
/**
* Where the point {@code x, y, z} in the world shows on screen this frame: {@code out[0]} and
* {@code out[1]} get its position in GUI units, {@code out[2]} its distance from the camera in
* blocks. False if it's behind the camera: then {@code out[0], out[1]} are far off screen the
* way to turn to it from the screen's middle (straight down for straight behind), for an arrow
* at the screen's edge.
*/
boolean project(double x, double y, double z, float[] out);
/** The camera's position in the world this frame: x. */
double cameraX();
/** The camera's y. */
double cameraY();
/** The camera's z. */
double cameraZ();
}
@@ -0,0 +1,5 @@
/** HUD elements: what modules draw on the HUD, where, and the canvas they draw with. */
@NullMarked
package incari.framework.hud;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,25 @@
package incari.framework.online;
import java.util.List;
/**
* A player in the world who is signed in to an Incari account, as the service describes them
* (ADR 0058). The service never says which account it is: only an id for this server.
*
* @param pid the account's id on this server only: the same account has another on another server
* @param friend whether they're the player's friend
* @param cosmetics the ids of the cosmetics they wear, for the cosmetics ADR to draw
* @param badge whether they let others see they use Incari: Incari's badge beside their name (ADR
* 0062)
*/
public record IncariPlayer(String pid, boolean friend, List<String> cosmetics, boolean badge) {
public IncariPlayer {
cosmetics = List.copyOf(cosmetics);
}
/** One who shows the badge, as every account did before ADR 0062. */
public IncariPlayer(String pid, boolean friend, List<String> cosmetics) {
this(pid, friend, cosmetics, true);
}
}
@@ -0,0 +1,76 @@
package incari.framework.online;
import java.util.UUID;
import org.jspecify.annotations.Nullable;
/**
* The player's Incari account and the Incari players around them (ADR 0058), as features see it.
* Accounts are optional: with none, or with the service unreachable, everything reads as nobody
* signed in and nobody an Incari player, and the game carries on.
*
* <p>Game thread. Every method is a field read or a map lookup; none waits on the service.
*/
public interface Online {
/** Where the client stands with the service. */
enum Status {
/** This build has no service to talk to (no URL set). */
OFF,
/** Opening the connection, or waiting to try again after it failed. */
CONNECTING,
/** Connected, and not signed in. */
SIGNED_OUT,
/** Connected and signed in: {@link #accountName} is the account's. */
SIGNED_IN,
/** The service no longer speaks this client's protocol; nothing more is tried until an update. */
UPDATE_NEEDED
}
/** No service at all: what a module system without one sees. */
Online NONE = new Online() {
@Override
public Status status() {
return Status.OFF;
}
@Override
public @Nullable String accountName() {
return null;
}
@Override
public @Nullable IncariPlayer player(UUID id) {
return null;
}
@Override
public long revision() {
return 0;
}
};
/** Where the client stands with the service now. */
Status status();
/** Whether the player is signed in to an Incari account. */
default boolean signedIn() {
return status() == Status.SIGNED_IN;
}
/**
* The signed-in account's Incari username; while reconnecting, the one last signed in on this
* device. Null when signed out.
*/
@Nullable
String accountName();
/**
* The player with this UUID in the current world, if the service says they're an Incari player
* here; null for anyone else, outside a world, or while not signed in.
*/
@Nullable
IncariPlayer player(UUID id);
/** A number that goes up whenever anything here changes: a screen or module compares it to refresh. */
long revision();
}
@@ -0,0 +1,8 @@
/**
* What the client knows of Incari's online service (ADR 0058): whether the player is signed in to an
* Incari account, and which players in the world are Incari players. No network or game types.
*/
@NullMarked
package incari.framework.online;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,9 @@
/**
* The module framework (ADR 0046): {@link incari.framework.Module}, the base of every client
* feature, and {@link incari.framework.ModuleSystem}, which holds them. No game types: features see
* the game only through this package and its subpackages.
*/
@NullMarked
package incari.framework;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,52 @@
package incari.framework.setting;
/**
* A button in the settings screen that does something rather than holding a value: Waypoints'
* "Manage waypoints". Nothing is stored; the profile leaves it out.
*/
public final class ActionSetting extends Setting<ActionSetting> {
private final String label;
private final Runnable action;
/**
* @param id unique among the settings, like any setting's
* @param name what the settings screen calls the row
* @param label what the button says
* @param action what pressing it does; game thread
*/
public ActionSetting(String id, String name, String label, Runnable action) {
super(id, name);
this.label = label;
this.action = action;
}
/** What the button says. */
public String label() {
return label;
}
/** Presses the button. */
public void run() {
action.run();
}
/** Always: there's no value. */
@Override
public boolean isDefault() {
return true;
}
@Override
public void reset() {}
@Override
public <R> R accept(SettingVisitor<R> visitor) {
return visitor.visit(this);
}
@Override
protected ActionSetting self() {
return this;
}
}
@@ -0,0 +1,62 @@
package incari.framework.setting;
/** An on/off setting. Read with {@link #get()}: no boxing, fine on hot paths. */
public final class BooleanSetting extends Setting<BooleanSetting> {
private final boolean defaultValue;
private boolean value;
/**
* @param id the config key
* @param name what the settings screen calls it
* @param defaultValue the value before the player changes it
*/
public BooleanSetting(String id, String name, boolean defaultValue) {
super(id, name);
this.defaultValue = defaultValue;
this.value = defaultValue;
}
/** The value. */
public boolean get() {
return value;
}
/** Sets the value; telling listeners only if it changed. */
public void set(boolean value) {
if (this.value != value) {
this.value = value;
changed();
}
}
/** Flips the value. */
public void toggle() {
set(!value);
}
/** The value before the player changes it. */
public boolean defaultValue() {
return defaultValue;
}
@Override
public boolean isDefault() {
return value == defaultValue;
}
@Override
public void reset() {
set(defaultValue);
}
@Override
public <R> R accept(SettingVisitor<R> visitor) {
return visitor.visit(this);
}
@Override
protected BooleanSetting self() {
return this;
}
}
@@ -0,0 +1,114 @@
package incari.framework.setting;
import java.util.List;
import java.util.Locale;
import java.util.function.Function;
import org.jspecify.annotations.Nullable;
/**
* One of an enum's constants. Stored by the constant's name in lowercase, so reordering the enum
* keeps what players chose; renaming a constant doesn't.
*
* @param <E> the enum
*/
public final class ChoiceSetting<E extends Enum<E>> extends Setting<ChoiceSetting<E>> {
private final List<E> values;
private final E defaultValue;
private final Function<E, String> label;
private E value;
/**
* @param id the config key
* @param name what the settings screen calls it
* @param values every choice, in the order the settings screen cycles through them
* @param defaultValue the value before the player changes it, one of {@code values}
* @param label what the settings screen calls each choice
*/
public ChoiceSetting(String id, String name, E[] values, E defaultValue, Function<E, String> label) {
super(id, name);
if (values.length == 0) {
throw new IllegalArgumentException(id + ": no choices");
}
this.values = List.of(values);
if (!this.values.contains(defaultValue)) {
throw new IllegalArgumentException(id + ": default " + defaultValue + " isn't a choice");
}
this.defaultValue = defaultValue;
this.value = defaultValue;
this.label = label;
}
/** The value. */
public E get() {
return value;
}
/** Sets the value; one that isn't a choice is ignored. */
public void set(E value) {
if (this.value != value && values.contains(value)) {
this.value = value;
changed();
}
}
/** Moves to the next choice, from the last back to the first. */
public void next() {
set(values.get((values.indexOf(value) + 1) % values.size()));
}
/** Every choice, in order. */
public List<E> values() {
return values;
}
/** The value before the player changes it. */
public E defaultValue() {
return defaultValue;
}
/** What the settings screen calls {@code choice}. */
public String label(E choice) {
return label.apply(choice);
}
/** What the settings screen calls the current value. */
public String label() {
return label.apply(value);
}
/** The config's name for the current value. */
public String key() {
return value.name().toLowerCase(Locale.ROOT);
}
/** The choice the config's {@code key} names, or null if none does. */
public @Nullable E fromKey(String key) {
for (E choice : values) {
if (choice.name().toLowerCase(Locale.ROOT).equals(key)) {
return choice;
}
}
return null;
}
@Override
public boolean isDefault() {
return value == defaultValue;
}
@Override
public void reset() {
set(defaultValue);
}
@Override
public <R> R accept(SettingVisitor<R> visitor) {
return visitor.visit(this);
}
@Override
protected ChoiceSetting<E> self() {
return this;
}
}
@@ -0,0 +1,74 @@
package incari.framework.setting;
/**
* A color as {@code 0xAARRGGBB}. Without alpha ({@link #opaque}), the alpha byte is always
* {@code FF}.
*/
public final class ColorSetting extends Setting<ColorSetting> {
private final int defaultValue;
private final boolean alpha;
private int value;
/**
* @param id the config key
* @param name what the settings screen calls it
* @param defaultValue {@code 0xAARRGGBB}
* @param alpha whether the player may make it see-through
*/
public ColorSetting(String id, String name, int defaultValue, boolean alpha) {
super(id, name);
this.alpha = alpha;
this.defaultValue = alpha ? defaultValue : defaultValue | 0xFF000000;
this.value = this.defaultValue;
}
/** An opaque color setting. */
public static ColorSetting opaque(String id, String name, int rgb) {
return new ColorSetting(id, name, rgb, false);
}
/** The color, {@code 0xAARRGGBB}. */
public int get() {
return value;
}
/** Sets the color; an opaque setting keeps its alpha at {@code FF}. */
public void set(int argb) {
int kept = alpha ? argb : argb | 0xFF000000;
if (value != kept) {
value = kept;
changed();
}
}
/** Whether the alpha byte is the player's to set. */
public boolean hasAlpha() {
return alpha;
}
/** The color before the player changes it. */
public int defaultValue() {
return defaultValue;
}
@Override
public boolean isDefault() {
return value == defaultValue;
}
@Override
public void reset() {
set(defaultValue);
}
@Override
public <R> R accept(SettingVisitor<R> visitor) {
return visitor.visit(this);
}
@Override
protected ColorSetting self() {
return this;
}
}
@@ -0,0 +1,135 @@
package incari.framework.setting;
import java.util.function.DoubleFunction;
/**
* A decimal number between a minimum and a maximum, in steps (a scale from 0.5 to 2 in steps of
* 0.1, say). Set values are clamped and rounded to the nearest step from the minimum.
*/
public final class FloatSetting extends Setting<FloatSetting> {
private final float min;
private final float max;
private final float step;
private final float defaultValue;
private float value;
private DoubleFunction<String> format;
/**
* @param id the config key
* @param name what the settings screen calls it
* @param min the smallest value
* @param max the largest value
* @param step the spacing of the values in between; positive
* @param defaultValue the value before the player changes it, in range
*/
public FloatSetting(String id, String name, float min, float max, float step, float defaultValue) {
super(id, name);
if (!(min <= max) || !(step > 0) || !(defaultValue >= min && defaultValue <= max)) {
throw new IllegalArgumentException(
id + ": default " + defaultValue + " outside " + min + ".." + max + " or step " + step);
}
this.min = min;
this.max = max;
this.step = step;
this.defaultValue = defaultValue;
this.value = defaultValue;
int decimals = decimals(step);
this.format = v -> trim(v, decimals);
}
/** The value. */
public float get() {
return value;
}
/** Sets the value, clamped into range and rounded to a step. NaN is ignored. */
public void set(float value) {
if (Float.isNaN(value)) {
return;
}
float stepped = min + Math.round((value - min) / step) * step;
float clamped = Math.max(min, Math.min(max, stepped));
if (this.value != clamped) {
this.value = clamped;
changed();
}
}
/** The smallest value. */
public float min() {
return min;
}
/** The largest value. */
public float max() {
return max;
}
/** The spacing of the values. */
public float step() {
return step;
}
/** The value before the player changes it. */
public float defaultValue() {
return defaultValue;
}
/** How the settings screen writes a value ("1.5x", say); as many decimals as the step by default. */
public FloatSetting formattedAs(DoubleFunction<String> format) {
this.format = format;
return this;
}
/** {@code value} as the settings screen writes it. */
public String format(float value) {
return format.apply(value);
}
@Override
public boolean isDefault() {
return value == defaultValue;
}
@Override
public void reset() {
set(defaultValue);
}
@Override
public <R> R accept(SettingVisitor<R> visitor) {
return visitor.visit(this);
}
@Override
protected FloatSetting self() {
return this;
}
/** How many decimals a step needs: 0.25 needs 2, 0.1 needs 1, 5 needs none. */
static int decimals(float step) {
for (int decimals = 0; decimals < 4; decimals++) {
double scaled = step * Math.pow(10, decimals);
if (Math.abs(scaled - Math.rint(scaled)) < 1e-4) {
return decimals;
}
}
return 4;
}
/** Writes {@code value} with {@code decimals} places (no locale: the screen's digits are ASCII). */
static String trim(double value, int decimals) {
long scale = (long) Math.pow(10, decimals);
long rounded = Math.round(Math.abs(value) * scale);
String sign = value < 0 && rounded != 0 ? "-" : "";
if (decimals == 0) {
return sign + rounded;
}
StringBuilder fraction = new StringBuilder(Long.toString(rounded % scale));
while (fraction.length() < decimals) {
fraction.insert(0, '0');
}
return sign + rounded / scale + "." + fraction;
}
}
@@ -0,0 +1,98 @@
package incari.framework.setting;
import java.util.Arrays;
/**
* A square of cells, each on or off: a crosshair drawn pixel by pixel. The settings screen edits it
* in a grid of its own; the profile writes it as one hex number a row.
*/
public final class GridSetting extends Setting<GridSetting> {
/** The largest side: a row fits a {@code long}. */
public static final int MAX_SIZE = 63;
private final int size;
private final long[] defaultRows;
private final long[] rows;
/**
* @param id the config key
* @param name what the settings screen calls it
* @param size cells a side, at most {@link #MAX_SIZE}
* @param defaultRows each row's cells as bits, bit 0 the leftmost; copied
*/
public GridSetting(String id, String name, int size, long[] defaultRows) {
super(id, name);
if (size < 1 || size > MAX_SIZE || defaultRows.length != size) {
throw new IllegalArgumentException(id + ": a grid of " + size + " with " + defaultRows.length + " rows");
}
this.size = size;
this.defaultRows = defaultRows.clone();
this.rows = defaultRows.clone();
}
/** Cells a side. */
public int size() {
return size;
}
/** Whether the cell {@code x} across, {@code y} down is on. */
public boolean get(int x, int y) {
return (rows[y] >>> x & 1L) != 0;
}
/** Turns the cell {@code x} across, {@code y} down on or off. */
public void set(int x, int y, boolean on) {
long row = on ? rows[y] | 1L << x : rows[y] & ~(1L << x);
if (row != rows[y]) {
rows[y] = row;
changed();
}
}
/** Row {@code y}'s cells as bits, bit 0 the leftmost. */
public long row(int y) {
return rows[y];
}
/** Sets every row at once (a preset, a loaded profile); rows past the size are ignored. */
public void setRows(long[] values) {
boolean changed = false;
long mask = size == 64 ? -1L : (1L << size) - 1;
for (int y = 0; y < size; y++) {
long row = y < values.length ? values[y] & mask : 0;
if (rows[y] != row) {
rows[y] = row;
changed = true;
}
}
if (changed) {
changed();
}
}
/** Turns every cell off. */
public void clear() {
setRows(new long[size]);
}
@Override
public boolean isDefault() {
return Arrays.equals(rows, defaultRows);
}
@Override
public void reset() {
setRows(defaultRows);
}
@Override
public <R> R accept(SettingVisitor<R> visitor) {
return visitor.visit(this);
}
@Override
protected GridSetting self() {
return this;
}
}
@@ -0,0 +1,37 @@
package incari.framework.setting;
/** The shape of the ids that end up as config keys and file names. */
public final class Ids {
private static final int MAX_LENGTH = 48;
private Ids() {}
/**
* Returns {@code id} if it's 1 to 48 lowercase letters, digits, {@code _} or {@code -}, starting
* with a letter.
*
* @throws IllegalArgumentException otherwise
*/
public static String require(String id) {
if (!valid(id)) {
throw new IllegalArgumentException("Not a valid id (a-z, 0-9, _ and -, from a letter): \"" + id + "\"");
}
return id;
}
/** Whether {@code id} has the shape {@link #require} accepts. */
public static boolean valid(String id) {
if (id.isEmpty() || id.length() > MAX_LENGTH) {
return false;
}
for (int i = 0; i < id.length(); i++) {
char c = id.charAt(i);
boolean letter = c >= 'a' && c <= 'z';
if (i == 0 ? !letter : !(letter || (c >= '0' && c <= '9') || c == '_' || c == '-')) {
return false;
}
}
return true;
}
}
@@ -0,0 +1,91 @@
package incari.framework.setting;
import java.util.function.IntFunction;
/** A whole number between a minimum and a maximum, both included. Set values are clamped. */
public final class IntSetting extends Setting<IntSetting> {
private final int min;
private final int max;
private final int defaultValue;
private int value;
private IntFunction<String> format = Integer::toString;
/**
* @param id the config key
* @param name what the settings screen calls it
* @param min the smallest value
* @param max the largest value
* @param defaultValue the value before the player changes it, in range
*/
public IntSetting(String id, String name, int min, int max, int defaultValue) {
super(id, name);
if (min > max || defaultValue < min || defaultValue > max) {
throw new IllegalArgumentException(id + ": default " + defaultValue + " outside " + min + ".." + max);
}
this.min = min;
this.max = max;
this.defaultValue = defaultValue;
this.value = defaultValue;
}
/** The value. */
public int get() {
return value;
}
/** Sets the value, clamped into range. */
public void set(int value) {
int clamped = Math.max(min, Math.min(max, value));
if (this.value != clamped) {
this.value = clamped;
changed();
}
}
/** The smallest value. */
public int min() {
return min;
}
/** The largest value. */
public int max() {
return max;
}
/** The value before the player changes it. */
public int defaultValue() {
return defaultValue;
}
/** How the settings screen writes a value ("12 blocks", say); the bare number by default. */
public IntSetting formattedAs(IntFunction<String> format) {
this.format = format;
return this;
}
/** {@code value} as the settings screen writes it. */
public String format(int value) {
return format.apply(value);
}
@Override
public boolean isDefault() {
return value == defaultValue;
}
@Override
public void reset() {
set(defaultValue);
}
@Override
public <R> R accept(SettingVisitor<R> visitor) {
return visitor.visit(this);
}
@Override
protected IntSetting self() {
return this;
}
}
@@ -0,0 +1,73 @@
package incari.framework.setting;
import java.util.Locale;
import org.jspecify.annotations.Nullable;
/**
* A key or a mouse button, in the game's own codes: keyboard keys by scancode (USB HID usage, as
* SDL numbers them: 224 is Left Control, 229 Right Shift), mouse buttons from 0 (left). The config
* writes it as {@code keyboard:224}, {@code mouse:3} or {@code none}.
*
* @param device which device the code is on
* @param code the scancode or button; 0 on the keyboard is no key
*/
public record Key(Device device, int code) {
/** No key: a binding that never fires. */
public static final Key NONE = new Key(Device.KEYBOARD, 0);
/** Which device a {@link Key} is on. */
public enum Device {
/** A keyboard key, by scancode. */
KEYBOARD,
/** A mouse button, from 0. */
MOUSE
}
/** The keyboard key with this scancode. */
public static Key keyboard(int scancode) {
return new Key(Device.KEYBOARD, scancode);
}
/** The mouse button with this number (0 left, 1 right, 2 middle). */
public static Key mouse(int button) {
return new Key(Device.MOUSE, button);
}
/** Whether it's a real key, not {@link #NONE}. */
public boolean isBound() {
return !equals(NONE);
}
/** How the config writes it. */
public String encode() {
return isBound() ? device.name().toLowerCase(Locale.ROOT) + ":" + code : "none";
}
/** The key {@link #encode} wrote, or null if {@code text} isn't one. */
public static @Nullable Key decode(String text) {
if (text.equals("none")) {
return NONE;
}
int colon = text.indexOf(':');
if (colon < 0) {
return null;
}
@Nullable
Device device =
switch (text.substring(0, colon)) {
case "keyboard" -> Device.KEYBOARD;
case "mouse" -> Device.MOUSE;
default -> null;
};
if (device == null) {
return null;
}
try {
int code = Integer.parseInt(text.substring(colon + 1));
return code < 0 ? null : new Key(device, code);
} catch (NumberFormatException e) {
return null;
}
}
}
@@ -0,0 +1,91 @@
package incari.framework.setting;
import java.util.ArrayList;
import java.util.List;
/**
* A keybind: which {@link Key} does something. The module system reads the key once a tick through
* the game's own key handling, so a bind fires only with no screen open, as the game's do, and a
* press shorter than a tick still counts.
*
* <p>A module's binds other than its toggle key fire only while it's enabled.
*/
public final class KeySetting extends Setting<KeySetting> {
private final Key defaultValue;
private Key value;
private boolean down;
private final List<Runnable> pressHandlers = new ArrayList<>(1);
/**
* @param id the config key
* @param name what the settings screen calls it
* @param defaultValue the key before the player changes it; {@link Key#NONE} for none
*/
public KeySetting(String id, String name, Key defaultValue) {
super(id, name);
this.defaultValue = defaultValue;
this.value = defaultValue;
}
/** The key. */
public Key get() {
return value;
}
/** Binds another key, or {@link Key#NONE}. */
public void set(Key key) {
if (!value.equals(key)) {
value = key;
changed();
}
}
/** The key before the player changes it. */
public Key defaultValue() {
return defaultValue;
}
/** Runs {@code handler} on every press. */
public KeySetting onPress(Runnable handler) {
pressHandlers.add(handler);
return this;
}
/** Whether the key is held now (as of this tick), with no screen open. */
public boolean isDown() {
return down;
}
/** The module system's: the key's state this tick. */
public void update(boolean down) {
this.down = down;
}
/** The module system's: runs the press handlers once. */
public void press() {
for (int i = 0; i < pressHandlers.size(); i++) {
pressHandlers.get(i).run();
}
}
@Override
public boolean isDefault() {
return value.equals(defaultValue);
}
@Override
public void reset() {
set(defaultValue);
}
@Override
public <R> R accept(SettingVisitor<R> visitor) {
return visitor.visit(this);
}
@Override
protected KeySetting self() {
return this;
}
}
@@ -0,0 +1,119 @@
package incari.framework.setting;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BooleanSupplier;
import org.jspecify.annotations.Nullable;
/**
* One typed value a module or HUD element offers the player: a schema entry the settings screen is
* generated from and the profile's config stores. A module never draws its own settings; the UI
* reaches each kind through {@link SettingVisitor}, so restyling the UI changes no module.
*
* <p>Game thread only. A setting's id is part of the saved config: renaming one loses what players
* set.
*
* @param <S> the setting's own type, for the fluent configuration methods
*/
public abstract class Setting<S extends Setting<S>> {
private final String id;
private final String name;
private String description = "";
private @Nullable BooleanSupplier visible;
private boolean hidden;
private final List<Runnable> listeners = new ArrayList<>(1);
private @Nullable Runnable container;
/**
* @param id the config key: lowercase letters, digits, {@code _} and {@code -}
* @param name what the settings screen calls it
*/
protected Setting(String id, String name) {
this.id = Ids.require(id);
this.name = name;
}
/** The config key, unique within its module or HUD element. */
public final String id() {
return id;
}
/** The name the settings screen shows. */
public final String name() {
return name;
}
/** One sentence the settings screen shows as the setting's tooltip; empty for none. */
public final String description() {
return description;
}
/** Sets the tooltip sentence. */
public final S describedAs(String sentence) {
this.description = sentence;
return self();
}
/**
* Shows the setting only while {@code condition} holds (a color only while its text is shown,
* say). The settings screen asks again whenever any setting changes.
*/
public final S visibleWhen(BooleanSupplier condition) {
this.visible = condition;
return self();
}
/**
* Keeps the setting out of the generated settings screen: it's stored and restored, but set by
* something else (a HUD element's position, which the HUD editor sets).
*/
public final S hidden() {
this.hidden = true;
return self();
}
/** Whether the generated settings screen shows it now. */
public final boolean isVisible() {
BooleanSupplier condition = visible;
return !hidden && (condition == null || condition.getAsBoolean());
}
/** Whether it's kept out of the generated settings screen for good ({@link #hidden()}). */
public final boolean isHidden() {
return hidden;
}
/** Runs {@code listener} after every change to the value, from the screen or a profile load. */
public final void onChange(Runnable listener) {
listeners.add(listener);
}
/** Whether the value is the default. */
public abstract boolean isDefault();
/** Puts the default back. */
public abstract void reset();
/** Calls the visitor's method for this kind of setting. */
public abstract <R> R accept(SettingVisitor<R> visitor);
/** Every subclass returns itself, for the fluent methods. */
protected abstract S self();
/** Subclasses call this after the value changed. */
protected final void changed() {
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).run();
}
Runnable owner = container;
if (owner != null) {
owner.run();
}
}
/** {@link Settings} tells its container (the module system) about every change through this. */
final void attach(Runnable owner) {
this.container = owner;
}
}
@@ -0,0 +1,35 @@
package incari.framework.setting;
/**
* One method per kind of setting. The generated settings screen, the config codec and anything
* else that handles every kind implements this, so a new kind fails to compile wherever it isn't
* handled yet.
*
* @param <R> what each visit returns
*/
public interface SettingVisitor<R> {
/** An on/off value. */
R visit(BooleanSetting setting);
/** A whole number in a range. */
R visit(IntSetting setting);
/** A decimal number in a range. */
R visit(FloatSetting setting);
/** One of a fixed set of choices. */
R visit(ChoiceSetting<?> setting);
/** A color. */
R visit(ColorSetting setting);
/** A key or mouse button. */
R visit(KeySetting setting);
/** A button, with no value. */
R visit(ActionSetting setting);
/** A square of cells, each on or off. */
R visit(GridSetting setting);
}
@@ -0,0 +1,116 @@
package incari.framework.setting;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import org.jspecify.annotations.Nullable;
/**
* A module's or HUD element's settings, in the order the settings screen lists them. Declared as
* fields, in the constructor; the list is fixed once the module system has the module.
*/
public final class Settings implements Iterable<Setting<?>> {
private final List<Setting<?>> settings = new ArrayList<>();
private final List<Setting<?>> view = Collections.unmodifiableList(settings);
private Runnable owner = () -> {};
/** Adds {@code setting} at the end of the list. */
public <S extends Setting<S>> S add(S setting) {
if (get(setting.id()) != null) {
throw new IllegalArgumentException("Two settings with the id " + setting.id());
}
settings.add(setting);
setting.attach(this::changed);
return setting;
}
/** Adds an on/off setting. */
public BooleanSetting bool(String id, String name, boolean defaultValue) {
return add(new BooleanSetting(id, name, defaultValue));
}
/** Adds a whole-number setting. */
public IntSetting integer(String id, String name, int min, int max, int defaultValue) {
return add(new IntSetting(id, name, min, max, defaultValue));
}
/** Adds a decimal setting. */
public FloatSetting decimal(String id, String name, float min, float max, float step, float defaultValue) {
return add(new FloatSetting(id, name, min, max, step, defaultValue));
}
/** Adds a choice among an enum's constants. */
public <E extends Enum<E>> ChoiceSetting<E> choice(
String id, String name, E[] values, E defaultValue, Function<E, String> label) {
return add(new ChoiceSetting<>(id, name, values, defaultValue, label));
}
/** Adds an opaque color, {@code 0xRRGGBB}. */
public ColorSetting color(String id, String name, int rgb) {
return add(ColorSetting.opaque(id, name, rgb));
}
/** Adds a button that runs {@code action}, saying {@code label}. */
public ActionSetting action(String id, String name, String label, Runnable action) {
return add(new ActionSetting(id, name, label, action));
}
/** Adds a square of {@code size} cells a side, as {@link GridSetting} describes. */
public GridSetting grid(String id, String name, int size, long[] defaultRows) {
return add(new GridSetting(id, name, size, defaultRows));
}
/** Adds a keybind. */
public KeySetting key(String id, String name, Key defaultKey) {
return add(new KeySetting(id, name, defaultKey));
}
/** The setting with this id, or null. */
public @Nullable Setting<?> get(String id) {
for (Setting<?> setting : settings) {
if (setting.id().equals(id)) {
return setting;
}
}
return null;
}
/** Every setting, in order. Unmodifiable. */
public List<Setting<?>> all() {
return view;
}
/** Whether any setting shows in the generated settings screen. */
public boolean anyShown() {
for (Setting<?> setting : settings) {
if (!setting.isHidden()) {
return true;
}
}
return false;
}
/** Puts every setting's default back. */
public void resetAll() {
for (Setting<?> setting : settings) {
setting.reset();
}
}
@Override
public Iterator<Setting<?>> iterator() {
return view.iterator();
}
/** The module system's: where changes are reported. */
public void attach(Runnable owner) {
this.owner = owner;
}
private void changed() {
owner.run();
}
}
@@ -0,0 +1,8 @@
/**
* The typed settings schema: what a module offers the player, from which the settings screen is
* generated and the profile is saved.
*/
@NullMarked
package incari.framework.setting;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,230 @@
package incari.framework.waypoint;
import incari.framework.hud.Shape;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* A named mark at a block in one dimension of a world: its color and icon, whether it's shown,
* and whether a beacon's beam rises from it. Changing one that's in a {@link Waypoints} saves it.
* Game thread.
*/
public final class Waypoint {
/** The colors the editor offers, {@code 0xRRGGBB}, in order: each new waypoint takes the next. */
public static final List<Integer> COLORS = List.of(
0xFF5A5A, 0xFF9F43, 0xFFD93D, 0x8BE04E, 0x3DDC97, 0x3DD6F5, 0x5B8CFF, 0x9D7BFF, 0xF06FD8, 0xFFFFFF,
0xA9B4BF, 0x8B5E3C);
/** The longest name, in characters. */
public static final int MAX_NAME = 32;
private String name;
private int x;
private int y;
private int z;
private String dimension;
private int rgb;
private Shape icon;
private boolean visible = true;
private boolean beam = true;
private boolean death;
private boolean temporary;
private @Nullable Waypoints owner;
/**
* @param name what it's called (cut to {@link #MAX_NAME})
* @param x the block's x
* @param y the block's y
* @param z the block's z
* @param dimension the dimension's id, as {@code PlayerView.dimension()} gives it
* @param rgb its color, {@code 0xRRGGBB}
* @param icon its shape
*/
public Waypoint(String name, int x, int y, int z, String dimension, int rgb, Shape icon) {
this.name = clip(name);
this.x = x;
this.y = y;
this.z = z;
this.dimension = dimension;
this.rgb = rgb & 0xFFFFFF;
this.icon = icon;
}
/** A copy outside any list, for an editor to change before the player saves or cancels. */
public Waypoint copy() {
Waypoint copy = new Waypoint(name, x, y, z, dimension, rgb, icon);
copy.visible = visible;
copy.beam = beam;
copy.death = death;
copy.temporary = temporary;
return copy;
}
/** Takes every value of {@code other} (an edited {@link #copy}), as one change. */
public void set(Waypoint other) {
name = other.name;
x = other.x;
y = other.y;
z = other.z;
dimension = other.dimension;
rgb = other.rgb;
icon = other.icon;
visible = other.visible;
beam = other.beam;
death = other.death;
temporary = other.temporary;
changed();
}
/** What it's called. */
public String name() {
return name;
}
/** Renames it (cut to {@link #MAX_NAME}). */
public void setName(String name) {
this.name = clip(name);
changed();
}
/** The block's x. */
public int x() {
return x;
}
/** The block's y. */
public int y() {
return y;
}
/** The block's z. */
public int z() {
return z;
}
/** Moves it to another block in its dimension. */
public void setPosition(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
changed();
}
/** The dimension it's in. */
public String dimension() {
return dimension;
}
/** Its color, {@code 0xRRGGBB}. */
public int rgb() {
return rgb;
}
/** Its color with full alpha, {@code 0xFFRRGGBB}, for drawing. */
public int argb() {
return 0xFF000000 | rgb;
}
/** Recolors it. */
public void setRgb(int rgb) {
this.rgb = rgb & 0xFFFFFF;
changed();
}
/** Its shape on the minimap and over the world. */
public Shape icon() {
return icon;
}
/** Gives it another shape. */
public void setIcon(Shape icon) {
this.icon = icon;
changed();
}
/** Whether it's shown, on the minimap and over the world. */
public boolean isVisible() {
return visible;
}
/** Shows or hides it. */
public void setVisible(boolean visible) {
this.visible = visible;
changed();
}
/** Whether a beacon's beam rises from it, where beams are on. */
public boolean hasBeam() {
return beam;
}
/** Turns its beam on or off. */
public void setBeam(boolean beam) {
this.beam = beam;
changed();
}
/** Whether it marks where the player last died (made by the game, replaced at the next death). */
public boolean isDeath() {
return death;
}
/** Marks it as the last death's, or not. */
public void setDeath(boolean death) {
this.death = death;
changed();
}
/**
* Whether it lasts only while the player stays in the world: shown, but never saved to the
* world's file (a death's on a server, where one address can be many maps).
*/
public boolean isTemporary() {
return temporary;
}
/** Makes it last only for this visit to the world, or be saved as usual. */
public void setTemporary(boolean temporary) {
this.temporary = temporary;
// Saved either way: the file gains it, or loses it.
Waypoints list = owner;
if (list != null) {
list.changed(false);
}
}
/** The squared distance from {@code px, py, pz} to the middle of its block. */
public double distanceSquared(double px, double py, double pz) {
double dx = x + 0.5 - px;
double dy = y + 0.5 - py;
double dz = z + 0.5 - pz;
return dx * dx + dy * dy + dz * dz;
}
void attach(@Nullable Waypoints list) {
owner = list;
}
@Nullable
Waypoints owner() {
return owner;
}
private void changed() {
Waypoints list = owner;
if (list != null) {
list.changed(temporary);
}
}
private static String clip(String name) {
String stripped = name.strip();
return stripped.length() > MAX_NAME ? stripped.substring(0, MAX_NAME) : stripped;
}
@Override
public String toString() {
return name + " (" + x + ", " + y + ", " + z + " in " + dimension + ")";
}
}
@@ -0,0 +1,212 @@
package incari.framework.waypoint;
import incari.framework.config.ConfigStorage;
import incari.framework.config.WaypointCodec;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.function.Consumer;
import org.jspecify.annotations.Nullable;
/**
* The waypoints of the world the player is in, every dimension's, kept in a file of the world's
* own ({@code waypoints/<world>.json} beside the profiles): opened when the player joins a world,
* closed when they leave. Waypoints aren't part of a profile, so switching profiles keeps them.
*
* <p>Game thread. Changes are saved a second after the last one, as profiles are, or at once by
* {@link #flush()} and on {@link #close()}.
*/
public final class Waypoints {
/** Ticks from the last change to the save: dragging through a color is one save. */
static final int SAVE_DELAY_TICKS = 20;
private final ConfigStorage storage;
private final Consumer<String> log;
private final List<Waypoint> list = new ArrayList<>();
private final List<Waypoint> view = Collections.unmodifiableList(list);
private @Nullable String world;
private long revision;
private int saveCountdown = -1;
/**
* The module system's.
*
* @param storage where the files are kept
* @param log where problems go
*/
public Waypoints(ConfigStorage storage, Consumer<String> log) {
this.storage = storage;
this.log = log;
}
/** The world whose waypoints these are ({@code Game.world()}), or null outside a world. */
public @Nullable String world() {
return world;
}
/**
* Every waypoint of the world, in every dimension, in the order they were made. Unmodifiable;
* changes go through {@link #add} and {@link #remove}.
*/
public List<Waypoint> all() {
return view;
}
/**
* A number that goes up whenever a waypoint is added, removed or changed, or another world's
* are opened: what draws them compares it to know when to refresh.
*/
public long revision() {
return revision;
}
/** Adds {@code waypoint} at the end; nothing outside a world. */
public void add(Waypoint waypoint) {
if (world == null || waypoint.owner() == this) {
return;
}
Waypoints previous = waypoint.owner();
if (previous != null) {
previous.remove(waypoint);
}
list.add(waypoint);
waypoint.attach(this);
changed(waypoint.isTemporary());
}
/** Removes {@code waypoint}; nothing if it isn't here. */
public void remove(Waypoint waypoint) {
if (list.remove(waypoint)) {
waypoint.attach(null);
changed(waypoint.isTemporary());
}
}
/** The waypoint marking the player's last death in this world, or null. */
public @Nullable Waypoint death() {
for (Waypoint waypoint : list) {
if (waypoint.isDeath()) {
return waypoint;
}
}
return null;
}
/**
* Opens {@code name}'s waypoints ({@code Game.world()}), saving and closing any open ones first.
* A missing or unreadable file reads as none; an unreadable one isn't overwritten until
* something changes.
*/
public void open(String name) {
if (name.equals(world)) {
return;
}
close();
world = name;
try {
String text = storage.read(path(name));
if (text != null) {
for (Waypoint waypoint : WaypointCodec.read(text, message -> log.accept(name + ": " + message))) {
list.add(waypoint);
waypoint.attach(this);
}
}
} catch (IOException | RuntimeException e) {
log.accept("Couldn't read the waypoints of " + name + ": " + e);
}
revision++;
}
/** Saves any change and forgets the world's waypoints: the player left it. */
public void close() {
flush();
for (Waypoint waypoint : list) {
waypoint.attach(null);
}
list.clear();
world = null;
saveCountdown = -1;
revision++;
}
/**
* Deletes {@code name}'s waypoints: the game deleted the world, and a new one with its name
* mustn't find them. Nothing for the world open now.
*/
public void delete(String name) {
if (name.equals(world)) {
return;
}
try {
storage.delete(path(name));
} catch (IOException | RuntimeException e) {
log.accept("Couldn't delete the waypoints of " + name + ": " + e);
}
}
/** Once a client tick: a due save. */
public void tick() {
if (saveCountdown > 0 && --saveCountdown == 0) {
flush();
}
}
/** Saves now if anything changed since the last save; {@linkplain Waypoint#isTemporary() temporary} ones aren't. */
public void flush() {
String name = world;
if (saveCountdown < 0 || name == null) {
return;
}
saveCountdown = -1;
// A temporary waypoint is the visit's: never in the file.
List<Waypoint> kept = new ArrayList<>(list.size());
for (Waypoint waypoint : list) {
if (!waypoint.isTemporary()) {
kept.add(waypoint);
}
}
try {
if (kept.isEmpty()) {
storage.delete(path(name));
} else {
storage.write(path(name), WaypointCodec.write(kept));
}
} catch (IOException | RuntimeException e) {
log.accept("Couldn't save the waypoints of " + name + ": " + e);
}
}
/**
* A waypoint in the list changed, or the list did. A {@linkplain Waypoint#isTemporary()
* temporary} one's change needs no save: the file never has it (and an unreadable file isn't
* overwritten for it).
*/
void changed(boolean temporary) {
revision++;
if (!temporary) {
saveCountdown = SAVE_DELAY_TICKS;
}
}
/**
* The file a world's waypoints are kept in: its name with anything but letters, digits, dots
* and dashes made an underscore, and a hash of it, so two names that read alike stay apart.
*/
static String path(String world) {
StringBuilder file = new StringBuilder(world.length() + 16).append("waypoints/");
for (int i = 0; i < world.length() && i < 64; i++) {
char c = world.charAt(i);
boolean plain =
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-';
file.append(plain ? c : '_');
}
return file.append('-')
.append(Integer.toHexString(world.hashCode()).toLowerCase(Locale.ROOT))
.append(".json")
.toString();
}
}
@@ -0,0 +1,9 @@
/**
* Waypoints: named, colored marks at places in a world, kept for each world the player visits
* ({@link incari.framework.waypoint.Waypoints}, {@code ModuleSystem.waypoints()}). Modules show
* them (the world's labels and beams, the minimap); the client's screens list and edit them.
*/
@NullMarked
package incari.framework.waypoint;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,38 @@
package incari.framework;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
/**
* The framework is what features see of the game, so it holds no game, platform or TeaVM types:
* only the JDK's basics, JSpecify, and Gson's tree API for the config.
*/
@AnalyzeClasses(packages = "incari.framework", importOptions = ImportOption.DoNotIncludeTests.class)
class BoundaryTest {
@ArchTest
static final ArchRule onlyJdkAndJspecify = classes()
.that()
.resideOutsideOfPackage("incari.framework.config..")
.should()
.onlyDependOnClassesThat()
.resideInAnyPackage("java.lang..", "java.util..", "java.io", "org.jspecify..", "incari.framework..");
@ArchTest
static final ArchRule configAddsGson = classes()
.that()
.resideInAPackage("incari.framework.config..")
.should()
.onlyDependOnClassesThat()
.resideInAnyPackage(
"java.lang..",
"java.util..",
"java.io",
"org.jspecify..",
"com.google.gson..",
"incari.framework..");
}
@@ -0,0 +1,165 @@
package incari.framework;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.offset;
import incari.framework.config.Profiles;
import incari.framework.event.Events;
import incari.framework.game.GameOption;
import incari.framework.game.GamePart;
import incari.framework.hud.Anchor;
import incari.framework.hud.GamePartElement;
import incari.framework.setting.FloatSetting;
import incari.framework.testing.TestGame;
import org.junit.jupiter.api.Test;
/** Option holds, game parts and the fire overlay: what ADR 0050 adds to modules. */
class GameViewTest {
static final class Holder extends Module {
final FloatSetting level = settings().decimal("level", "Level", 0, 1, 0.05F, 0.2F);
int enables;
Holder() {
super("holder", "Holder", "Holds the damage tilt.", Category.VISUAL);
holdOption(GameOption.DAMAGE_TILT, level::get);
}
@Override
protected void onEnable() {
enables++;
}
}
@Test
void anOptionIsTakenOnFollowsTheSettingAndIsGivenBack() {
Holder holder = new Holder();
TestGame game = new TestGame(holder);
game.setOption(GameOption.DAMAGE_TILT, 0.9);
holder.setEnabled(true);
assertThat(game.option(GameOption.DAMAGE_TILT)).isEqualTo(0.2, org.assertj.core.data.Offset.offset(1e-6));
holder.level.set(0.5F);
game.tick();
assertThat(game.option(GameOption.DAMAGE_TILT)).isEqualTo(0.5);
assertThat(holder.isEnabled()).isTrue();
holder.setEnabled(false);
assertThat(game.option(GameOption.DAMAGE_TILT)).isEqualTo(0.9, org.assertj.core.data.Offset.offset(1e-4));
}
@Test
void thePlayersSliderWins() {
Holder holder = new Holder();
TestGame game = new TestGame(holder);
holder.setEnabled(true);
game.setOption(GameOption.DAMAGE_TILT, 0.7);
game.tick();
assertThat(holder.isEnabled()).isFalse();
assertThat(game.option(GameOption.DAMAGE_TILT)).isEqualTo(0.7);
// Turned on again, it takes the option again and remembers 0.7.
holder.setEnabled(true);
holder.setEnabled(false);
assertThat(game.option(GameOption.DAMAGE_TILT)).isEqualTo(0.7, org.assertj.core.data.Offset.offset(1e-4));
}
@Test
void aPlayersValueEqualToTheModulesIsGivenBack() {
Holder holder = new Holder();
TestGame game = new TestGame(holder);
game.setOption(GameOption.DAMAGE_TILT, 0.2);
holder.setEnabled(true);
holder.setEnabled(false);
assertThat(game.option(GameOption.DAMAGE_TILT)).isEqualTo(0.2, offset(1e-4));
}
@Test
void thePlayersValueIsGivenBackAfterARestart() {
Holder first = new Holder();
TestGame before = new TestGame(first);
before.setOption(GameOption.DAMAGE_TILT, 0.9);
first.setEnabled(true);
before.ticks(2);
before.system().flush();
// The game saved its options with the module's value in them.
Holder second = new Holder();
TestGame after = new TestGame(second);
after.files.putAll(before.files);
after.setOption(GameOption.DAMAGE_TILT, 0.2);
after.system().load();
assertThat(second.isEnabled()).isTrue();
second.setEnabled(false);
assertThat(after.option(GameOption.DAMAGE_TILT)).isEqualTo(0.9, offset(1e-4));
}
@Test
void anotherProfilesCopyDoesntReplaceThePlayersValue() {
Holder holder = new Holder();
TestGame game = new TestGame(holder);
assertThat(game.system().createProfile("Other")).isTrue();
game.setOption(GameOption.DAMAGE_TILT, 0.9);
holder.setEnabled(true);
game.tick();
// Default has the module off, and its own (default) idea of the player's value.
assertThat(game.system().switchProfile(Profiles.DEFAULT)).isTrue();
assertThat(holder.isEnabled()).isFalse();
assertThat(game.option(GameOption.DAMAGE_TILT)).isEqualTo(0.9, offset(1e-4));
}
@Test
void resetAllKeepsThePlayersValue() {
Holder holder = new Holder();
TestGame game = new TestGame(holder);
game.setOption(GameOption.DAMAGE_TILT, 0.9);
holder.setEnabled(true);
game.tick();
holder.settings().resetAll();
game.tick();
holder.setEnabled(false);
assertThat(game.option(GameOption.DAMAGE_TILT)).isEqualTo(0.9, offset(1e-4));
}
@Test
void anOptionIsHeldOnce() {
final class Twice extends Module {
Twice() {
super("twice", "Twice", "", Category.VISUAL);
holdOption(GameOption.DAMAGE_TILT, () -> 0);
holdOption(GameOption.DAMAGE_TILT, () -> 1);
}
}
assertThatThrownBy(Twice::new).isInstanceOf(IllegalArgumentException.class);
}
@Test
void aGamePartIsHeldWhileItsModuleIsOn() {
final class Part extends Module {
Part() {
super("part", "Part", "", Category.HUD);
hud(new GamePartElement(GamePart.SCOREBOARD, "sidebar", Anchor.RIGHT, 1, 0));
}
}
Part part = new Part();
TestGame game = new TestGame(part);
assertThat(game.system().holds(GamePart.SCOREBOARD)).isFalse();
part.setEnabled(true);
assertThat(game.system().holds(GamePart.SCOREBOARD)).isTrue();
part.setEnabled(false);
assertThat(game.system().holds(GamePart.SCOREBOARD)).isFalse();
}
@Test
void theFireOverlayEventCostsNothingUnheard() {
Holder holder = new Holder();
TestGame game = new TestGame(holder);
assertThat(game.system().events().count(Events.FIRE_OVERLAY)).isZero();
assertThat(game.fireOverlay()).isZero();
}
}
@@ -0,0 +1,373 @@
package incari.framework;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import incari.framework.event.Events;
import incari.framework.hud.Anchor;
import incari.framework.hud.HudCanvas;
import incari.framework.hud.HudElement;
import incari.framework.hud.Tone;
import incari.framework.setting.BooleanSetting;
import incari.framework.setting.IntSetting;
import incari.framework.setting.Key;
import incari.framework.setting.KeySetting;
import incari.framework.testing.TestGame;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class ModuleSystemTest {
/** A module with a bit of everything, counting what happens to it. */
static final class Sample extends Module {
final BooleanSetting flag = settings().bool("flag", "Flag", false);
final IntSetting amount = settings().integer("amount", "Amount", 0, 10, 3);
final KeySetting action = settings().key("action", "Action", Key.keyboard(9));
final List<String> calls = new ArrayList<>();
boolean throwOnTick;
Sample(String id) {
super(id, "Sample " + id, "For tests.", Category.UTILITY);
on(Events.TICK, this::tick);
action.onPress(() -> calls.add("action"));
hud(new Label());
}
private void tick() {
if (throwOnTick) {
throw new IllegalStateException("broken");
}
calls.add("tick");
}
@Override
protected void onEnable() {
calls.add("enable flag=" + flag.get());
}
@Override
protected void onDisable() {
calls.add("disable");
}
static final class Label extends HudElement {
Label() {
super("label", "Label", Anchor.TOP_RIGHT, 2, 2);
}
@Override
public int width(HudCanvas canvas) {
return canvas.textWidth("hi");
}
@Override
public int height(HudCanvas canvas) {
return canvas.lineHeight();
}
@Override
public void draw(HudCanvas canvas) {
canvas.text("hi", 0, 0, Tone.ACCENT);
}
}
}
@Test
void listenersRunOnlyWhileEnabled() {
Sample sample = new Sample("sample");
TestGame game = new TestGame(sample);
game.tick();
assertThat(game.system().events().count(Events.TICK)).isZero();
sample.setEnabled(true);
game.tick();
sample.setEnabled(false);
game.tick();
assertThat(sample.calls).containsExactly("enable flag=false", "tick", "disable");
assertThat(game.system().events().count(Events.TICK)).isZero();
}
@Test
void theToggleKeyWorksWhileOffAndOtherKeysOnlyWhileOn() {
Sample sample = new Sample("sample");
TestGame game = new TestGame(sample);
sample.toggleKey().set(Key.keyboard(40));
game.press(Key.keyboard(9));
game.tick();
assertThat(sample.calls).isEmpty();
game.press(Key.keyboard(40));
game.tick();
assertThat(sample.isEnabled()).isTrue();
game.press(Key.keyboard(9));
game.press(Key.keyboard(9));
game.tick();
assertThat(sample.calls).containsExactly("enable flag=false", "tick", "action", "action", "tick");
}
@Test
void unboundKeysNeverFire() {
Sample sample = new Sample("sample");
TestGame game = new TestGame(sample);
sample.setEnabled(true);
sample.action.set(Key.NONE);
sample.calls.clear();
// A key the platform can't name arrives as "no key", which is what unbound keys hold.
game.press(Key.NONE);
game.hold(Key.NONE, true);
game.tick();
assertThat(sample.isEnabled()).isTrue();
assertThat(sample.action.isDown()).isFalse();
assertThat(sample.calls).containsExactly("tick");
}
@Test
void heldKeysReadAsDownOnlyWhileTheirModuleIsOn() {
Sample sample = new Sample("sample");
TestGame game = new TestGame(sample);
game.hold(Key.keyboard(9), true);
game.tick();
assertThat(sample.action.isDown()).isFalse();
sample.setEnabled(true);
game.tick();
assertThat(sample.action.isDown()).isTrue();
}
@Test
void aModuleThatThrowsIsTurnedOffAndLogged() {
Sample broken = new Sample("broken");
Sample fine = new Sample("fine");
TestGame game = new TestGame(broken, fine);
broken.setEnabled(true);
fine.setEnabled(true);
broken.throwOnTick = true;
game.tick();
game.tick();
assertThat(broken.isEnabled()).isFalse();
assertThat(fine.calls).containsExactly("enable flag=false", "tick", "tick");
assertThat(game.warnings).hasSize(1).first().asString().contains("broken", "tick", "turned off");
// The player is told, once.
assertThat(game.messages)
.containsExactly("Sample broken was turned off: It hit a problem. You can turn it on again.");
}
@Test
void theHudDrawsEnabledModulesElementsWherePlaced() {
Sample sample = new Sample("sample");
TestGame game = new TestGame(sample);
assertThat(game.system().hasHud()).isFalse();
assertThat(game.drawHud().drawn).isEmpty();
sample.setEnabled(true);
HudElement label = sample.hudElements().get(0);
label.scale().set(2);
TestGame.Canvas canvas = game.drawHud();
// 12 units wide at 2x is 24, 2 in from the right of 320.
assertThat(canvas.drawn).containsExactly("text \"hi\" at 294,2 ACCENT");
assertThat(canvas.balanced()).isTrue();
}
@Test
void changesAreSavedASecondAfterTheLastOne() {
Sample sample = new Sample("sample");
TestGame game = new TestGame(sample);
sample.amount.set(7);
game.ticks(19);
assertThat(game.files).isEmpty();
sample.amount.set(8);
game.ticks(19);
assertThat(game.files).isEmpty();
game.tick();
assertThat(game.files).containsKeys("profiles.json", "profiles/Default.json");
assertThat(game.files.get("profiles/Default.json")).contains("\"amount\": 8");
}
@Test
void aToggleByKeyIsSavedAtOnce() {
Sample sample = new Sample("sample");
TestGame game = new TestGame(sample);
sample.toggleKey().set(Key.keyboard(40));
game.system().flush();
game.files.clear();
game.press(Key.keyboard(40));
game.tick();
assertThat(game.files.get("profiles/Default.json")).contains("\"enabled\": true");
}
@Test
void aSavedProfileComesBackInANewSession() {
Sample sample = new Sample("sample");
TestGame game = new TestGame(sample);
sample.flag.set(true);
sample.setEnabled(true);
sample.action.set(Key.mouse(3));
sample.hudElements().get(0).anchor().set(Anchor.BOTTOM);
game.system().flush();
Sample again = new Sample("sample");
TestGame next = new TestGame(again);
next.files.putAll(game.files);
next.system().load();
assertThat(again.isEnabled()).isTrue();
assertThat(again.flag.get()).isTrue();
assertThat(again.action.get()).isEqualTo(Key.mouse(3));
assertThat(again.hudElements().get(0).anchor().get()).isEqualTo(Anchor.BOTTOM);
// onEnable ran after the settings were read.
assertThat(again.calls).containsExactly("enable flag=true");
// Loading isn't a change to save.
next.files.clear();
next.ticks(30);
assertThat(next.files).isEmpty();
}
@Test
void twoModulesCantShareAnId() {
assertThatThrownBy(() -> new TestGame(new Sample("same"), new Sample("same")))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void modulesSubscribeOnlyInTheirConstructor() {
Sample sample = new Sample("sample");
new TestGame(sample);
assertThatThrownBy(() -> sample.on(Events.TICK, () -> {})).isInstanceOf(IllegalStateException.class);
}
/** A module with one live element and one drawn with the HUD. */
static final class Live extends Module {
Live() {
super("live", "Live", "For tests.", Category.HUD);
hud(new Sample.Label());
hud(new HudElement("compass", "Compass", Anchor.TOP_LEFT, 0, 0) {
@Override
public boolean isLive() {
return true;
}
@Override
public int width(HudCanvas canvas) {
return 10;
}
@Override
public int height(HudCanvas canvas) {
return 10;
}
@Override
public void draw(HudCanvas canvas) {
canvas.text("N", 0, 0, Tone.ACCENT);
}
});
}
}
@Test
void liveElementsAreDrawnEveryFrameNotWithTheHud() {
TestGame game = new TestGame(new Live());
assertThat(game.system().hasLiveHud()).isFalse();
game.module().setEnabled(true);
assertThat(game.system().hasHud()).isTrue();
assertThat(game.system().hasLiveHud()).isTrue();
assertThat(game.drawHud().drawn).containsExactly("text \"hi\" at 306,2 ACCENT");
assertThat(game.drawLive().drawn).containsExactly("text \"N\" at 0,0 ACCENT");
}
@Test
void anActionIsAButtonNotAValue() {
List<String> pressed = new ArrayList<>();
Sample sample = new Sample("sample");
incari.framework.setting.ActionSetting open =
sample.settings().action("open", "Things", "Open...", () -> pressed.add("open"));
TestGame game = new TestGame(sample);
open.run();
assertThat(pressed).containsExactly("open");
sample.flag.set(true);
game.system().flush();
assertThat(game.files.values()).noneMatch(text -> text.contains("\"open\""));
}
/** A part of the client rather than a choice. */
static final class Built extends Module {
Built() {
super("built", "Built", "For tests.", Category.UTILITY);
alwaysOn();
}
}
@Test
void anAlwaysOnModuleIsOnAfterLoadingAndCantBeTurnedOff() {
Built built = new Built();
TestGame game = new TestGame(built, new Sample("sample"));
game.files.put("profiles/Default.json", "{\"modules\": {\"built\": {\"enabled\": false}}}");
game.system().load();
assertThat(built.isEnabled()).isTrue();
built.setEnabled(false);
built.toggle();
assertThat(built.isEnabled()).isTrue();
assertThat(built.toggleKey().isHidden()).isTrue();
}
@Test
void aPresetMakesItsProfileAndSetsWhichModulesAreOn() {
Sample a = new Sample("a");
Sample b = new Sample("b");
Built built = new Built();
TestGame game = new TestGame(a, b, built);
game.system().load();
a.setEnabled(true);
b.amount.set(7);
assertThat(game.system().applyPreset("QoL", java.util.Set.of("b", "missing")))
.isTrue();
assertThat(game.system().activeProfile()).isEqualTo("QoL");
assertThat(a.isEnabled()).isFalse();
assertThat(b.isEnabled()).isTrue();
assertThat(b.amount.get()).isEqualTo(7);
assertThat(built.isEnabled()).isTrue();
// Applied again later, it switches back to the same profile.
game.system().switchProfile("Default");
assertThat(a.isEnabled()).isTrue();
assertThat(game.system().applyPreset("qol", java.util.Set.of("a"))).isTrue();
assertThat(game.system().profiles()).containsExactly("Default", "QoL");
assertThat(a.isEnabled()).isTrue();
assertThat(b.isEnabled()).isFalse();
}
@Test
void aPresetCanSetSettings() {
Sample a = new Sample("a");
TestGame game = new TestGame(a);
game.system().load();
assertThat(game.system().applyPreset("1.8 PvP", java.util.Set.of("a"), java.util.Map.of("a.amount", "9")))
.isTrue();
assertThat(game.system().activeProfile()).isEqualTo("1.8 PvP");
assertThat(a.amount.get()).isEqualTo(9);
// A value the setting can't take leaves it.
game.system().applyPreset("1.8 PvP", java.util.Set.of("a"), java.util.Map.of("a.amount", "lots"));
assertThat(a.amount.get()).isEqualTo(9);
}
}
@@ -0,0 +1,96 @@
package incari.framework;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import incari.framework.testing.TestGame;
import org.junit.jupiter.api.Test;
/** A module that's the switch for a resource pack ({@link Module#followPack}). */
class PackSwitchTest {
static final class Switch extends Module {
Switch(String pack) {
super("switch", "Switch", "Turns a pack on.", Category.VISUAL);
followPack(pack);
}
}
@Test
void turningTheModuleOnAndOffTurnsThePack() {
Switch module = new Switch("programmer_art");
TestGame game = new TestGame(module);
module.setEnabled(true);
assertThat(game.selectedPacks).containsExactly("programmer_art");
assertThat(game.reloads).isEqualTo(1);
game.ticks(3);
assertThat(module.isEnabled()).isTrue();
module.setEnabled(false);
assertThat(game.selectedPacks).isEmpty();
assertThat(game.reloads).isEqualTo(2);
}
@Test
void theResourcePacksScreenTurnsTheModule() {
Switch module = new Switch("programmer_art");
TestGame game = new TestGame(module);
game.selectedPacks.add("programmer_art");
game.tick();
assertThat(module.isEnabled()).isTrue();
game.selectedPacks.clear();
game.tick();
assertThat(module.isEnabled()).isFalse();
// Following the game, the module asked for no reload of its own.
assertThat(game.reloads).isZero();
}
@Test
void atStartThePackWinsOverTheProfile() {
Switch module = new Switch("programmer_art");
TestGame game = new TestGame(module);
module.setEnabled(true);
game.system().flush();
// A new start: the profile has the module on, but the player turned the pack off since.
Switch again = new Switch("programmer_art");
TestGame restarted = new TestGame(again);
restarted.files.putAll(game.files);
restarted.system().load();
assertThat(again.isEnabled()).isFalse();
assertThat(restarted.reloads).isZero();
restarted.selectedPacks.add("programmer_art");
restarted.system().load();
assertThat(again.isEnabled()).isTrue();
assertThat(restarted.reloads).isZero();
}
@Test
void aMissingPackTurnsTheModuleBackOff() {
Switch module = new Switch("programmer_art");
TestGame game = new TestGame(module);
game.packs.clear();
module.setEnabled(true);
assertThat(game.warnings).anyMatch(w -> w.contains("programmer_art"));
game.tick();
assertThat(module.isEnabled()).isFalse();
}
@Test
void aModuleFollowsOnePack() {
final class Two extends Module {
Two() {
super("two", "Two", "", Category.VISUAL);
followPack("programmer_art");
followPack("high_contrast");
}
}
assertThatThrownBy(Two::new).isInstanceOf(IllegalArgumentException.class);
}
}
@@ -0,0 +1,138 @@
package incari.framework.config;
import static org.assertj.core.api.Assertions.assertThat;
import incari.framework.Category;
import incari.framework.Module;
import incari.framework.setting.ColorSetting;
import incari.framework.setting.IntSetting;
import incari.framework.testing.TestGame;
import org.junit.jupiter.api.Test;
class ProfilesTest {
static final class Sample extends Module {
final IntSetting amount = settings().integer("amount", "Amount", 0, 10, 3);
final ColorSetting color = settings().color("color", "Color", 0x112233);
Sample() {
super("sample", "Sample", "For tests.", Category.UTILITY);
}
}
@Test
void aNewProfileStartsAsACopyAndSwitchingKeepsEach() {
Sample sample = new Sample();
TestGame game = new TestGame(sample);
sample.amount.set(5);
assertThat(game.system().createProfile("PvP")).isTrue();
assertThat(game.system().activeProfile()).isEqualTo("PvP");
assertThat(sample.amount.get()).isEqualTo(5);
sample.amount.set(9);
sample.setEnabled(true);
assertThat(game.system().switchProfile("Default")).isTrue();
assertThat(sample.amount.get()).isEqualTo(5);
assertThat(sample.isEnabled()).isFalse();
assertThat(game.system().switchProfile("pvp")).isTrue();
assertThat(sample.amount.get()).isEqualTo(9);
assertThat(sample.isEnabled()).isTrue();
assertThat(game.system().profiles()).containsExactly("Default", "PvP");
}
@Test
void namesAreCheckedAndUniqueWithoutCase() {
TestGame game = new TestGame(new Sample());
assertThat(game.system().createProfile("default")).isFalse();
assertThat(game.system().createProfile("../escape")).isFalse();
assertThat(game.system().createProfile(" padded")).isFalse();
assertThat(game.system().createProfile("")).isFalse();
assertThat(game.system().createProfile("Building 2")).isTrue();
assertThat(Profiles.validName("A-b_c 9")).isTrue();
assertThat(Profiles.validName("café")).isFalse();
assertThat(Profiles.validName("1.8 PvP")).isTrue();
assertThat(Profiles.validName("..")).isFalse();
assertThat(Profiles.validName("a/b")).isFalse();
}
@Test
void deletingTheActiveProfileMovesToTheFirstAndTheLastStays() {
Sample sample = new Sample();
TestGame game = new TestGame(sample);
game.system().createProfile("PvP");
sample.amount.set(1);
game.system().flush();
assertThat(game.system().deleteProfile("PvP")).isTrue();
assertThat(game.system().activeProfile()).isEqualTo("Default");
assertThat(sample.amount.get()).isEqualTo(3);
assertThat(game.files).doesNotContainKey("profiles/PvP.json");
assertThat(game.system().deleteProfile("Default")).isFalse();
}
@Test
void theActiveProfileIsRememberedAcrossSessions() {
Sample sample = new Sample();
TestGame game = new TestGame(sample);
game.system().createProfile("PvP");
sample.amount.set(7);
game.system().flush();
Sample again = new Sample();
TestGame next = new TestGame(again);
next.files.putAll(game.files);
next.system().load();
assertThat(next.system().activeProfile()).isEqualTo("PvP");
assertThat(again.amount.get()).isEqualTo(7);
}
@Test
void modulesThisBuildLacksAreKeptAndBadValuesFallBackToDefaults() {
Sample sample = new Sample();
TestGame game = new TestGame(sample);
game.files.put("profiles.json", "{\"active\": \"Default\", \"profiles\": [\"Default\"]}");
game.files.put("profiles/Default.json", """
{"format": 1, "modules": {
"sample": {"enabled": true, "settings": {"amount": "lots", "color": "#AABBCC"}},
"gone": {"enabled": true, "settings": {"x": 1}}
}}
""");
game.system().load();
assertThat(sample.isEnabled()).isTrue();
assertThat(sample.amount.get()).isEqualTo(3);
assertThat(sample.color.get()).isEqualTo(0xFFAABBCC);
sample.amount.set(4);
game.system().flush();
assertThat(game.files.get("profiles/Default.json")).contains("\"gone\"", "\"x\": 1", "\"amount\": 4");
}
@Test
void aBrokenFileIsReportedAndReadAsDefaults() {
Sample sample = new Sample();
TestGame game = new TestGame(sample);
game.files.put("profiles/Default.json", "{not json");
sample.amount.set(8);
game.system().load();
assertThat(sample.amount.get()).isEqualTo(3);
assertThat(game.warnings).anyMatch(line -> line.contains("profiles/Default.json"));
// Not overwritten until something changes.
assertThat(game.files.get("profiles/Default.json")).isEqualTo("{not json");
}
@Test
void colorsAreWrittenAsHex() {
assertThat(ProfileCodec.colorText(0xFF00AA11)).isEqualTo("#FF00AA11");
assertThat(ProfileCodec.colorText(0x0000000F)).isEqualTo("#0000000F");
assertThat(ProfileCodec.parseColor("#00AA11")).isEqualTo(0xFF00AA11);
assertThat(ProfileCodec.parseColor("#80000000")).isEqualTo(0x80000000);
assertThat(ProfileCodec.parseColor("00AA11")).isNull();
assertThat(ProfileCodec.parseColor("#GG0000")).isNull();
}
}
@@ -0,0 +1,108 @@
package incari.framework.event;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class EventBusTest {
private final List<String> failures = new ArrayList<>();
private final EventBus bus =
new EventBus((owner, channel, error) -> failures.add(owner + " " + channel + " " + error.getMessage()));
@Test
void firesListenersInTheOrderTheySubscribed() {
List<String> calls = new ArrayList<>();
TickListener first = () -> calls.add("first");
TickListener second = () -> calls.add("second");
bus.add(Events.TICK, "a", first);
bus.add(Events.TICK, "b", second);
bus.fireTick();
assertThat(calls).containsExactly("first", "second");
assertThat(bus.count(Events.TICK)).isEqualTo(2);
}
@Test
void removesOnlyTheListenerGiven() {
List<String> calls = new ArrayList<>();
TickListener first = () -> calls.add("first");
TickListener second = () -> calls.add("second");
TickListener third = () -> calls.add("third");
bus.add(Events.TICK, "a", first);
bus.add(Events.TICK, "b", second);
bus.add(Events.TICK, "c", third);
bus.remove(Events.TICK, second);
bus.remove(Events.TICK, second);
bus.fireTick();
assertThat(calls).containsExactly("first", "third");
bus.remove(Events.TICK, first);
bus.remove(Events.TICK, third);
assertThat(bus.count(Events.TICK)).isZero();
}
@Test
void aListenerRemovedDuringAFireStillRunsThatFire() {
List<String> calls = new ArrayList<>();
TickListener[] second = new TickListener[1];
TickListener first = () -> {
calls.add("first");
bus.remove(Events.TICK, second[0]);
};
second[0] = () -> calls.add("second");
bus.add(Events.TICK, "a", first);
bus.add(Events.TICK, "b", second[0]);
bus.fireTick();
bus.fireTick();
assertThat(calls).containsExactly("first", "second", "first");
}
@Test
void aThrowingListenerIsReportedAndTheRestStillRun() {
List<String> calls = new ArrayList<>();
bus.add(Events.TICK, "broken", (TickListener) () -> {
throw new IllegalStateException("boom");
});
bus.add(Events.TICK, "fine", (TickListener) () -> calls.add("fine"));
bus.fireTick();
assertThat(failures).containsExactly("broken tick boom");
assertThat(calls).containsExactly("fine");
}
@Test
void movementReportsWhetherAListenerChangedTheInput() {
MovementInput input = new MovementInput();
input.reset(true, false, false, false, false, false, false, 0, 0);
assertThat(bus.fireMovement(input)).isFalse();
bus.add(Events.MOVEMENT, "m", (MovementListener) in -> in.setSprint(true));
input.reset(true, false, false, false, false, false, false, 0, 0);
assertThat(bus.fireMovement(input)).isTrue();
assertThat(input.sprint()).isTrue();
// Setting what's already there isn't a change.
input.reset(true, false, false, false, false, false, true, 0, 0);
assertThat(bus.fireMovement(input)).isFalse();
}
@Test
void joinAndLeaveReachTheirListeners() {
List<String> calls = new ArrayList<>();
bus.add(Events.JOIN, "m", (JoinListener) server -> calls.add("join " + server));
bus.add(Events.LEAVE, "m", (LeaveListener) () -> calls.add("leave"));
bus.fireJoin("ws://example.net");
bus.fireLeave();
assertThat(calls).containsExactly("join ws://example.net", "leave");
}
}
@@ -0,0 +1,53 @@
package incari.framework.hud;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class AnchorTest {
@Test
void sidesMeasureOffsetsInward() {
assertThat(Anchor.TOP_LEFT.x(2, 50, 320)).isEqualTo(2);
assertThat(Anchor.TOP_RIGHT.x(2, 50, 320)).isEqualTo(268);
assertThat(Anchor.BOTTOM_RIGHT.y(4, 9, 240)).isEqualTo(227);
}
@Test
void centersMeasureOffsetsFromTheMiddle() {
assertThat(Anchor.CENTER.x(0, 50, 320)).isEqualTo(135);
assertThat(Anchor.TOP.x(-10, 50, 320)).isEqualTo(125);
assertThat(Anchor.LEFT.y(0, 10, 240)).isEqualTo(115);
}
@Test
void elementsStayOnScreen() {
assertThat(Anchor.TOP_LEFT.x(400, 50, 320)).isEqualTo(270);
assertThat(Anchor.TOP_RIGHT.x(-30, 50, 320)).isEqualTo(270);
assertThat(Anchor.TOP_LEFT.x(-5, 50, 320)).isZero();
// Bigger than the screen: pinned to its start.
assertThat(Anchor.BOTTOM_RIGHT.x(0, 400, 320)).isZero();
}
@Test
void theNearestAnchorIsTheThirdTheMiddleIsIn() {
assertThat(Anchor.nearest(2, 2, 50, 9, 320, 240)).isEqualTo(Anchor.TOP_LEFT);
assertThat(Anchor.nearest(135, 115, 50, 10, 320, 240)).isEqualTo(Anchor.CENTER);
assertThat(Anchor.nearest(268, 227, 50, 9, 320, 240)).isEqualTo(Anchor.BOTTOM_RIGHT);
assertThat(Anchor.nearest(130, 2, 50, 9, 320, 240)).isEqualTo(Anchor.TOP);
// Bigger than the screen: still an anchor, by its middle.
assertThat(Anchor.nearest(0, 0, 400, 300, 320, 240)).isEqualTo(Anchor.CENTER);
}
@Test
void offsetsAreThePlacementsInverse() {
for (Anchor anchor : Anchor.values()) {
for (int start : new int[] {0, 3, 100, 135, 270}) {
assertThat(anchor.x(anchor.offsetX(start, 50, 320), 50, 320)).isEqualTo(start);
assertThat(anchor.y(anchor.offsetY(start % 191, 49, 240), 49, 240))
.isEqualTo(start % 191);
}
}
assertThat(Anchor.TOP_RIGHT.offsetX(268, 50, 320)).isEqualTo(2);
}
}

Some files were not shown because too many files have changed in this diff Show More