Skip to content

Commit

Permalink
Refactor SpeedPresets to use Object2IntMap.
Browse files Browse the repository at this point in the history
Replaced LinkedHashMap with Object2IntMap for efficiency and consistency in managing speed presets. Adjusted related methods and logic to accommodate the new data structure. Updated SpeedPresetListWidget to handle changes and comparisons using the revised map implementation.
  • Loading branch information
Manchick0 committed Dec 29, 2024
1 parent 010b328 commit ea4efb8
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 47 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package de.hysky.skyblocker.skyblock.speedPreset;

import it.unimi.dsi.fastutil.Pair;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.Drawable;
Expand All @@ -8,18 +10,17 @@
import net.minecraft.client.gui.widget.*;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jetbrains.annotations.Nullable;

import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

public class SpeedPresetListWidget extends ElementListWidget<SpeedPresetListWidget.AbstractEntry> {

private static final Pattern NUMBER = Pattern.compile("^-?\\d+(\\.\\d+)?$");
// Alphanumeric sequence that doesn't start with a number.
private static final Pattern TITLE = Pattern.compile("^[a-zA-Z][a-zA-Z0-9_]*$");
private static final Logger LOGGER = LoggerFactory.getLogger(SpeedPresetListWidget.class);

public SpeedPresetListWidget(int width, int height, int y) {
super(MinecraftClient.getInstance(), width, height, y, 25);
Expand All @@ -38,12 +39,18 @@ public int getRowWidth() {
}

public boolean hasBeenChanged() {
var presets = SpeedPresets.getInstance().getPresetCount();
var presets = SpeedPresets.getInstance();
// If there are fewer children than presets, some were removed, and all further checks are pointless
if (children().size() < presets) return true;
return presets != children().stream().filter(SpeedPresetEntry.class::isInstance)
.filter(preset -> !((SpeedPresetEntry) preset).isEmpty())
.count() || children().stream().filter(SpeedPresetEntry.class::isInstance).map(SpeedPresetEntry.class::cast).anyMatch(SpeedPresetEntry::hasBeenModified);
if (children().size() < presets.getPresetCount()) return true;
var childrenMap = new Object2IntOpenHashMap<String>();
this.children().stream()
.filter(SpeedPresetEntry.class::isInstance)
.map(SpeedPresetEntry.class::cast)
.filter(entry -> !entry.isEmpty())
.map(SpeedPresetEntry::getMapping)
.filter(Objects::nonNull)
.forEach(mapping -> childrenMap.put(mapping.first(), mapping.second()));
return !presets.compare(childrenMap);
}

public void updatePosition() {
Expand All @@ -67,11 +74,7 @@ public void save() {

public abstract static class AbstractEntry extends ElementListWidget.Entry<AbstractEntry> {

protected boolean hasBeenModified() {
return false;
}

protected void updatePosition(){}
protected void updatePosition() {}

@Override
public void render(DrawContext context, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) {
Expand Down Expand Up @@ -111,15 +114,9 @@ public class SpeedPresetEntry extends AbstractEntry {
protected final TextFieldWidget speedInput;
protected final ButtonWidget removeButton;

protected final String initialTitle;
protected final String initialSpeed;

public SpeedPresetEntry(String title, String speed) {
var client = SpeedPresetListWidget.this.client;

this.initialTitle = title;
this.initialSpeed = speed;

// All Xs and Ys are then set using the initPosition() method.
this.titleInput = new TextFieldWidget(client.textRenderer, 0, 0, 120, 20, Text.empty());
this.titleInput.setTextPredicate(str -> str.isEmpty() || TITLE.matcher(str).matches());
Expand All @@ -133,9 +130,10 @@ public SpeedPresetEntry(String title, String speed) {
this.speedInput.setMaxLength(3);
this.speedInput.setPlaceholder(Text.literal("0").formatted(Formatting.DARK_GRAY));

this.removeButton = ButtonWidget.builder(Text.literal("-"), (btn) -> {
SpeedPresetListWidget.this.removeEntry(this);
}).dimensions(0, 0, 20, 20).build();
this.removeButton = ButtonWidget.builder(Text.literal("-"),
(btn) -> SpeedPresetListWidget.this.removeEntry(this))
.dimensions(0, 0, 20, 20)
.build();

this.updatePosition();
}
Expand All @@ -152,15 +150,10 @@ public List<? extends Element> children() {

public void save() {
var presets = SpeedPresets.getInstance();
assert presets != null && children().size() == 3;
var title = ((TextFieldWidget) children().get(0)).getText();
var speed = ((TextFieldWidget) children().get(1)).getText();
if (title.isEmpty()) return;
try {
presets.setPreset(title, Short.parseShort(speed));
} catch (NumberFormatException e) {
LOGGER.warn("Couldn't save speed preset '{}' because of an invalid speed value: {}", title, speed);
}
if (this.isEmpty()) return;
var mapping = getMapping();
if (mapping != null)
presets.setPreset(mapping.first(), mapping.second());
}

protected boolean isEmpty() {
Expand All @@ -178,10 +171,13 @@ protected void updatePosition() {
SimplePositioningWidget.setPos(grid, 0, 0, width, itemHeight, 0.5f, 0.5f);
}

@Override
protected boolean hasBeenModified() {
return !this.titleInput.getText().equals(this.initialTitle)
|| !this.speedInput.getText().equals(this.initialSpeed);
@Nullable
protected Pair<String, Short> getMapping() {
try {
return Pair.of(titleInput.getText(), Short.parseShort(speedInput.getText()));
} catch (NumberFormatException e) {
return null;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import de.hysky.skyblocker.annotations.Init;
import de.hysky.skyblocker.config.SkyblockerConfigManager;
import de.hysky.skyblocker.utils.Utils;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.fabricmc.fabric.api.client.message.v1.ClientSendMessageEvents;
Expand All @@ -22,9 +24,7 @@
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.regex.Pattern;

Expand All @@ -33,15 +33,15 @@ public class SpeedPresets {
private static final Pattern COMMAND_PATTERN = Pattern.compile("^setmaxspeed\\s([a-zA-Z][a-zA-Z0-9_]*)$");

private static final Logger LOGGER = LoggerFactory.getLogger(SpeedPresets.class);
private static final Codec<Map<String, Short>> MAP_CODEC = Codec.unboundedMap(Codec.STRING, Codec.SHORT);
private static final Codec<Map<String, Integer>> MAP_CODEC = Codec.unboundedMap(Codec.STRING, Codec.INT);
private static final File PRESETS_FILE = new File(SkyblockerMod.CONFIG_DIR.toFile(), "speed_presets.json");

private static SpeedPresets instance;

private final Map<String, Short> presets;
private final Object2IntMap<String> presets;

private SpeedPresets() {
this.presets = new LinkedHashMap<>();
this.presets = new Object2IntOpenHashMap<>();
this.loadPresets();
}

Expand Down Expand Up @@ -80,27 +80,27 @@ public void clear() {
this.presets.clear();
}

public Set<Map.Entry<String, Short>> entries() {
return this.presets.entrySet();
}

public boolean hasPreset(String name) {
return this.presets.containsKey(name);
}

public short getPreset(String name) {
return this.presets.getOrDefault(name, (short) 0);
public int getPreset(String name) {
return this.presets.getOrDefault(name, 0);
}

public void setPreset(String name, short value) {
this.presets.put(name, value);
savePresets();
}

public void forEach(BiConsumer<String, Short> consumer) {
public void forEach(BiConsumer<String, Integer> consumer) {
this.presets.forEach(consumer);
}

public boolean compare(Map<String, Integer> presets) {
return this.presets.equals(presets);
}

public int getPresetCount() {
return this.presets.size();
}
Expand Down

0 comments on commit ea4efb8

Please sign in to comment.