| 1 | package net.minecraft.client;
|
| 2 |
|
| 3 | import com.mojang.datafixers.DataFixer;
|
| 4 | import com.mojang.logging.LogUtils;
|
| 5 | import com.mojang.serialization.DataResult;
|
| 6 | import java.nio.file.Path;
|
| 7 | import net.fabricmc.api.EnvType;
|
| 8 | import net.fabricmc.api.Environment;
|
| 9 | import net.minecraft.client.player.inventory.Hotbar;
|
| 10 | import net.minecraft.nbt.CompoundTag;
|
| 11 | import net.minecraft.nbt.NbtIo;
|
| 12 | import net.minecraft.nbt.NbtOps;
|
| 13 | import net.minecraft.nbt.NbtUtils;
|
| 14 | import net.minecraft.nbt.Tag;
|
| 15 | import net.minecraft.util.datafix.DataFixTypes;
|
| 16 | import org.slf4j.Logger;
|
| 17 |
|
| 18 | @Environment(EnvType.CLIENT)
|
| 19 | public class HotbarManager {
|
| 20 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 21 | public static final int NUM_HOTBAR_GROUPS = 9;
|
| 22 | private final Path optionsFile;
|
| 23 | private final DataFixer fixerUpper;
|
| 24 | private final Hotbar[] hotbars = new Hotbar[9];
|
| 25 | private boolean loaded;
|
| 26 |
|
| 27 | public HotbarManager(final Path workingDirectory, final DataFixer fixerUpper) {
|
| 28 | this.optionsFile = workingDirectory.resolve("hotbar.nbt");
|
| 29 | this.fixerUpper = fixerUpper;
|
| 30 |
|
| 31 | for (int i = 0; i < 9; i++) {
|
| 32 | this.hotbars[i] = new Hotbar();
|
| 33 | }
|
| 34 | }
|
| 35 |
|
| 36 | private void load() {
|
| 37 | try {
|
| 38 | CompoundTag tag = NbtIo.read(this.optionsFile);
|
| 39 | if (tag == null) {
|
| 40 | return;
|
| 41 | }
|
| 42 |
|
| 43 | int version = NbtUtils.getDataVersion(tag, 1343);
|
| 44 | tag = DataFixTypes.HOTBAR.updateToCurrentVersion(this.fixerUpper, tag, version);
|
| 45 |
|
| 46 | for (int i = 0; i < 9; i++) {
|
| 47 | this.hotbars[i] = Hotbar.CODEC
|
| 48 | .parse(NbtOps.INSTANCE, tag.get(String.valueOf(i)))
|
| 49 | .resultOrPartial(error -> LOGGER.warn("Failed to parse hotbar: {}", error))
|
| 50 | .orElseGet(Hotbar::new);
|
| 51 | }
|
| 52 | } catch (Exception e) {
|
| 53 | LOGGER.error("Failed to load creative mode options", e);
|
| 54 | }
|
| 55 | }
|
| 56 |
|
| 57 | public void save() {
|
| 58 | try {
|
| 59 | CompoundTag tag = NbtUtils.addCurrentDataVersion(new CompoundTag());
|
| 60 |
|
| 61 | for (int i = 0; i < 9; i++) {
|
| 62 | Hotbar hotbar = this.get(i);
|
| 63 | DataResult<Tag> result = Hotbar.CODEC.encodeStart(NbtOps.INSTANCE, hotbar);
|
| 64 | tag.put(String.valueOf(i), result.getOrThrow());
|
| 65 | }
|
| 66 |
|
| 67 | NbtIo.write(tag, this.optionsFile);
|
| 68 | } catch (Exception e) {
|
| 69 | LOGGER.error("Failed to save creative mode options", e);
|
| 70 | }
|
| 71 | }
|
| 72 |
|
| 73 | public Hotbar get(final int id) {
|
| 74 | if (!this.loaded) {
|
| 75 | this.load();
|
| 76 | this.loaded = true;
|
| 77 | }
|
| 78 |
|
| 79 | return this.hotbars[id];
|
| 80 | }
|
| 81 | }
|
| 82 |
|